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
Account
Account.sol
0x2ed747ed395cfd40ff750fdfa351b229d67c8c01
Solidity
Account
contract Account { // The implementation of the proxy address public implementation; // Logic manager address public manager; // The enabled static calls mapping (bytes4 => address) public enabled; event EnabledStaticCall(address indexed module, bytes4 indexed method); event Invoked(address indexed module, address indexed target, uint indexed value, bytes data); event Received(uint indexed value, address indexed sender, bytes data); event AccountInit(address indexed account); event ManagerChanged(address indexed mgr); modifier allowAuthorizedLogicContractsCallsOnly { require(LogicManager(manager).isAuthorized(msg.sender), "not an authorized logic"); _; } function init(address _manager, address _accountStorage, address[] calldata _logics, address[] calldata _keys, address[] calldata _backups) external { require(manager == address(0), "Account: account already initialized"); require(_manager != address(0) && _accountStorage != address(0), "Account: address is null"); manager = _manager; for (uint i = 0; i < _logics.length; i++) { address logic = _logics[i]; require(LogicManager(manager).isAuthorized(logic), "must be authorized logic"); BaseLogic(logic).initAccount(this); } AccountStorage(_accountStorage).initAccount(this, _keys, _backups); emit AccountInit(address(this)); } function invoke(address _target, uint _value, bytes calldata _data) external allowAuthorizedLogicContractsCallsOnly returns (bytes memory _res) { bool success; // solium-disable-next-line security/no-call-value (success, _res) = _target.call.value(_value)(_data); require(success, "call to target failed"); emit Invoked(msg.sender, _target, _value, _data); } /** * @dev Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external allowAuthorizedLogicContractsCallsOnly { enabled[_method] = _module; emit EnabledStaticCall(_module, _method); } function changeManager(address _newMgr) external allowAuthorizedLogicContractsCallsOnly { require(_newMgr != address(0), "address cannot be null"); require(_newMgr != manager, "already changed"); manager = _newMgr; emit ManagerChanged(_newMgr); } /** * @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to * implement specific static methods. It delegates the static call to a target contract if the data corresponds * to an enabled method, or logs the call otherwise. */ function() external payable { if(msg.data.length > 0) { address logic = enabled[msg.sig]; if(logic == address(0)) { emit Received(msg.value, msg.sender, msg.data); } else { require(LogicManager(manager).isAuthorized(logic), "must be an authorized logic for static call"); // solium-disable-next-line security/no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas, logic, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } } } }
function() external payable { if(msg.data.length > 0) { address logic = enabled[msg.sig]; if(logic == address(0)) { emit Received(msg.value, msg.sender, msg.data); } else { require(LogicManager(manager).isAuthorized(logic), "must be an authorized logic for static call"); // solium-disable-next-line security/no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas, logic, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } } }
/** * @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to * implement specific static methods. It delegates the static call to a target contract if the data corresponds * to an enabled method, or logs the call otherwise. */
NatSpecMultiLine
v0.5.4+commit.9549d8ff
GNU GPLv3
bzzr://325ab23acf652cf963ee273c31a40feb195010aef23c1acf8f2f424fa1bd1a26
{ "func_code_index": [ 2999, 3875 ] }
2,800
Feed
Feed.sol
0xd9a19471e4c4e6766518f7a91a8e4237dead5647
Solidity
Feed
contract Feed is Owned { uint public basePrice=0.005 ether; uint public k=1; uint public showInterval=15; uint public totalMessages=0; struct Message { string content; uint date; address sender; uint price; uint show_date; uint rejected; string rejected_reason; } mapping (uint => Message) public messageInfo; /* events */ event Transfer(address indexed from, address indexed to, uint256 value); /* Initializes contract */ function Feed() { } function() public payable { submitMessage(""); } function queueCount() public returns (uint _count) { _count=0; for (uint i=totalMessages; i>0; i--) { if (messageInfo[i].show_date<(now-showInterval) && messageInfo[i].rejected==0) return _count; if (messageInfo[i].rejected==0) _count++; } return _count; } function currentMessage(uint _now) public returns ( uint _message_id, string _content, uint _show_date,uint _show_interval,uint _serverTime) { require(totalMessages>0); if (_now==0) _now=now; for (uint i=totalMessages; i>0; i--) { if (messageInfo[i].show_date>=(_now-showInterval) && messageInfo[i].show_date<_now && messageInfo[i].rejected==0) { //good if (messageInfo[i+1].show_date>0) _show_interval=messageInfo[i+1].show_date-messageInfo[i].show_date; else _show_interval=showInterval; return (i,messageInfo[i].content,messageInfo[i].show_date,_show_interval,_now); } if (messageInfo[i].show_date<(_now-showInterval)) throw; } throw; } function submitMessage(string _content) payable public returns(uint _message_id, uint _message_price, uint _queueCount) { require(msg.value>0); if (bytes(_content).length<1 || bytes(_content).length>150) throw; uint total=queueCount(); uint _last_Show_data=messageInfo[totalMessages].show_date; if (_last_Show_data==0) _last_Show_data=now+showInterval*2; else { if (_last_Show_data<(now-showInterval)) { _last_Show_data=_last_Show_data+(((now-_last_Show_data)/showInterval)+1)*showInterval; } else _last_Show_data=_last_Show_data+showInterval; } uint message_price=basePrice+basePrice*total*k; require(msg.value>=message_price); // add message totalMessages++; messageInfo[totalMessages].date=now; messageInfo[totalMessages].sender=msg.sender; messageInfo[totalMessages].content=_content; messageInfo[totalMessages].price=message_price; messageInfo[totalMessages].show_date=_last_Show_data; // refound if (msg.value>message_price) { uint cashback=msg.value-message_price; sendMoney(msg.sender,cashback); } return (totalMessages,message_price,(total+1)); } function sendMoney(address _address, uint _amount) internal { require(this.balance >= _amount); if (_address.send(_amount)) { Transfer(this,_address, _amount); } } function withdrawBenefit(address _address, uint _amount) onlyOwner public { sendMoney(_address,_amount); } function setBasePrice(uint _newprice) onlyOwner public returns(uint _basePrice) { require(_newprice>0); basePrice=_newprice; return basePrice; } function setShowInterval(uint _newinterval) onlyOwner public returns(uint _showInterval) { require(_newinterval>0); showInterval=_showInterval; return showInterval; } function setPriceCoeff(uint _new_k) onlyOwner public returns(uint _k) { require(_new_k>0); k=_new_k; return k; } function rejectMessage(uint _message_id, string _reason) onlyOwner public returns(uint _amount) { require(_message_id>0); require(bytes(messageInfo[_message_id].content).length > 0); require(messageInfo[_message_id].rejected==0); if (messageInfo[_message_id].show_date>=(now-showInterval) && messageInfo[_message_id].show_date<=now) throw; messageInfo[_message_id].rejected=1; messageInfo[_message_id].rejected_reason=_reason; if (messageInfo[_message_id].sender!= 0x0 && messageInfo[_message_id].price>0) { sendMoney(messageInfo[_message_id].sender,messageInfo[_message_id].price); return messageInfo[_message_id].price; } else throw; } }
Feed
function Feed() { }
/* Initializes contract */
Comment
v0.4.18+commit.9cf6e910
bzzr://c971029a674c166ab3f47256e27c53f417aef4b8d2dcf6c744ff32dc8d2be33f
{ "func_code_index": [ 573, 611 ] }
2,801
L1T
DividendPayingTokenInterface.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
DividendPayingTokenInterface
interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns(uint256); /// @notice Distributes ether to token holders as dividends. /// @dev SHOULD distribute the paid ether to token holders as dividends. /// SHOULD NOT directly transfer ether to token holders in this function. /// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0. function distributeDividends() external payable; /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed( address indexed from, uint256 weiAmount ); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn( address indexed to, uint256 weiAmount ); }
/// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract.
NatSpecSingleLine
dividendOf
function dividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw.
NatSpecSingleLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 247, 317 ] }
2,802
L1T
DividendPayingTokenInterface.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
DividendPayingTokenInterface
interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns(uint256); /// @notice Distributes ether to token holders as dividends. /// @dev SHOULD distribute the paid ether to token holders as dividends. /// SHOULD NOT directly transfer ether to token holders in this function. /// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0. function distributeDividends() external payable; /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed( address indexed from, uint256 weiAmount ); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn( address indexed to, uint256 weiAmount ); }
/// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract.
NatSpecSingleLine
distributeDividends
function distributeDividends() external payable;
/// @notice Distributes ether to token holders as dividends. /// @dev SHOULD distribute the paid ether to token holders as dividends. /// SHOULD NOT directly transfer ether to token holders in this function. /// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
NatSpecSingleLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 643, 694 ] }
2,803
L1T
DividendPayingTokenInterface.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
DividendPayingTokenInterface
interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns(uint256); /// @notice Distributes ether to token holders as dividends. /// @dev SHOULD distribute the paid ether to token holders as dividends. /// SHOULD NOT directly transfer ether to token holders in this function. /// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0. function distributeDividends() external payable; /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed( address indexed from, uint256 weiAmount ); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn( address indexed to, uint256 weiAmount ); }
/// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract.
NatSpecSingleLine
withdrawDividend
function withdrawDividend() external;
/// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
NatSpecSingleLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 994, 1034 ] }
2,804
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
committeeMembershipWillChange
function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external /* onlyCommitteeContract */;
/// 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": [ 1662, 1877 ] }
2,805
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
getFeesAndBootstrapBalance
function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 bootstrapBalance );
/// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @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": [ 2188, 2341 ] }
2,806
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
estimateFutureFeesAndBootstrapRewards
function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards );
/// 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": [ 2879, 3073 ] }
2,807
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
withdrawFees
function withdrawFees(address guardian) external;
/// 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": [ 3239, 3293 ] }
2,808
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
withdrawBootstrapFunds
function withdrawBootstrapFunds(address guardian) external;
/// 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": [ 3464, 3528 ] }
2,809
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
getFeesAndBootstrapState
function getFeesAndBootstrapState() external view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 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": [ 4292, 4564 ] }
2,810
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
getFeesAndBootstrapData
function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified );
/// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 5391, 5712 ] }
2,811
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
activateRewardDistribution
function activateRewardDistribution(uint startTime) external /* onlyInitializationAdmin */;
/// 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": [ 6667, 6763 ] }
2,812
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
deactivateRewardDistribution
function deactivateRewardDistribution() external /* onlyMigrationManager */;
/// 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": [ 6975, 7056 ] }
2,813
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
isRewardAllocationActive
function isRewardAllocationActive() external view returns (bool);
/// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 7182, 7252 ] }
2,814
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
setGeneralCommitteeAnnualBootstrap
function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external /* onlyFunctionalManager */;
/// 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": [ 7546, 7654 ] }
2,815
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
getGeneralCommitteeAnnualBootstrap
function getGeneralCommitteeAnnualBootstrap() external view returns (uint256);
/// 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": [ 7810, 7893 ] }
2,816
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
setCertifiedCommitteeAnnualBootstrap
function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external /* onlyFunctionalManager */;
/// 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": [ 8191, 8301 ] }
2,817
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
getCertifiedCommitteeAnnualBootstrap
function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256);
/// 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": [ 8475, 8560 ] }
2,818
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
migrateRewardsBalance
function migrateRewardsBalance(address[] calldata guardians) external;
/// 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": [ 8950, 9025 ] }
2,819
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
acceptRewardsBalanceMigration
function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external;
/// 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": [ 9700, 9875 ] }
2,820
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
emergencyWithdraw
function emergencyWithdraw(address erc20) external; /* onlyMigrationManager */
/// 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": [ 10170, 10253 ] }
2,821
FeesAndBootstrapRewards
contracts/spec_interfaces/IFeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
IFeesAndBootstrapRewards
interface IFeesAndBootstrapRewards { event FeesAllocated(uint256 allocatedGeneralFees, uint256 generalFeesPerMember, uint256 allocatedCertifiedFees, uint256 certifiedFeesPerMember); event FeesAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 feesPerMember); event FeesWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); event BootstrapRewardsAllocated(uint256 allocatedGeneralBootstrapRewards, uint256 generalBootstrapRewardsPerMember, uint256 allocatedCertifiedBootstrapRewards, uint256 certifiedBootstrapRewardsPerMember); event BootstrapRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, bool certification, uint256 bootstrapPerMember); event BootstrapRewardsWithdrawn(address indexed guardian, uint256 amount, uint256 totalWithdrawn); /* * 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 /* onlyCommitteeContract */; /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @param guardian is the guardian address /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external view returns ( uint256 feeBalance, uint256 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 view returns ( uint256 estimatedFees, uint256 estimatedBootstrapRewards ); /// 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; /// 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; /// 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 view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ); /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @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 /// @return withdrawnFees is the amount of fees withdrawn by the guardian /// @return withdrawnBootstrap is the amount of bootstrap reward withdrawn by the guardian /// @return certified is the current guardian certification state function getFeesAndBootstrapData(address guardian) external view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ); /* * Governance */ event GeneralCommitteeAnnualBootstrapChanged(uint256 generalCommitteeAnnualBootstrap); event CertifiedCommitteeAnnualBootstrapChanged(uint256 certifiedCommitteeAnnualBootstrap); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event FeesAndBootstrapRewardsBalanceMigrated(address indexed guardian, uint256 fees, uint256 bootstrapRewards, address toRewardsContract); event FeesAndBootstrapRewardsBalanceMigrationAccepted(address from, address indexed guardian, uint256 fees, uint256 bootstrapRewards); event EmergencyWithdrawal(address addr, address token); /// 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 /* onlyInitializationAdmin */; /// 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 /* onlyMigrationManager */; /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external view returns (bool); /// 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 /* onlyFunctionalManager */; /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external view returns (uint256); /// 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 /* onlyFunctionalManager */; /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external view returns (uint256); /// 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; /// 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; /// 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; /* onlyMigrationManager */ /// 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 view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ); }
/// @title Rewards contract interface
NatSpecSingleLine
getSettings
function getSettings() external view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool 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": [ 10585, 10777 ] }
2,822
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
stake
function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); }
/** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 3091, 3293 ] }
2,823
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
permitAndStake
function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); }
/** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 4046, 4504 ] }
2,824
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
unstake
function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } }
/** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 4749, 5843 ] }
2,825
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
delegate
function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; }
/** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 6005, 6873 ] }
2,826
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
undelegate
function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); }
/** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 7022, 7118 ] }
2,827
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
stakesNum
function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; }
/// @notice Returns number of stakes of given _account
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 7179, 7299 ] }
2,828
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
accountStakes
function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; }
/// @notice Returns stakes of given account
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 7349, 7543 ] }
2,829
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
totalVotingPower
function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; }
/// @inheritdoc IVotingPower
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 7578, 7757 ] }
2,830
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
totalPower
function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; }
/// @inheritdoc IVotingPower
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 7792, 7909 ] }
2,831
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
latestGlobalsSnapshotBlock
function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); }
/// @inheritdoc IVotingPower
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 7944, 8120 ] }
2,832
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
latestSnapshotBlock
function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; }
/// @inheritdoc IVotingPower
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 8155, 8424 ] }
2,833
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
globalsSnapshotLength
function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; }
/// @inheritdoc IVotingPower
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 8459, 8593 ] }
2,834
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
snapshotLength
function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; }
/// @inheritdoc IVotingPower
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 8628, 8801 ] }
2,835
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
globalsSnapshot
function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; }
/// @inheritdoc IVotingPower
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 8836, 9023 ] }
2,836
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
snapshot
function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; }
/// @inheritdoc IVotingPower
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 9058, 9250 ] }
2,837
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
globalSnapshotAt
function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); }
/// @inheritdoc IVotingPower
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 9285, 9499 ] }
2,838
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
snapshotAt
function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); }
/// @inheritdoc IVotingPower
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 9534, 9748 ] }
2,839
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
addTerms
function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); }
/// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER}
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 9890, 11322 ] }
2,840
Staking
contracts/Staking.sol
0xf4d06d72dacdd8393fa4ea72fdcc10049711f899
Solidity
Staking
contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } }
/** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */
NatSpecMultiLine
_createStake
function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; }
/// Internal and private functions follow
NatSpecSingleLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 11746, 14021 ] }
2,841
ERC20Token
ERC20Token.sol
0x0b9a61648331d3bf850182626db85281b8043126
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
totalSupply
function totalSupply() constant returns (uint256 supply) {}
/// @return total amount of tokens
NatSpecSingleLine
v0.4.26+commit.4563c3fc
None
bzzr://e4ac867551e5aa1a56cdbea2ea65df7ceb090e76eec83564adc4d5c7d1191e78
{ "func_code_index": [ 55, 116 ] }
2,842
ERC20Token
ERC20Token.sol
0x0b9a61648331d3bf850182626db85281b8043126
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @param _owner The address from which the balance will be retrieved /// @return The balance
NatSpecSingleLine
v0.4.26+commit.4563c3fc
None
bzzr://e4ac867551e5aa1a56cdbea2ea65df7ceb090e76eec83564adc4d5c7d1191e78
{ "func_code_index": [ 215, 289 ] }
2,843
ERC20Token
ERC20Token.sol
0x0b9a61648331d3bf850182626db85281b8043126
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transfer
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.26+commit.4563c3fc
None
bzzr://e4ac867551e5aa1a56cdbea2ea65df7ceb090e76eec83564adc4d5c7d1191e78
{ "func_code_index": [ 511, 585 ] }
2,844
ERC20Token
ERC20Token.sol
0x0b9a61648331d3bf850182626db85281b8043126
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.26+commit.4563c3fc
None
bzzr://e4ac867551e5aa1a56cdbea2ea65df7ceb090e76eec83564adc4d5c7d1191e78
{ "func_code_index": [ 890, 983 ] }
2,845
ERC20Token
ERC20Token.sol
0x0b9a61648331d3bf850182626db85281b8043126
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
approve
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not
NatSpecSingleLine
v0.4.26+commit.4563c3fc
None
bzzr://e4ac867551e5aa1a56cdbea2ea65df7ceb090e76eec83564adc4d5c7d1191e78
{ "func_code_index": [ 1252, 1330 ] }
2,846
ERC20Token
ERC20Token.sol
0x0b9a61648331d3bf850182626db85281b8043126
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
allowance
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
/// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent
NatSpecSingleLine
v0.4.26+commit.4563c3fc
None
bzzr://e4ac867551e5aa1a56cdbea2ea65df7ceb090e76eec83564adc4d5c7d1191e78
{ "func_code_index": [ 1526, 1620 ] }
2,847
ERC20Token
ERC20Token.sol
0x0b9a61648331d3bf850182626db85281b8043126
Solidity
ERC20Token
contract ERC20Token is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ string public name = "Rainbow Token"; //Name of the token uint8 public decimals = 18; //How many decimals to show. ie. There could 1000 base units with 3 decimals string public symbol ="RNBO"; //An identifier: eg AXM string public version = "H1.1"; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THE FOLLOWING VALUES FOR YOUR TOKEN! // //make sure this function name matches the contract name above. So if you’re token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function ERC20Token( ) { balances[msg.sender] = 450000000000000000000000000000000; // Give the creator all initial tokens (100000 for example) totalSupply = 900000000000000000000000000000000; // Update total supply (100000 for example) name = "Rainbow Token"; // Set the name for display purposes decimals = 18; // Amount of decimals symbol = "RNBO"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn’t have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
ERC20Token
function ERC20Token( ) { balances[msg.sender] = 450000000000000000000000000000000; // Give the creator all initial tokens (100000 for example) totalSupply = 900000000000000000000000000000000; // Update total supply (100000 for example) name = "Rainbow Token"; // Set the name for display purposes decimals = 18; // Amount of decimals symbol = "RNBO"; // Set the symbol for display purposes }
//human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THE FOLLOWING VALUES FOR YOUR TOKEN! // //make sure this function name matches the contract name above. So if you’re token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
LineComment
v0.4.26+commit.4563c3fc
None
bzzr://e4ac867551e5aa1a56cdbea2ea65df7ceb090e76eec83564adc4d5c7d1191e78
{ "func_code_index": [ 718, 1124 ] }
2,848
ERC20Token
ERC20Token.sol
0x0b9a61648331d3bf850182626db85281b8043126
Solidity
ERC20Token
contract ERC20Token is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ string public name = "Rainbow Token"; //Name of the token uint8 public decimals = 18; //How many decimals to show. ie. There could 1000 base units with 3 decimals string public symbol ="RNBO"; //An identifier: eg AXM string public version = "H1.1"; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THE FOLLOWING VALUES FOR YOUR TOKEN! // //make sure this function name matches the contract name above. So if you’re token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function ERC20Token( ) { balances[msg.sender] = 450000000000000000000000000000000; // Give the creator all initial tokens (100000 for example) totalSupply = 900000000000000000000000000000000; // Update total supply (100000 for example) name = "Rainbow Token"; // Set the name for display purposes decimals = 18; // Amount of decimals symbol = "RNBO"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn’t have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); /call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn’t have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; }
/* Approves and then calls the receiving contract */
Comment
v0.4.26+commit.4563c3fc
None
bzzr://e4ac867551e5aa1a56cdbea2ea65df7ceb090e76eec83564adc4d5c7d1191e78
{ "func_code_index": [ 1179, 1926 ] }
2,849
UNOS_Lock_Dec
UNOS_Lock_Dec.sol
0x30e950918b96bb0e870a3c9c05c983606abb2030
Solidity
UNOS_Lock_Dec
contract UNOS_Lock_Dec is Ownable { using SafeMath for uint; address public constant tokenAddress = 0xd18A8abED9274eDBEace4B12D86A8633283435Da; uint public constant tokensLocked = 13860e18; // 13860 UNOS uint public constant unlockRate = 13860; // Unlock Date: 20 December 2020 uint public constant lockDuration = 60 days; // Before 60 Days, Its impossible to unlock... uint public lastClaimedTime; uint public deployTime; constructor() public { deployTime = now; lastClaimedTime = now; } function claim() public onlyOwner { uint pendingUnlocked = getPendingUnlocked(); uint contractBalance = UNOS(tokenAddress).balanceOf(address(this)); uint amountToSend = pendingUnlocked; if (contractBalance < pendingUnlocked) { amountToSend = contractBalance; } require(UNOS(tokenAddress).transfer(owner, amountToSend), "Could not transfer Tokens."); lastClaimedTime = now; } function getPendingUnlocked() public view returns (uint) { uint timeDiff = now.sub(lastClaimedTime); uint pendingUnlocked = tokensLocked .mul(unlockRate) .mul(timeDiff) .div(lockDuration) .div(1e4); return pendingUnlocked; } // function to allow admin to claim *other than UNOS* ERC20 tokens sent to this contract (by mistake) like USDT // UNOS can't be unlocked untill 20 Dec 2020 function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { require(_tokenAddr != tokenAddress, "Cannot transfer out reward tokens"); UNOS(_tokenAddr).transfer(_to, _amount); } }
transferAnyERC20Tokens
function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { require(_tokenAddr != tokenAddress, "Cannot transfer out reward tokens"); UNOS(_tokenAddr).transfer(_to, _amount); }
// function to allow admin to claim *other than UNOS* ERC20 tokens sent to this contract (by mistake) like USDT // UNOS can't be unlocked untill 20 Dec 2020
LineComment
v0.6.12+commit.27d51765
None
ipfs://fdb2342747b41ff7a75384087edbb5fb2c3195f06507a4da1014fd78c23d01c2
{ "func_code_index": [ 1659, 1901 ] }
2,850
DAO
contracts/DAO.sol
0x5b1b8bdbcc534b17e9f8e03a3308172c7657f4a3
Solidity
DAO
contract DAO { struct Proposal { uint id; address proposer; string title; string description; string[] optionsNames; bytes[][] optionsActions; uint[] optionsVotes; uint startAt; uint endAt; uint executableAt; uint executedAt; uint snapshotId; uint votersSupply; bool cancelled; } event Proposed(uint indexed proposalId); event Voted(uint indexed proposalId, address indexed voter, uint optionId); event Executed(address indexed to, uint value, bytes data); event ExecutedProposal(uint indexed proposalId, uint optionId, address executer); bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint optionId)"); uint public minBalanceToPropose; uint public minPercentQuorum; uint public minVotingTime; uint public minExecutionDelay; IVoters public voters; uint public proposalsCount; mapping(uint => Proposal) private proposals; mapping(uint => mapping(address => uint)) public proposalVotes; mapping (address => uint) private latestProposalIds; constructor( address _voters, uint _minBalanceToPropose, uint _minPercentQuorum, uint _minVotingTime, uint _minExecutionDelay ) { voters = IVoters(_voters); minBalanceToPropose = _minBalanceToPropose; minPercentQuorum = _minPercentQuorum; minVotingTime = _minVotingTime; minExecutionDelay = _minExecutionDelay; } function proposal(uint index) public view returns (uint, address, string memory, uint, uint, uint, uint, bool) { Proposal storage p = proposals[index]; return ( p.id, p.proposer, p.title, p.startAt, p.endAt, p.executableAt, p.executedAt, p.cancelled ); } function proposalDetails(uint index) public view returns (string memory, uint, uint, string[] memory, bytes[][] memory, uint[] memory) { return ( proposals[index].description, proposals[index].snapshotId, proposals[index].votersSupply, proposals[index].optionsNames, proposals[index].optionsActions, proposals[index].optionsVotes ); } function propose(string calldata title, string calldata description, uint votingTime, uint executionDelay, string[] calldata optionNames, bytes[][] memory optionActions) external returns (uint) { uint snapshotId = voters.snapshot(); require(voters.votesAt(msg.sender, snapshotId) >= minBalanceToPropose, "<balance"); require(optionNames.length == optionActions.length && optionNames.length > 0 && optionNames.length <= 100, "option len match or count"); require(optionActions[optionActions.length - 1].length == 0, "last option, no action"); require(votingTime >= minVotingTime, "<voting time"); require(executionDelay >= minExecutionDelay, "<exec delay"); // Check the proposing address doesn't have an other active proposal uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { require(block.timestamp > proposals[latestProposalId].endAt, "1 live proposal max"); } // Add new proposal proposalsCount += 1; Proposal storage newProposal = proposals[proposalsCount]; newProposal.id = proposalsCount; newProposal.proposer = msg.sender; newProposal.title = title; newProposal.description = description; newProposal.startAt = block.timestamp + 86400; newProposal.endAt = block.timestamp + 86400 + votingTime; newProposal.executableAt = block.timestamp + 86400 + votingTime + executionDelay; newProposal.snapshotId = snapshotId; newProposal.votersSupply = voters.totalSupplyAt(snapshotId); newProposal.optionsNames = new string[](optionNames.length); newProposal.optionsVotes = new uint[](optionNames.length); newProposal.optionsActions = optionActions; for (uint i = 0; i < optionNames.length; i++) { require(optionActions[i].length <= 10, "actions length > 10"); newProposal.optionsNames[i] = optionNames[i]; } latestProposalIds[msg.sender] = newProposal.id; emit Proposed(newProposal.id); return newProposal.id; } function proposeCancel(uint proposalId, string memory title, string memory description) external returns (uint) { uint snapshotId = voters.snapshot(); require(voters.votesAt(msg.sender, snapshotId) >= minBalanceToPropose, "<balance"); // Check the proposing address doesn't have an other active proposal uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { require(block.timestamp > proposals[latestProposalId].endAt, "1 live proposal max"); } // Add new proposal proposalsCount += 1; Proposal storage newProposal = proposals[proposalsCount]; newProposal.id = proposalsCount; newProposal.proposer = msg.sender; newProposal.title = title; newProposal.description = description; newProposal.startAt = block.timestamp; newProposal.endAt = block.timestamp + 86400; // 24 hours newProposal.executableAt = block.timestamp + 86400; // Executable immediately newProposal.snapshotId = snapshotId; newProposal.votersSupply = voters.totalSupplyAt(snapshotId); newProposal.optionsNames = new string[](2); newProposal.optionsVotes = new uint[](2); newProposal.optionsActions = new bytes[][](2); newProposal.optionsNames[0] = "Cancel Proposal"; newProposal.optionsNames[1] = "Do Nothing"; newProposal.optionsActions[0] = new bytes[](1); newProposal.optionsActions[1] = new bytes[](0); newProposal.optionsActions[0][0] = abi.encode( address(this), 0, abi.encodeWithSignature("cancel(uint256)", proposalId) ); latestProposalIds[msg.sender] = newProposal.id; emit Proposed(newProposal.id); return newProposal.id; } function vote(uint proposalId, uint optionId) external { _vote(msg.sender, proposalId, optionId); } function voteBySig(uint proposalId, uint optionId, uint8 v, bytes32 r, bytes32 s) external { uint chainId; assembly { chainId := chainid() } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes("Thorstarter DAO")), chainId, address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, optionId)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address voter = ecrecover(digest, v, r, s); require(voter != address(0), "invalid signature"); _vote(voter, proposalId, optionId); } function _vote(address voter, uint proposalId, uint optionId) private { Proposal storage p = proposals[proposalId]; require(block.timestamp < p.endAt, "voting ended"); require(proposalVotes[proposalId][voter] == 0, "already voted"); p.optionsVotes[optionId] = p.optionsVotes[optionId] + voters.votesAt(voter, p.snapshotId); proposalVotes[proposalId][voter] = optionId + 1; emit Voted(proposalId, voter, optionId); } // Executes an un-executed, with quorum, ready to be executed proposal // If the pre-conditions are met, anybody can call this // Part of this is establishing which option "won" and if quorum was reached function execute(uint proposalId) external { Proposal storage p = proposals[proposalId]; require(p.executedAt == 0, "already executed"); require(block.timestamp > p.executableAt, "not yet executable"); require(!p.cancelled, "proposal cancelled"); require(p.optionsVotes.length >= 2, "not a proposal"); p.executedAt = block.timestamp; // Mark as executed now to prevent re-entrancy // Pick the winning option (the one with the most votes, defaulting to the "Against" (last) option uint votesTotal; uint winningOptionIndex = p.optionsNames.length - 1; // Default to "Against" uint winningOptionVotes = 0; for (int i = int(p.optionsVotes.length) - 1; i >= 0; i--) { uint votes = p.optionsVotes[uint(i)]; votesTotal = votesTotal + votes; // Use greater than (not equal) to avoid a proposal with 0 votes // to default to the 1st option if (votes > winningOptionVotes) { winningOptionIndex = uint(i); winningOptionVotes = votes; } } require((votesTotal * 1e12) / p.votersSupply > minPercentQuorum, "not at quorum"); // Run all actions attached to the winning option for (uint i = 0; i < p.optionsActions[winningOptionIndex].length; i++) { (address to, uint value, bytes memory data) = abi.decode( p.optionsActions[winningOptionIndex][i], (address, uint, bytes) ); (bool success,) = to.call{value: value}(data); require(success, "action reverted"); emit Executed(to, value, data); } emit ExecutedProposal(proposalId, winningOptionIndex, msg.sender); } function setMinBalanceToPropose(uint value) external { require(msg.sender == address(this), "!DAO"); minBalanceToPropose = value; } function setMinPercentQuorum(uint value) external { require(msg.sender == address(this), "!DAO"); minPercentQuorum = value; } function setMinVotingTime(uint value) external { require(msg.sender == address(this), "!DAO"); minVotingTime = value; } function setMinExecutionDelay(uint value) external { require(msg.sender == address(this), "!DAO"); minExecutionDelay = value; } function setVoters(address newVoters) external { require(msg.sender == address(this), "!DAO"); voters = IVoters(newVoters); } function cancel(uint proposalId) external { require(msg.sender == address(this), "!DAO"); Proposal storage p = proposals[proposalId]; require(p.executedAt == 0 && !p.cancelled, "already executed or cancelled"); p.cancelled = true; } fallback() external payable { } }
execute
function execute(uint proposalId) external { Proposal storage p = proposals[proposalId]; require(p.executedAt == 0, "already executed"); require(block.timestamp > p.executableAt, "not yet executable"); require(!p.cancelled, "proposal cancelled"); require(p.optionsVotes.length >= 2, "not a proposal"); p.executedAt = block.timestamp; // Mark as executed now to prevent re-entrancy // Pick the winning option (the one with the most votes, defaulting to the "Against" (last) option uint votesTotal; uint winningOptionIndex = p.optionsNames.length - 1; // Default to "Against" uint winningOptionVotes = 0; for (int i = int(p.optionsVotes.length) - 1; i >= 0; i--) { uint votes = p.optionsVotes[uint(i)]; votesTotal = votesTotal + votes; // Use greater than (not equal) to avoid a proposal with 0 votes // to default to the 1st option if (votes > winningOptionVotes) { winningOptionIndex = uint(i); winningOptionVotes = votes; } } require((votesTotal * 1e12) / p.votersSupply > minPercentQuorum, "not at quorum"); // Run all actions attached to the winning option for (uint i = 0; i < p.optionsActions[winningOptionIndex].length; i++) { (address to, uint value, bytes memory data) = abi.decode( p.optionsActions[winningOptionIndex][i], (address, uint, bytes) ); (bool success,) = to.call{value: value}(data); require(success, "action reverted"); emit Executed(to, value, data); } emit ExecutedProposal(proposalId, winningOptionIndex, msg.sender); }
// Executes an un-executed, with quorum, ready to be executed proposal // If the pre-conditions are met, anybody can call this // Part of this is establishing which option "won" and if quorum was reached
LineComment
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 7860, 9644 ] }
2,851
TokenController
contracts/ReclaimerToken.sol
0x30ae713c785672b7e7601e3253d043d9d22937c9
Solidity
ReclaimerToken
contract ReclaimerToken is HasOwner { /** *@dev send all eth balance in the contract to another address */ function reclaimEther(address payable _to) external onlyOwner { _to.transfer(address(this).balance); } /** *@dev send all token balance of an arbitary erc20 token in the contract to another address */ function reclaimToken(ERC20 token, address _to) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(_to, balance); } /** *@dev allows owner of the contract to gain ownership of any contract that the contract currently owns */ function reclaimContract(Ownable _ownable) external onlyOwner { _ownable.transferOwnership(owner); } }
reclaimEther
function reclaimEther(address payable _to) external onlyOwner { _to.transfer(address(this).balance); }
/** *@dev send all eth balance in the contract to another address */
NatSpecMultiLine
v0.5.8+commit.23d335f2
bzzr://9ce83a31bede9c87f6525cf84de5aa8be1bd414901fa9945612925767de18213
{ "func_code_index": [ 125, 246 ] }
2,852
TokenController
contracts/ReclaimerToken.sol
0x30ae713c785672b7e7601e3253d043d9d22937c9
Solidity
ReclaimerToken
contract ReclaimerToken is HasOwner { /** *@dev send all eth balance in the contract to another address */ function reclaimEther(address payable _to) external onlyOwner { _to.transfer(address(this).balance); } /** *@dev send all token balance of an arbitary erc20 token in the contract to another address */ function reclaimToken(ERC20 token, address _to) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(_to, balance); } /** *@dev allows owner of the contract to gain ownership of any contract that the contract currently owns */ function reclaimContract(Ownable _ownable) external onlyOwner { _ownable.transferOwnership(owner); } }
reclaimToken
function reclaimToken(ERC20 token, address _to) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(_to, balance); }
/** *@dev send all token balance of an arbitary erc20 token in the contract to another address */
NatSpecMultiLine
v0.5.8+commit.23d335f2
bzzr://9ce83a31bede9c87f6525cf84de5aa8be1bd414901fa9945612925767de18213
{ "func_code_index": [ 369, 547 ] }
2,853
TokenController
contracts/ReclaimerToken.sol
0x30ae713c785672b7e7601e3253d043d9d22937c9
Solidity
ReclaimerToken
contract ReclaimerToken is HasOwner { /** *@dev send all eth balance in the contract to another address */ function reclaimEther(address payable _to) external onlyOwner { _to.transfer(address(this).balance); } /** *@dev send all token balance of an arbitary erc20 token in the contract to another address */ function reclaimToken(ERC20 token, address _to) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(_to, balance); } /** *@dev allows owner of the contract to gain ownership of any contract that the contract currently owns */ function reclaimContract(Ownable _ownable) external onlyOwner { _ownable.transferOwnership(owner); } }
reclaimContract
function reclaimContract(Ownable _ownable) external onlyOwner { _ownable.transferOwnership(owner); }
/** *@dev allows owner of the contract to gain ownership of any contract that the contract currently owns */
NatSpecMultiLine
v0.5.8+commit.23d335f2
bzzr://9ce83a31bede9c87f6525cf84de5aa8be1bd414901fa9945612925767de18213
{ "func_code_index": [ 676, 795 ] }
2,854
L1T
Ownable.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
owner
function owner() public view returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 488, 572 ] }
2,855
L1T
Ownable.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
renounceOwnership
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 1130, 1283 ] }
2,856
L1T
Ownable.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
transferOwnership
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 1433, 1682 ] }
2,857
L1T
SafeMath.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
/** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 259, 445 ] }
2,858
L1T
SafeMath.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); }
/** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 723, 864 ] }
2,859
L1T
SafeMath.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
sub
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; }
/** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 1162, 1359 ] }
2,860
L1T
SafeMath.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
/** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 1613, 2089 ] }
2,861
L1T
SafeMath.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); }
/** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 2560, 2697 ] }
2,862
L1T
SafeMath.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
div
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 3188, 3471 ] }
2,863
L1T
SafeMath.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 3931, 4066 ] }
2,864
L1T
SafeMath.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
mod
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 4546, 4717 ] }
2,865
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
DSMath
contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } }
rpow
function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } }
// This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. //
LineComment
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 2015, 2307 ] }
2,866
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
DSTokenBase
contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint) { return _supply; } /** * @dev Gets the balance of the specified address. * @param src The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address src) public view returns (uint) { return _balances[src]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param src address The address which owns the funds. * @param guy address The address which will spend the funds. */ function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } /** * @dev Transfer token for a specified address * @param dst The address to transfer to. * @param wad The amount to be transferred. */ function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } /** * @dev Transfer tokens from one address to another * @param src address The address which you want to send tokens from * @param dst address The address which you want to transfer to * @param wad uint256 the amount of tokens to be transferred */ function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param guy The address which will spend the funds. * @param wad The amount of tokens to be spent. */ function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function increaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = add(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } /** * @dev Decrese the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function decreaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } }
totalSupply
function totalSupply() public view returns (uint) { return _supply; }
/** * @dev Total number of tokens in existence */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 443, 535 ] }
2,867
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
DSTokenBase
contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint) { return _supply; } /** * @dev Gets the balance of the specified address. * @param src The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address src) public view returns (uint) { return _balances[src]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param src address The address which owns the funds. * @param guy address The address which will spend the funds. */ function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } /** * @dev Transfer token for a specified address * @param dst The address to transfer to. * @param wad The amount to be transferred. */ function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } /** * @dev Transfer tokens from one address to another * @param src address The address which you want to send tokens from * @param dst address The address which you want to transfer to * @param wad uint256 the amount of tokens to be transferred */ function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param guy The address which will spend the funds. * @param wad The amount of tokens to be spent. */ function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function increaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = add(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } /** * @dev Decrese the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function decreaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } }
balanceOf
function balanceOf(address src) public view returns (uint) { return _balances[src]; }
/** * @dev Gets the balance of the specified address. * @param src The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 751, 859 ] }
2,868
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
DSTokenBase
contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint) { return _supply; } /** * @dev Gets the balance of the specified address. * @param src The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address src) public view returns (uint) { return _balances[src]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param src address The address which owns the funds. * @param guy address The address which will spend the funds. */ function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } /** * @dev Transfer token for a specified address * @param dst The address to transfer to. * @param wad The amount to be transferred. */ function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } /** * @dev Transfer tokens from one address to another * @param src address The address which you want to send tokens from * @param dst address The address which you want to transfer to * @param wad uint256 the amount of tokens to be transferred */ function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param guy The address which will spend the funds. * @param wad The amount of tokens to be spent. */ function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function increaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = add(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } /** * @dev Decrese the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function decreaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } }
allowance
function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; }
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param src address The address which owns the funds. * @param guy address The address which will spend the funds. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 1099, 1226 ] }
2,869
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
DSTokenBase
contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint) { return _supply; } /** * @dev Gets the balance of the specified address. * @param src The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address src) public view returns (uint) { return _balances[src]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param src address The address which owns the funds. * @param guy address The address which will spend the funds. */ function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } /** * @dev Transfer token for a specified address * @param dst The address to transfer to. * @param wad The amount to be transferred. */ function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } /** * @dev Transfer tokens from one address to another * @param src address The address which you want to send tokens from * @param dst address The address which you want to transfer to * @param wad uint256 the amount of tokens to be transferred */ function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param guy The address which will spend the funds. * @param wad The amount of tokens to be spent. */ function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function increaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = add(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } /** * @dev Decrese the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function decreaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } }
transfer
function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); }
/** * @dev Transfer token for a specified address * @param dst The address to transfer to. * @param wad The amount to be transferred. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 1403, 1535 ] }
2,870
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
DSTokenBase
contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint) { return _supply; } /** * @dev Gets the balance of the specified address. * @param src The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address src) public view returns (uint) { return _balances[src]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param src address The address which owns the funds. * @param guy address The address which will spend the funds. */ function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } /** * @dev Transfer token for a specified address * @param dst The address to transfer to. * @param wad The amount to be transferred. */ function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } /** * @dev Transfer tokens from one address to another * @param src address The address which you want to send tokens from * @param dst address The address which you want to transfer to * @param wad uint256 the amount of tokens to be transferred */ function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param guy The address which will spend the funds. * @param wad The amount of tokens to be spent. */ function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function increaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = add(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } /** * @dev Decrese the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function decreaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } }
transferFrom
function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; }
/** * @dev Transfer tokens from one address to another * @param src address The address which you want to send tokens from * @param dst address The address which you want to transfer to * @param wad uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 1829, 2271 ] }
2,871
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
DSTokenBase
contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint) { return _supply; } /** * @dev Gets the balance of the specified address. * @param src The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address src) public view returns (uint) { return _balances[src]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param src address The address which owns the funds. * @param guy address The address which will spend the funds. */ function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } /** * @dev Transfer token for a specified address * @param dst The address to transfer to. * @param wad The amount to be transferred. */ function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } /** * @dev Transfer tokens from one address to another * @param src address The address which you want to send tokens from * @param dst address The address which you want to transfer to * @param wad uint256 the amount of tokens to be transferred */ function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param guy The address which will spend the funds. * @param wad The amount of tokens to be spent. */ function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function increaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = add(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } /** * @dev Decrese the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function decreaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } }
approve
function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param guy The address which will spend the funds. * @param wad The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 2918, 3121 ] }
2,872
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
DSTokenBase
contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint) { return _supply; } /** * @dev Gets the balance of the specified address. * @param src The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address src) public view returns (uint) { return _balances[src]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param src address The address which owns the funds. * @param guy address The address which will spend the funds. */ function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } /** * @dev Transfer token for a specified address * @param dst The address to transfer to. * @param wad The amount to be transferred. */ function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } /** * @dev Transfer tokens from one address to another * @param src address The address which you want to send tokens from * @param dst address The address which you want to transfer to * @param wad uint256 the amount of tokens to be transferred */ function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param guy The address which will spend the funds. * @param wad The amount of tokens to be spent. */ function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function increaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = add(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } /** * @dev Decrese the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function decreaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } }
increaseAllowance
function increaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = add(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; }
/** * @dev Increase the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 3590, 3919 ] }
2,873
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
DSTokenBase
contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint) { return _supply; } /** * @dev Gets the balance of the specified address. * @param src The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address src) public view returns (uint) { return _balances[src]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param src address The address which owns the funds. * @param guy address The address which will spend the funds. */ function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } /** * @dev Transfer token for a specified address * @param dst The address to transfer to. * @param wad The amount to be transferred. */ function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } /** * @dev Transfer tokens from one address to another * @param src address The address which you want to send tokens from * @param dst address The address which you want to transfer to * @param wad uint256 the amount of tokens to be transferred */ function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param guy The address which will spend the funds. * @param wad The amount of tokens to be spent. */ function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function increaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = add(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } /** * @dev Decrese the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */ function decreaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; } }
decreaseAllowance
function decreaseAllowance( address src, uint256 wad ) public returns (bool) { require(src != address(0)); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); emit Approval(msg.sender, src, _approvals[msg.sender][src]); return true; }
/** * @dev Decrese the amount of tokens that an owner allowed to a 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 * @param src The address which will spend the funds. * @param wad The amount of tokens to increase the allowance by. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 4387, 4712 ] }
2,874
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
ZDTToken
contract ZDTToken is DSTokenBase , DSStop { string public symbol="ZDT"; string public name="Zenoshi Dividend Token"; uint256 public decimals = 8; // Token Precision every token is 1.00000000 uint256 public initialSupply=90000000000000000;// 900000000+8 zeros for decimals address public burnAdmin; constructor() public DSTokenBase(initialSupply) { burnAdmin=msg.sender; } event Burn(address indexed guy, uint wad); /** * @dev Throws if called by any account other than the owner. */ modifier onlyAdmin() { require(isAdmin()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isAdmin() public view returns(bool) { return msg.sender == burnAdmin; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyAdmin { burnAdmin = address(0); } function approve(address guy) public stoppable returns (bool) { return super.approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { return super.approve(guy, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } /** * @dev Burns a specific amount of tokens from the target address * @param guy address The address which you want to send tokens from * @param wad uint256 The amount of token to be burned */ function burnfromAdmin(address guy, uint wad) public onlyAdmin { require(guy != address(0)); _balances[guy] = sub(_balances[guy], wad); _supply = sub(_supply, wad); emit Burn(guy, wad); emit Transfer(guy, address(0), wad); } }
isAdmin
function isAdmin() public view returns(bool) { return msg.sender == burnAdmin;
/** * @return true if `msg.sender` is the owner of the contract. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 762, 855 ] }
2,875
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
ZDTToken
contract ZDTToken is DSTokenBase , DSStop { string public symbol="ZDT"; string public name="Zenoshi Dividend Token"; uint256 public decimals = 8; // Token Precision every token is 1.00000000 uint256 public initialSupply=90000000000000000;// 900000000+8 zeros for decimals address public burnAdmin; constructor() public DSTokenBase(initialSupply) { burnAdmin=msg.sender; } event Burn(address indexed guy, uint wad); /** * @dev Throws if called by any account other than the owner. */ modifier onlyAdmin() { require(isAdmin()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isAdmin() public view returns(bool) { return msg.sender == burnAdmin; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyAdmin { burnAdmin = address(0); } function approve(address guy) public stoppable returns (bool) { return super.approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { return super.approve(guy, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } /** * @dev Burns a specific amount of tokens from the target address * @param guy address The address which you want to send tokens from * @param wad uint256 The amount of token to be burned */ function burnfromAdmin(address guy, uint wad) public onlyAdmin { require(guy != address(0)); _balances[guy] = sub(_balances[guy], wad); _supply = sub(_supply, wad); emit Burn(guy, wad); emit Transfer(guy, address(0), wad); } }
renounceOwnership
function renounceOwnership() public onlyAdmin { burnAdmin = address(0); }
/** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 1138, 1226 ] }
2,876
ZDTToken
ZDTToken.sol
0xefdee3d0d1bb99714fe9049d21006a4e46519936
Solidity
ZDTToken
contract ZDTToken is DSTokenBase , DSStop { string public symbol="ZDT"; string public name="Zenoshi Dividend Token"; uint256 public decimals = 8; // Token Precision every token is 1.00000000 uint256 public initialSupply=90000000000000000;// 900000000+8 zeros for decimals address public burnAdmin; constructor() public DSTokenBase(initialSupply) { burnAdmin=msg.sender; } event Burn(address indexed guy, uint wad); /** * @dev Throws if called by any account other than the owner. */ modifier onlyAdmin() { require(isAdmin()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isAdmin() public view returns(bool) { return msg.sender == burnAdmin; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyAdmin { burnAdmin = address(0); } function approve(address guy) public stoppable returns (bool) { return super.approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { return super.approve(guy, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } /** * @dev Burns a specific amount of tokens from the target address * @param guy address The address which you want to send tokens from * @param wad uint256 The amount of token to be burned */ function burnfromAdmin(address guy, uint wad) public onlyAdmin { require(guy != address(0)); _balances[guy] = sub(_balances[guy], wad); _supply = sub(_supply, wad); emit Burn(guy, wad); emit Transfer(guy, address(0), wad); } }
burnfromAdmin
function burnfromAdmin(address guy, uint wad) public onlyAdmin { require(guy != address(0)); _balances[guy] = sub(_balances[guy], wad); _supply = sub(_supply, wad); emit Burn(guy, wad); emit Transfer(guy, address(0), wad); }
/** * @dev Burns a specific amount of tokens from the target address * @param guy address The address which you want to send tokens from * @param wad uint256 The amount of token to be burned */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://701f272bd3b46d47a8d90168b75fa5e2170afa2c1d22d49a97623dbaae4e9244
{ "func_code_index": [ 2248, 2551 ] }
2,877
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
name
function name() public view virtual override returns (string memory) { return _name; }
/** * @dev Returns the name of the token. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 811, 916 ] }
2,878
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
symbol
function symbol() public view virtual override returns (string memory) { return _symbol; }
/** * @dev Returns the symbol of the token, usually a shorter version of the * name. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 1030, 1139 ] }
2,879
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
decimals
function decimals() public view virtual override returns (uint8) { return 9; }
/** * @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 this function is * overridden; * * 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.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 1773, 1870 ] }
2,880
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
totalSupply
function totalSupply() public view virtual override returns (uint256) { return _totalSupply; }
/** * @dev See {IERC20-totalSupply}. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 1930, 2043 ] }
2,881
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
balanceOf
function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; }
/** * @dev See {IERC20-balanceOf}. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 2101, 2233 ] }
2,882
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
transfer
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; }
/** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 2441, 2621 ] }
2,883
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
allowance
function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; }
/** * @dev See {IERC20-allowance}. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 2679, 2835 ] }
2,884
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
approve
function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; }
/** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 2977, 3151 ] }
2,885
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
transferFrom
function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
/** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 3628, 3988 ] }
2,886
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; }
/** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 4392, 4615 ] }
2,887
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; }
/** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 5113, 5387 ] }
2,888
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_transfer
function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
/** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 5872, 6450 ] }
2,889
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_mint
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
/** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 6732, 7115 ] }
2,890
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_burn
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); }
/** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 7443, 7866 ] }
2,891
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_approve
function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
/** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 8299, 8684 ] }
2,892
L1T
ERC20.sol
0x30baadb0c58a913934082962512c1aab1e596fef
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 this function is * overridden; * * 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 virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_beforeTokenTransfer
function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {}
/** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
None
ipfs://3844a6bb64018c5bf46b0fc297e23eb78ce92a407938a1df7234e39eea24dc5a
{ "func_code_index": [ 9282, 9412 ] }
2,893
OptionsPool
contracts/interfaces/IERC20Nameable.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
IERC20Nameable
interface IERC20Nameable is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @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() external view returns (uint8); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
name
function name() external view returns (string memory);
/** * @dev Returns the name of the token. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 96, 154 ] }
2,894
OptionsPool
contracts/interfaces/IERC20Nameable.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
IERC20Nameable
interface IERC20Nameable is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @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() external view returns (uint8); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
symbol
function symbol() external view returns (string memory);
/** * @dev Returns the symbol of the token, usually a shorter version of the * name. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 263, 323 ] }
2,895
OptionsPool
contracts/interfaces/IERC20Nameable.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
IERC20Nameable
interface IERC20Nameable is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @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() external view returns (uint8); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
decimals
function decimals() external view returns (uint8);
/** * @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": [ 942, 996 ] }
2,896
MthereumToken
MthereumToken.sol
0x7dd23f3aefcad5b4a1cd7d4d4e77bdc487b52580
Solidity
MthereumToken
contract MthereumToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function MthereumToken() public { symbol = "MTE"; name = "Mthereum"; decimals = 8; _totalSupply = 10000000000000000; balances[0x7aF7ff854a80ba5dd8aB247208918c58A319B904] = _totalSupply; Transfer(address(0), 0x7aF7ff854a80ba5dd8aB247208918c58A319B904, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
balanceOf
function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; }
// ------------------------------------------------------------------------
LineComment
v0.4.19+commit.c4cbbb05
bzzr://f7c5729c6f5712d0043eeafbaab35b7a0217852ed19c0cc65c1ff416977f755a
{ "func_code_index": [ 818, 947 ] }
2,897
MthereumToken
MthereumToken.sol
0x7dd23f3aefcad5b4a1cd7d4d4e77bdc487b52580
Solidity
MthereumToken
contract MthereumToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function MthereumToken() public { symbol = "MTE"; name = "Mthereum"; decimals = 8; _totalSupply = 10000000000000000; balances[0x7aF7ff854a80ba5dd8aB247208918c58A319B904] = _totalSupply; Transfer(address(0), 0x7aF7ff854a80ba5dd8aB247208918c58A319B904, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
allowance
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; }
// ------------------------------------------------------------------------
LineComment
v0.4.19+commit.c4cbbb05
bzzr://f7c5729c6f5712d0043eeafbaab35b7a0217852ed19c0cc65c1ff416977f755a
{ "func_code_index": [ 1881, 2037 ] }
2,898
MthereumToken
MthereumToken.sol
0x7dd23f3aefcad5b4a1cd7d4d4e77bdc487b52580
Solidity
MthereumToken
contract MthereumToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function MthereumToken() public { symbol = "MTE"; name = "Mthereum"; decimals = 8; _totalSupply = 10000000000000000; balances[0x7aF7ff854a80ba5dd8aB247208918c58A319B904] = _totalSupply; Transfer(address(0), 0x7aF7ff854a80ba5dd8aB247208918c58A319B904, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
approveAndCall
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; }
// ------------------------------------------------------------------------
LineComment
v0.4.19+commit.c4cbbb05
bzzr://f7c5729c6f5712d0043eeafbaab35b7a0217852ed19c0cc65c1ff416977f755a
{ "func_code_index": [ 2119, 2436 ] }
2,899