Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
4
// Returns the address to approve source tokens to for trading. This is the Uniswap router address return address Address of the contract to approve tokens to /
function getSpender() external view returns (address)
function getSpender() external view returns (address)
36,702
97
// If there are funds leftover, mint the best available with it.
if (_leftoverAmount != 0) { _leftoverAmount = _mintBestAvailableTier( _leftoverAmount, _data.beneficiary, _expectMintFromExtraFunds ); if (_leftoverAmount != 0) {
if (_leftoverAmount != 0) { _leftoverAmount = _mintBestAvailableTier( _leftoverAmount, _data.beneficiary, _expectMintFromExtraFunds ); if (_leftoverAmount != 0) {
40,549
13
// create auction struct
Auction memory auction = Auction( _id, uint128(_price), uint64(_duration), uint64(_startTime), _seller );
Auction memory auction = Auction( _id, uint128(_price), uint64(_duration), uint64(_startTime), _seller );
30,838
35
// Whitelisted/STOKR
contract Whitelisted is Ownable { Whitelist public whitelist; /// @dev Log entry on change of whitelist contract instance /// @param previous Ethereum address of previous whitelist /// @param current Ethereum address of new whitelist event WhitelistChange(address indexed previous, address indexed current); /// @dev Ensure only whitelisted addresses can call modifier onlyWhitelisted(address _address) { require(whitelist.isWhitelisted(_address), "Address is not whitelisted"); _; } /// @dev Constructor /// @param _whitelist address of whitelist contract constructor(Whitelist _whitelist) public { setWhitelist(_whitelist); } /// @dev Set the address of whitelist /// @param _newWhitelist An Ethereum address function setWhitelist(Whitelist _newWhitelist) public onlyOwner { require(address(_newWhitelist) != address(0x0), "Whitelist address is zero"); if (address(_newWhitelist) != address(whitelist)) { emit WhitelistChange(address(whitelist), address(_newWhitelist)); whitelist = Whitelist(_newWhitelist); } } }
contract Whitelisted is Ownable { Whitelist public whitelist; /// @dev Log entry on change of whitelist contract instance /// @param previous Ethereum address of previous whitelist /// @param current Ethereum address of new whitelist event WhitelistChange(address indexed previous, address indexed current); /// @dev Ensure only whitelisted addresses can call modifier onlyWhitelisted(address _address) { require(whitelist.isWhitelisted(_address), "Address is not whitelisted"); _; } /// @dev Constructor /// @param _whitelist address of whitelist contract constructor(Whitelist _whitelist) public { setWhitelist(_whitelist); } /// @dev Set the address of whitelist /// @param _newWhitelist An Ethereum address function setWhitelist(Whitelist _newWhitelist) public onlyOwner { require(address(_newWhitelist) != address(0x0), "Whitelist address is zero"); if (address(_newWhitelist) != address(whitelist)) { emit WhitelistChange(address(whitelist), address(_newWhitelist)); whitelist = Whitelist(_newWhitelist); } } }
20,072
122
// Function to mint tokens to The address that will receive the minted tokens. amount The amount of tokens to mint.return A boolean that indicates if the operation was successful. /
function mint( address to, uint256 amount ) public onlyMinter onlyBeforeMintingFinished returns (bool)
function mint( address to, uint256 amount ) public onlyMinter onlyBeforeMintingFinished returns (bool)
36,242
170
// Ensures the input address is the interest model contract.
require( _newInterestRateModel.isInterestRateModel(), "_setInterestRateModel: This is not the rate model contract!" );
require( _newInterestRateModel.isInterestRateModel(), "_setInterestRateModel: This is not the rate model contract!" );
80,136
533
// called by the owner to remove and add new oracles as well asupdate the round related parameters that pertain to total oracle count _removed is the list of addresses for the new Oracles being removed _added is the list of addresses for the new Oracles being added _addedAdmins is the admin addresses for the new respective _addedlist. Only this address is allowed to access the respective oracle's funds _minSubmissions is the new minimum submission count for each round _maxSubmissions is the new maximum submission count for each round _restartDelay is the number of rounds an Oracle has to wait beforethey
function changeOracles( address[] calldata _removed, address[] calldata _added, address[] calldata _addedAdmins, uint32 _minSubmissions, uint32 _maxSubmissions, uint32 _restartDelay
function changeOracles( address[] calldata _removed, address[] calldata _added, address[] calldata _addedAdmins, uint32 _minSubmissions, uint32 _maxSubmissions, uint32 _restartDelay
13,279
261
// Transfer rewards to this strategy
function updateReward() public onlyOwner { harvestRewardPool.getReward(); }
function updateReward() public onlyOwner { harvestRewardPool.getReward(); }
14,500
20
// Appends a byte to the end of the buffer. Resizes if doing so wouldexceed the capacity of the buffer. buf The buffer to append to. data The data to append.return The original buffer. /
function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } }
function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } }
20,780
15
// calculate token amount to be created
tokens = weiAmount.mul(rate);
tokens = weiAmount.mul(rate);
2,070
9
// getValidatorID represents the relation between a Validator address and the ID of the Validator.
mapping(address => uint256) public getValidatorID;
mapping(address => uint256) public getValidatorID;
24,953
39
// Get this deposit's lot size in TBTC./This is the same as lotSizeSatoshis(), but is multiplied to scale/to 18 decimal places./ return uint256 lot size in TBTC precision (max 18 decimal places).
function lotSizeTbtc() external view returns (uint256){ return self.lotSizeTbtc(); }
function lotSizeTbtc() external view returns (uint256){ return self.lotSizeTbtc(); }
31,510
2
// Sales mapping | tokenId: Sale
mapping(uint => Models.Sale) public sales;
mapping(uint => Models.Sale) public sales;
6,636
114
// SONE tokens created per block.
uint256 public REWARD_PER_BLOCK;
uint256 public REWARD_PER_BLOCK;
65,117
14
// Fire the cross chain event denoting there is a cross chain request from Ethereum network to other public chains through linq network network
emit CrossChainEvent(tx.origin, paramTxHash, msg.sender, toChainId, toContract, rawParam); return true;
emit CrossChainEvent(tx.origin, paramTxHash, msg.sender, toChainId, toContract, rawParam); return true;
16,249
132
// DODOIncentive DODO BreederTrade Incentive in DODO platform /
contract DODOIncentive is InitializableOwnable { using SafeMath for uint256; using SafeERC20 for IERC20; // ============ Storage ============ address public immutable _DODO_TOKEN_; address public _DODO_PROXY_; uint256 public dodoPerBlock; uint256 public defaultRate = 10; mapping(address => uint256) public boosts; uint32 public lastRewardBlock; uint112 public totalReward; uint112 public totalDistribution; // ============ Events ============ event SetBoost(address token, uint256 boostRate); event SetNewProxy(address dodoProxy); event SetPerReward(uint256 dodoPerBlock); event SetDefaultRate(uint256 defaultRate); event Incentive(address user, uint256 reward); constructor(address _dodoToken) public { _DODO_TOKEN_ = _dodoToken; } // ============ Ownable ============ function changeBoost(address _token, uint256 _boostRate) public onlyOwner { require(_token != address(0)); require(_boostRate + defaultRate <= 1000); boosts[_token] = _boostRate; emit SetBoost(_token, _boostRate); } function changePerReward(uint256 _dodoPerBlock) public onlyOwner { _updateTotalReward(); dodoPerBlock = _dodoPerBlock; emit SetPerReward(dodoPerBlock); } function changeDefaultRate(uint256 _defaultRate) public onlyOwner { defaultRate = _defaultRate; emit SetDefaultRate(defaultRate); } function changeDODOProxy(address _dodoProxy) public onlyOwner { _DODO_PROXY_ = _dodoProxy; emit SetNewProxy(_DODO_PROXY_); } function emptyReward(address assetTo) public onlyOwner { uint256 balance = IERC20(_DODO_TOKEN_).balanceOf(address(this)); IERC20(_DODO_TOKEN_).transfer(assetTo, balance); } // ============ Incentive function ============ function triggerIncentive( address fromToken, address toToken, address assetTo ) external { require(msg.sender == _DODO_PROXY_, "DODOIncentive:Access restricted"); uint256 curTotalDistribution = totalDistribution; uint256 fromRate = boosts[fromToken]; uint256 toRate = boosts[toToken]; uint256 rate = (fromRate >= toRate ? fromRate : toRate) + defaultRate; require(rate <= 1000, "RATE_INVALID"); uint256 _totalReward = _getTotalReward(); uint256 reward = ((_totalReward - curTotalDistribution) * rate) / 1000; uint256 _totalDistribution = curTotalDistribution + reward; _update(_totalReward, _totalDistribution); if (reward != 0) { IERC20(_DODO_TOKEN_).transfer(assetTo, reward); emit Incentive(assetTo, reward); } } function _updateTotalReward() internal { uint256 _totalReward = _getTotalReward(); require(_totalReward < uint112(-1), "OVERFLOW"); totalReward = uint112(_totalReward); lastRewardBlock = uint32(block.number); } function _update(uint256 _totalReward, uint256 _totalDistribution) internal { require( _totalReward < uint112(-1) && _totalDistribution < uint112(-1) && block.number < uint32(-1), "OVERFLOW" ); lastRewardBlock = uint32(block.number); totalReward = uint112(_totalReward); totalDistribution = uint112(_totalDistribution); } function _getTotalReward() internal view returns (uint256) { if (lastRewardBlock == 0) { return totalReward; } else { return totalReward + (block.number - lastRewardBlock) * dodoPerBlock; } } // ============= Helper function =============== function incentiveStatus(address fromToken, address toToken) external view returns ( uint256 reward, uint256 baseRate, uint256 totalRate, uint256 curTotalReward, uint256 perBlockReward ) { baseRate = defaultRate; uint256 fromRate = boosts[fromToken]; uint256 toRate = boosts[toToken]; totalRate = (fromRate >= toRate ? fromRate : toRate) + defaultRate; uint256 _totalReward = _getTotalReward(); reward = ((_totalReward - totalDistribution) * totalRate) / 1000; curTotalReward = _totalReward - totalDistribution; perBlockReward = dodoPerBlock; } }
contract DODOIncentive is InitializableOwnable { using SafeMath for uint256; using SafeERC20 for IERC20; // ============ Storage ============ address public immutable _DODO_TOKEN_; address public _DODO_PROXY_; uint256 public dodoPerBlock; uint256 public defaultRate = 10; mapping(address => uint256) public boosts; uint32 public lastRewardBlock; uint112 public totalReward; uint112 public totalDistribution; // ============ Events ============ event SetBoost(address token, uint256 boostRate); event SetNewProxy(address dodoProxy); event SetPerReward(uint256 dodoPerBlock); event SetDefaultRate(uint256 defaultRate); event Incentive(address user, uint256 reward); constructor(address _dodoToken) public { _DODO_TOKEN_ = _dodoToken; } // ============ Ownable ============ function changeBoost(address _token, uint256 _boostRate) public onlyOwner { require(_token != address(0)); require(_boostRate + defaultRate <= 1000); boosts[_token] = _boostRate; emit SetBoost(_token, _boostRate); } function changePerReward(uint256 _dodoPerBlock) public onlyOwner { _updateTotalReward(); dodoPerBlock = _dodoPerBlock; emit SetPerReward(dodoPerBlock); } function changeDefaultRate(uint256 _defaultRate) public onlyOwner { defaultRate = _defaultRate; emit SetDefaultRate(defaultRate); } function changeDODOProxy(address _dodoProxy) public onlyOwner { _DODO_PROXY_ = _dodoProxy; emit SetNewProxy(_DODO_PROXY_); } function emptyReward(address assetTo) public onlyOwner { uint256 balance = IERC20(_DODO_TOKEN_).balanceOf(address(this)); IERC20(_DODO_TOKEN_).transfer(assetTo, balance); } // ============ Incentive function ============ function triggerIncentive( address fromToken, address toToken, address assetTo ) external { require(msg.sender == _DODO_PROXY_, "DODOIncentive:Access restricted"); uint256 curTotalDistribution = totalDistribution; uint256 fromRate = boosts[fromToken]; uint256 toRate = boosts[toToken]; uint256 rate = (fromRate >= toRate ? fromRate : toRate) + defaultRate; require(rate <= 1000, "RATE_INVALID"); uint256 _totalReward = _getTotalReward(); uint256 reward = ((_totalReward - curTotalDistribution) * rate) / 1000; uint256 _totalDistribution = curTotalDistribution + reward; _update(_totalReward, _totalDistribution); if (reward != 0) { IERC20(_DODO_TOKEN_).transfer(assetTo, reward); emit Incentive(assetTo, reward); } } function _updateTotalReward() internal { uint256 _totalReward = _getTotalReward(); require(_totalReward < uint112(-1), "OVERFLOW"); totalReward = uint112(_totalReward); lastRewardBlock = uint32(block.number); } function _update(uint256 _totalReward, uint256 _totalDistribution) internal { require( _totalReward < uint112(-1) && _totalDistribution < uint112(-1) && block.number < uint32(-1), "OVERFLOW" ); lastRewardBlock = uint32(block.number); totalReward = uint112(_totalReward); totalDistribution = uint112(_totalDistribution); } function _getTotalReward() internal view returns (uint256) { if (lastRewardBlock == 0) { return totalReward; } else { return totalReward + (block.number - lastRewardBlock) * dodoPerBlock; } } // ============= Helper function =============== function incentiveStatus(address fromToken, address toToken) external view returns ( uint256 reward, uint256 baseRate, uint256 totalRate, uint256 curTotalReward, uint256 perBlockReward ) { baseRate = defaultRate; uint256 fromRate = boosts[fromToken]; uint256 toRate = boosts[toToken]; totalRate = (fromRate >= toRate ? fromRate : toRate) + defaultRate; uint256 _totalReward = _getTotalReward(); reward = ((_totalReward - totalDistribution) * totalRate) / 1000; curTotalReward = _totalReward - totalDistribution; perBlockReward = dodoPerBlock; } }
33,569
109
// returns the day number of the current day, in days since the UNIX epoch. /
function today() public view override returns (uint32) { return uint32(block.timestamp / SECONDS_PER_DAY); }
function today() public view override returns (uint32) { return uint32(block.timestamp / SECONDS_PER_DAY); }
26,811
40
// Sets the address and basis points for royalties.newInfo The struct to configure royalties. /
function setRoyaltyInfo(RoyaltyInfo calldata newInfo) external { // Ensure the sender is only the owner or contract itself. _onlyOwnerOrSelf(); // Revert if the new royalty address is the zero address. if (newInfo.royaltyAddress == address(0)) { revert RoyaltyAddressCannotBeZeroAddress(); } // Revert if the new basis points is greater than 10_000. if (newInfo.royaltyBps > 10_000) { revert InvalidRoyaltyBasisPoints(newInfo.royaltyBps); } // Set the new royalty info. _royaltyInfo = newInfo; // Emit an event with the updated params. emit RoyaltyInfoUpdated(newInfo.royaltyAddress, newInfo.royaltyBps); }
function setRoyaltyInfo(RoyaltyInfo calldata newInfo) external { // Ensure the sender is only the owner or contract itself. _onlyOwnerOrSelf(); // Revert if the new royalty address is the zero address. if (newInfo.royaltyAddress == address(0)) { revert RoyaltyAddressCannotBeZeroAddress(); } // Revert if the new basis points is greater than 10_000. if (newInfo.royaltyBps > 10_000) { revert InvalidRoyaltyBasisPoints(newInfo.royaltyBps); } // Set the new royalty info. _royaltyInfo = newInfo; // Emit an event with the updated params. emit RoyaltyInfoUpdated(newInfo.royaltyAddress, newInfo.royaltyBps); }
20,320
16
// Returns the total of rewards of an user, already accrued + not yet accrued user The address of the userreturn The rewards // Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards amount Amount of rewards to claim to Address that will be receiving the rewardsreturn Rewards claimed // Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller mustbe whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager amount Amount of rewards to claim user Address to check and claim
function getUserUnclaimedRewards(address user) external view returns (uint256);
function getUserUnclaimedRewards(address user) external view returns (uint256);
50,889
336
// The proportion of interest accrued that is taken as a service fee (scaled by 1e18). /
uint256 private _interestFeeRate;
uint256 private _interestFeeRate;
35,842
28
// Returns product if no overflow occurred/a First factor/b Second factor/ return Product
function mul(uint a, uint b) internal pure returns (uint) { require(safeToMul(a, b)); return a * b; }
function mul(uint a, uint b) internal pure returns (uint) { require(safeToMul(a, b)); return a * b; }
45,675
4
// we have read readUntil bytes and add 1 more to skip the zero byte at the beginning of every 32 bytes
index += bytesToRead + 1;
index += bytesToRead + 1;
1,834
119
// zero out keys if the accumulated profit doubled
function checkDoubledProfit(uint256 _pID, uint256 _rID) private
function checkDoubledProfit(uint256 _pID, uint256 _rID) private
30,503
2
// The topic has expired, was not automatically renewed, and is in a 7 day grace period before the topic will be deleted unrecoverably. This error response code will not be returned until autoRenew functionality is supported by HAPI.
int32 internal constant TOPIC_EXPIRED = 162; int32 internal constant INVALID_CHUNK_NUMBER = 163; // chunk number must be from 1 to total (chunks) inclusive. int32 internal constant INVALID_CHUNK_TRANSACTION_ID = 164; // For every chunk, the payer account that is part of initialTransactionID must match the Payer Account of this transaction. The entire initialTransactionID should match the transactionID of the first chunk, but this is not checked or enforced by Hedera except when the chunk number is 1. int32 internal constant ACCOUNT_FROZEN_FOR_TOKEN = 165; // Account is frozen and cannot transact with the token int32 internal constant TOKENS_PER_ACCOUNT_LIMIT_EXCEEDED = 166; // An involved account already has more than <tt>tokens.maxPerAccount</tt> associations with non-deleted tokens. int32 internal constant INVALID_TOKEN_ID = 167; // The token is invalid or does not exist int32 internal constant INVALID_TOKEN_DECIMALS = 168; // Invalid token decimals int32 internal constant INVALID_TOKEN_INITIAL_SUPPLY = 169; // Invalid token initial supply int32 internal constant INVALID_TREASURY_ACCOUNT_FOR_TOKEN = 170; // Treasury Account does not exist or is deleted int32 internal constant INVALID_TOKEN_SYMBOL = 171; // Token Symbol is not UTF-8 capitalized alphabetical string
int32 internal constant TOPIC_EXPIRED = 162; int32 internal constant INVALID_CHUNK_NUMBER = 163; // chunk number must be from 1 to total (chunks) inclusive. int32 internal constant INVALID_CHUNK_TRANSACTION_ID = 164; // For every chunk, the payer account that is part of initialTransactionID must match the Payer Account of this transaction. The entire initialTransactionID should match the transactionID of the first chunk, but this is not checked or enforced by Hedera except when the chunk number is 1. int32 internal constant ACCOUNT_FROZEN_FOR_TOKEN = 165; // Account is frozen and cannot transact with the token int32 internal constant TOKENS_PER_ACCOUNT_LIMIT_EXCEEDED = 166; // An involved account already has more than <tt>tokens.maxPerAccount</tt> associations with non-deleted tokens. int32 internal constant INVALID_TOKEN_ID = 167; // The token is invalid or does not exist int32 internal constant INVALID_TOKEN_DECIMALS = 168; // Invalid token decimals int32 internal constant INVALID_TOKEN_INITIAL_SUPPLY = 169; // Invalid token initial supply int32 internal constant INVALID_TREASURY_ACCOUNT_FOR_TOKEN = 170; // Treasury Account does not exist or is deleted int32 internal constant INVALID_TOKEN_SYMBOL = 171; // Token Symbol is not UTF-8 capitalized alphabetical string
15,710
62
// Valid MD5 token
realWorldPlayers[_rosterIndex].metadata = _metadata;
realWorldPlayers[_rosterIndex].metadata = _metadata;
41,511
6
// Information about the rest of the supply Total that have been minted
uint256 totalMinted;
uint256 totalMinted;
1,419
12
// All funding phases information to their position in mapping
mapping(uint256 => FundPhase) internal fundingPhases_;
mapping(uint256 => FundPhase) internal fundingPhases_;
25,861
23
// Cut owner takes on each auction, measured in basis points (1/100 of a percent). Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
uint256 public ownerCut;
1,668
12
// Farmer doesn't approve the order /
function notApprove() public onlyFarmer inState(State.Ordered)
function notApprove() public onlyFarmer inState(State.Ordered)
15,195
308
// we have a non number
if (_hasNonNumber == false) _hasNonNumber = true;
if (_hasNonNumber == false) _hasNonNumber = true;
21,219
5
// Removes the operator right from the _operator address_operator the address of the operator to remove/
function removeOperator(address _operator) public onlyOwner
function removeOperator(address _operator) public onlyOwner
25,038
0
// solhint-disable func-name-mixedcase
function OverspentEthError( uint256 ethSpent, uint256 ethAvailable ) internal pure returns (bytes memory)
function OverspentEthError( uint256 ethSpent, uint256 ethAvailable ) internal pure returns (bytes memory)
688
68
// setMinMax function to set the minimum or maximum investment amount/
function setMinMax (uint256 minMax, string eventType) public onlyOwner { require(minMax >= 0); // Set new maxAmmount if(compareStrings(eventType, "max")) maxAmmount = minMax; // Set new min to Contribute else if(compareStrings(eventType,"min")) minContribute = minMax; else require(1==2); }
function setMinMax (uint256 minMax, string eventType) public onlyOwner { require(minMax >= 0); // Set new maxAmmount if(compareStrings(eventType, "max")) maxAmmount = minMax; // Set new min to Contribute else if(compareStrings(eventType,"min")) minContribute = minMax; else require(1==2); }
37,625
59
// send excess amount back to sender
payable(msg.sender).transfer(msg.value - totalPrice);
payable(msg.sender).transfer(msg.value - totalPrice);
45,069
7
// state sender contract
IFxStateSender public fxRoot;
IFxStateSender public fxRoot;
24,729
66
// A mapping of handler addresses for lookups
mapping(address => bool) public handlerMap;
mapping(address => bool) public handlerMap;
44,409
2
// Tokens per wallet declaration
mapping(address => uint) public tokensPerWallet; // to limit max mint per wallet
mapping(address => uint) public tokensPerWallet; // to limit max mint per wallet
1,347
26
// Initialization function for upgradable proxy contracts _nexus Nexus contract address /
function _initialize(address _nexus) internal { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); InitializableModuleKeys._initialize(); }
function _initialize(address _nexus) internal { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); InitializableModuleKeys._initialize(); }
3,220
50
// tokensLeft is equal to amount at the beginning
tokens[1] = _data[0]; _src = wethToKyberEth(_src); _dest = wethToKyberEth(_dest);
tokens[1] = _data[0]; _src = wethToKyberEth(_src); _dest = wethToKyberEth(_dest);
84,880
2
// Struct to represent amount of vested tokens claimable for a vesting schedule scheduleID ID of vesting schedule claimableTokens number of vesting tokens claimable as of the current time /
struct ClaimableInfo { uint256 scheduleID; uint256 claimableTokens; }
struct ClaimableInfo { uint256 scheduleID; uint256 claimableTokens; }
39,518
27
// Internal function to approve tokens for the user /
function _approve( address owner, address spender, uint256 amount
function _approve( address owner, address spender, uint256 amount
31,256
54
// Calculate the reward amount for the current window - Need to consider pendingForApprovalAmount for Auto Approvals
totalAmount = stakeInfo.approvedAmount.add(stakeInfo.pendingForApprovalAmount); rewardAmount = _calculateRewardAmount(stakeMapIndex, totalAmount); totalAmount = totalAmount.add(rewardAmount);
totalAmount = stakeInfo.approvedAmount.add(stakeInfo.pendingForApprovalAmount); rewardAmount = _calculateRewardAmount(stakeMapIndex, totalAmount); totalAmount = totalAmount.add(rewardAmount);
10,633
62
// Verify caller is a valid vault contact Only callable from onlyVault modifier. Requirements: - msg.sender is contained in validVault address mapping /
function _onlyVault() private view { require( validVault[msg.sender], "Controller::_onlyVault: Can only be invoked by vault" ); }
function _onlyVault() private view { require( validVault[msg.sender], "Controller::_onlyVault: Can only be invoked by vault" ); }
48,023
40
// Clears the committee members vote-unready state upon declaring a guardian unready/committee is a list of the current committee members/subject is the subject guardian address
function clearCommitteeUnreadyVotes(address[] memory committee, address subject) private { for (uint i = 0; i < committee.length; i++) { voteUnreadyVotes[committee[i]][subject] = 0; // clear vote-outs } }
function clearCommitteeUnreadyVotes(address[] memory committee, address subject) private { for (uint i = 0; i < committee.length; i++) { voteUnreadyVotes[committee[i]][subject] = 0; // clear vote-outs } }
37,988
91
// Lower prodBoost of old tadpole owner
prodBoost[currentTadpoleOwner] = prodBoost[currentTadpoleOwner].sub(1);
prodBoost[currentTadpoleOwner] = prodBoost[currentTadpoleOwner].sub(1);
43,166
15
// Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. /
function isApprovedForAll(address owner, address operator) public view override(IERC721, ERC721) returns (bool) { // Whitelist OpenSea proxy contract for easy trading. if (proxyRegistry.proxies(owner) == operator) { return true; } return super.isApprovedForAll(owner, operator); }
function isApprovedForAll(address owner, address operator) public view override(IERC721, ERC721) returns (bool) { // Whitelist OpenSea proxy contract for easy trading. if (proxyRegistry.proxies(owner) == operator) { return true; } return super.isApprovedForAll(owner, operator); }
50,423
71
// send fees if threshold has been reacheddon't do this on buys, breaks swap
if (providingLiquidity && sender != pair && feeswap > 0) handle_fees(feeswap, currentTaxes);
if (providingLiquidity && sender != pair && feeswap > 0) handle_fees(feeswap, currentTaxes);
30,200
2
// Adds a Metaverse to LandWorks./Sets the metaverse registries as consumable adapters./_metaverseId The id of the metaverse/_name Name of the metaverse/_metaverseRegistries A list of metaverse registries, that will be/ associated with the given metaverse id./_administrativeConsumers A list of administrative consumers, mapped/ 1:1 to its metaverse registry index. Used as a consumer when no active rents are/ active.
function addMetaverseWithoutAdapters( uint256 _metaverseId, string calldata _name, address[] calldata _metaverseRegistries, address[] calldata _administrativeConsumers
function addMetaverseWithoutAdapters( uint256 _metaverseId, string calldata _name, address[] calldata _metaverseRegistries, address[] calldata _administrativeConsumers
35,195
46
// check if there is actually enough funds
require((internalBalance >= _amount) && (getTokenBalance() >= _amount));
require((internalBalance >= _amount) && (getTokenBalance() >= _amount));
10,713
26
// List of revert message codes. Implementing dApp should handle showing the correct message.Based on 0xcert framework error codes. /
string constant ZERO_ADDRESS = "003001"; string constant NOT_VALID_NFT = "003002"; string constant NOT_OWNER_OR_OPERATOR = "003003"; string constant NOT_OWNER_APPROVED_OR_OPERATOR = "003004"; string constant NOT_ABLE_TO_RECEIVE_NFT = "003005"; string constant NFT_ALREADY_EXISTS = "003006"; string constant NOT_OWNER = "003007"; string constant IS_OWNER = "003008";
string constant ZERO_ADDRESS = "003001"; string constant NOT_VALID_NFT = "003002"; string constant NOT_OWNER_OR_OPERATOR = "003003"; string constant NOT_OWNER_APPROVED_OR_OPERATOR = "003004"; string constant NOT_ABLE_TO_RECEIVE_NFT = "003005"; string constant NFT_ALREADY_EXISTS = "003006"; string constant NOT_OWNER = "003007"; string constant IS_OWNER = "003008";
23,220
7
// gameRegistry(gameRegistryAddress).getWinners(_gameId);
for (uint8 i = 0; i < _competitorsLimit; i++) { for (uint8 j = 0; j < _winnersLength; j++) { if (i != _winners[j]) { amount += totalBidAmount[_gameId][i]; }
for (uint8 i = 0; i < _competitorsLimit; i++) { for (uint8 j = 0; j < _winnersLength; j++) { if (i != _winners[j]) { amount += totalBidAmount[_gameId][i]; }
36,534
64
// Modifier, which only allows server to call function.
modifier onlyServer() { require(msg.sender == serverAddress); _; }
modifier onlyServer() { require(msg.sender == serverAddress); _; }
50,191
2
// accept transfer of contract ownership /
function _acceptOwnership() internal virtual { _setOwner(msg.sender); delete SafeOwnableStorage.layout().nomineeOwner; }
function _acceptOwnership() internal virtual { _setOwner(msg.sender); delete SafeOwnableStorage.layout().nomineeOwner; }
22,904
6
// ========== VIEW FUNCTIONS ========== / budget
function getReserve() public view returns (uint256) { return accumulatedSeigniorage; }
function getReserve() public view returns (uint256) { return accumulatedSeigniorage; }
38,515
10
// The current cycle payout percentage to the darknodes.
uint256 public currentCyclePayoutPercent;
uint256 public currentCyclePayoutPercent;
12,241
22
// Incoming transfer from the Presale token buyer
function() payable { uint tokenAmount; // Amount of tzokens which is possible to buy for incoming transfer/payment uint amountToBePaid; // Amount to be paid uint amountTransfered = msg.value; // Cost/price in WEI of incoming transfer/payment if (amountTransfered <= 0) { Error('no eth was transfered'); msg.sender.transfer(msg.value); return; } if(balanceFor[owner] <= 0) { Error('all tokens sold'); msg.sender.transfer(msg.value); return; } // Determine amount of tokens can be bought according to available supply and discount policy for (uint discountIndex = 0; discountIndex < tokenSupplies.length; discountIndex++) { // If it's not possible to buy any tokens at all skip the rest of discount policy TokenSupply storage tokenSupply = tokenSupplies[discountIndex]; if(tokenSupply.totalSupply < tokenSupply.limit) { uint tokensPossibleToBuy = amountTransfered / tokenSupply.tokenPriceInWei; if (tokensPossibleToBuy > balanceFor[owner]) tokensPossibleToBuy = balanceFor[owner]; if (tokenSupply.totalSupply + tokensPossibleToBuy > tokenSupply.limit) { tokensPossibleToBuy = tokenSupply.limit - tokenSupply.totalSupply; } tokenSupply.totalSupply += tokensPossibleToBuy; tokenAmount += tokensPossibleToBuy; uint delta = tokensPossibleToBuy * tokenSupply.tokenPriceInWei; amountToBePaid += delta; amountTransfered -= delta; } } // Do not waste gas if there is no tokens to buy if (tokenAmount == 0) { Error('no token to buy'); msg.sender.transfer(msg.value); return; } // Transfer tokens to buyer transferFromOwner(msg.sender, tokenAmount); // Transfer money to seller owner.transfer(amountToBePaid); // Refund buyer if overpaid / no tokens to sell msg.sender.transfer(msg.value - amountToBePaid); }
function() payable { uint tokenAmount; // Amount of tzokens which is possible to buy for incoming transfer/payment uint amountToBePaid; // Amount to be paid uint amountTransfered = msg.value; // Cost/price in WEI of incoming transfer/payment if (amountTransfered <= 0) { Error('no eth was transfered'); msg.sender.transfer(msg.value); return; } if(balanceFor[owner] <= 0) { Error('all tokens sold'); msg.sender.transfer(msg.value); return; } // Determine amount of tokens can be bought according to available supply and discount policy for (uint discountIndex = 0; discountIndex < tokenSupplies.length; discountIndex++) { // If it's not possible to buy any tokens at all skip the rest of discount policy TokenSupply storage tokenSupply = tokenSupplies[discountIndex]; if(tokenSupply.totalSupply < tokenSupply.limit) { uint tokensPossibleToBuy = amountTransfered / tokenSupply.tokenPriceInWei; if (tokensPossibleToBuy > balanceFor[owner]) tokensPossibleToBuy = balanceFor[owner]; if (tokenSupply.totalSupply + tokensPossibleToBuy > tokenSupply.limit) { tokensPossibleToBuy = tokenSupply.limit - tokenSupply.totalSupply; } tokenSupply.totalSupply += tokensPossibleToBuy; tokenAmount += tokensPossibleToBuy; uint delta = tokensPossibleToBuy * tokenSupply.tokenPriceInWei; amountToBePaid += delta; amountTransfered -= delta; } } // Do not waste gas if there is no tokens to buy if (tokenAmount == 0) { Error('no token to buy'); msg.sender.transfer(msg.value); return; } // Transfer tokens to buyer transferFromOwner(msg.sender, tokenAmount); // Transfer money to seller owner.transfer(amountToBePaid); // Refund buyer if overpaid / no tokens to sell msg.sender.transfer(msg.value - amountToBePaid); }
51,521
12
// Initialize header start index
bytes32 digest; totalDifficulty = 0; for (uint256 start = 0; start < headers.length; start += 80) {
bytes32 digest; totalDifficulty = 0; for (uint256 start = 0; start < headers.length; start += 80) {
11,269
13
// Perfomr all necessary steps for the transition
tellor.uintVars[keccak256("currentReward")] = 1e18; tellor.uintVars[keccak256("stakeAmount")] = 500e18; tellor.uintVars[keccak256("disputeFee")] = 500e18;
tellor.uintVars[keccak256("currentReward")] = 1e18; tellor.uintVars[keccak256("stakeAmount")] = 500e18; tellor.uintVars[keccak256("disputeFee")] = 500e18;
61,801
22
// Returns true if the peer is whitelisted, otherwise false. /
function peerWhitelisted(address _peer) override view external returns(bool){ return _peer == exhibition && exhibition != address(0); }
function peerWhitelisted(address _peer) override view external returns(bool){ return _peer == exhibition && exhibition != address(0); }
18,595
155
// required for weth.withdraw() to work properly
require(msg.sender == WETH, "ExchangeIssuance: Direct deposits not allowed");
require(msg.sender == WETH, "ExchangeIssuance: Direct deposits not allowed");
30,688
83
// COLOR tokens created per block.
uint256 public colorPerBlock = 167700000000000000;
uint256 public colorPerBlock = 167700000000000000;
5,208
1,189
// Contract initializer. logic address of the initial implementation. admin Address of the proxy administrator. data Data to send as msg.data to the implementation to initialize the proxied contract.It should include the signature and the parameters of the function to be called, as described inThis parameter is optional, if no data is given the initialization call to proxied contract will be skipped. /
function initialize( address logic, address admin, bytes memory data
function initialize( address logic, address admin, bytes memory data
15,524
0
// Emitted when ERC20 token is recovered
event Recovered(address indexed token, uint256 amount);
event Recovered(address indexed token, uint256 amount);
25,351
267
// must have ten of external account
return getExternalAccountBalance() > 9;
return getExternalAccountBalance() > 9;
40,956
92
// Interface marker /
function isUpgradeAgent() public constant returns (bool) { return true; }
function isUpgradeAgent() public constant returns (bool) { return true; }
27,607
105
// IPriceOracleGetter interface Interface for the Aave price oracle. /
interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address asset) external view returns (uint256); }
interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address asset) external view returns (uint256); }
60,605
114
// No referrer
require(amount >= registrationFeeWithoutReferrer, "Must send at least enough LID to pay registration fee."); distribute(registrationFeeWithoutReferrer); finalAmount = amount.sub(registrationFeeWithoutReferrer);
require(amount >= registrationFeeWithoutReferrer, "Must send at least enough LID to pay registration fee."); distribute(registrationFeeWithoutReferrer); finalAmount = amount.sub(registrationFeeWithoutReferrer);
39,988
29
// The provided address should be valid.
require(_feeAccount != 0x0);
require(_feeAccount != 0x0);
34,360
602
// We've already checked the remaining budget with `_canMakePayment()`
_unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" );
_unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" );
26,772
40
// add vested BZRX to rewards balance
rewardsVested = vBZRXBalance .mul(multiplier) .div(1e36); bzrxRewardsEarned += rewardsVested;
rewardsVested = vBZRXBalance .mul(multiplier) .div(1e36); bzrxRewardsEarned += rewardsVested;
44,788
99
// Payable function to purchase cnix with eth at current crowdsale price
function buyCnix() public payable returns (bool) { address client = msg.sender; uint256 cnixToSend = msg.value * ethToCnix; forwardAddress.transfer(msg.value); car.mint(client, cnixToSend); return true; }
function buyCnix() public payable returns (bool) { address client = msg.sender; uint256 cnixToSend = msg.value * ethToCnix; forwardAddress.transfer(msg.value); car.mint(client, cnixToSend); return true; }
23,742
65
// Checks that a given channel is in the Challenge mode. Checks that a given channel is in the Challenge mode. channelId Unique identifier for a channel. /
function _requireOngoingChallenge(bytes32 channelId) internal view { require(_mode(channelId) == ChannelMode.Challenge, 'No ongoing challenge.'); }
function _requireOngoingChallenge(bytes32 channelId) internal view { require(_mode(channelId) == ChannelMode.Challenge, 'No ongoing challenge.'); }
4,141
173
// Aludel/Reward distribution contract with time multiplier/ Access Control/ - Power controller:/ Can power off / shutdown the Aludel/ Can withdraw rewards from reward pool once shutdown/ - Aludel admin:/ Can add funds to the Aludel, register bonus tokens, and whitelist new vault factories/ Is a subset of proxy owner permissions/ - User:/ Can deposit / withdraw / ragequit/ Aludel State Machine/ - Online:/ Aludel is operating normally, all functions are enabled/ - Offline:/ Aludel is temporarely disabled for maintenance/ User deposits and withdrawls are disabled, ragequit remains enabled/ Users can withdraw their stake through rageQuit() but forego their pending reward/
contract Aludel is IAludel, Powered, Ownable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /* constants */ // An upper bound on the number of active stakes per vault is required to prevent // calls to rageQuit() from reverting. // With 30 stakes in a vault, ragequit costs 432811 gas which is conservatively lower // than the hardcoded limit of 500k gas on the vault. // This limit is configurable and could be increased in a future deployment. // Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide // an error code that allows for reliably catching out-of-gas errors on remote calls. uint256 public constant MAX_STAKES_PER_VAULT = 30; uint256 public constant MAX_REWARD_TOKENS = 50; uint256 public constant BASE_SHARES_PER_WEI = 1000000; /* storage */ AludelData private _aludel; mapping(address => VaultData) private _vaults; EnumerableSet.AddressSet private _bonusTokenSet; EnumerableSet.AddressSet private _vaultFactorySet; /* initializer */ /// @notice Initizalize Aludel /// access control: only proxy constructor /// state machine: can only be called once /// state scope: set initialization variables /// token transfer: none /// @param ownerAddress address The admin address /// @param rewardPoolFactory address The factory to use for deploying the RewardPool /// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch /// @param stakingToken address The address of the staking token for this Aludel /// @param rewardToken address The address of the reward token for this Aludel /// @param rewardScaling RewardScaling The config for reward scaling floor, ceiling, and time constructor( address ownerAddress, address rewardPoolFactory, address powerSwitchFactory, address stakingToken, address rewardToken, RewardScaling memory rewardScaling ) { // the scaling floor must be smaller than ceiling require(rewardScaling.floor <= rewardScaling.ceiling, "Aludel: floor above ceiling"); // setting rewardScalingTime to 0 would cause divide by zero error // to disable reward scaling, use rewardScalingFloor == rewardScalingCeiling require(rewardScaling.time != 0, "Aludel: scaling time cannot be zero"); // deploy power switch address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(ownerAddress)); // deploy reward pool address rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch)); // set internal configs Ownable.transferOwnership(ownerAddress); Powered._setPowerSwitch(powerSwitch); // commit to storage _aludel.stakingToken = stakingToken; _aludel.rewardToken = rewardToken; _aludel.rewardPool = rewardPool; _aludel.rewardScaling = rewardScaling; // emit event emit AludelCreated(rewardPool, powerSwitch); } /* getter functions */ function getBonusTokenSetLength() external view override returns (uint256 length) { return _bonusTokenSet.length(); } function getBonusTokenAtIndex(uint256 index) external view override returns (address bonusToken) { return _bonusTokenSet.at(index); } function getVaultFactorySetLength() external view override returns (uint256 length) { return _vaultFactorySet.length(); } function getVaultFactoryAtIndex(uint256 index) external view override returns (address factory) { return _vaultFactorySet.at(index); } function isValidVault(address target) public view override returns (bool validity) { // validate target is created from whitelisted vault factory for (uint256 index = 0; index < _vaultFactorySet.length(); index++) { if (IInstanceRegistry(_vaultFactorySet.at(index)).isInstance(target)) { return true; } } // explicit return return false; } function isValidAddress(address target) public view override returns (bool validity) { // sanity check target for potential input errors return target != address(this) && target != address(0) && target != _aludel.stakingToken && target != _aludel.rewardToken && target != _aludel.rewardPool && !_bonusTokenSet.contains(target); } /* Aludel getters */ function getAludelData() external view override returns (AludelData memory aludel) { return _aludel; } function getCurrentUnlockedRewards() public view override returns (uint256 unlockedRewards) { // calculate reward available based on state return getFutureUnlockedRewards(block.timestamp); } function getFutureUnlockedRewards(uint256 timestamp) public view override returns (uint256 unlockedRewards) { // get reward amount remaining uint256 remainingRewards = IERC20(_aludel.rewardToken).balanceOf(_aludel.rewardPool); // calculate reward available based on state unlockedRewards = calculateUnlockedRewards( _aludel.rewardSchedules, remainingRewards, _aludel.rewardSharesOutstanding, timestamp ); // explicit return return unlockedRewards; } function getCurrentTotalStakeUnits() public view override returns (uint256 totalStakeUnits) { // calculate new stake units return getFutureTotalStakeUnits(block.timestamp); } function getFutureTotalStakeUnits(uint256 timestamp) public view override returns (uint256 totalStakeUnits) { // return early if no change if (timestamp == _aludel.lastUpdate) return _aludel.totalStakeUnits; // calculate new stake units uint256 newStakeUnits = calculateStakeUnits(_aludel.totalStake, _aludel.lastUpdate, timestamp); // add to cached total totalStakeUnits = _aludel.totalStakeUnits.add(newStakeUnits); // explicit return return totalStakeUnits; } /* vault getters */ function getVaultData(address vault) external view override returns (VaultData memory vaultData) { return _vaults[vault]; } function getCurrentVaultReward(address vault) external view override returns (uint256 reward) { // calculate rewards return calculateRewardFromStakes( _vaults[vault] .stakes, _vaults[vault] .totalStake, getCurrentUnlockedRewards(), getCurrentTotalStakeUnits(), block .timestamp, _aludel .rewardScaling ) .reward; } function getFutureVaultReward(address vault, uint256 timestamp) external view override returns (uint256 reward) { // calculate rewards return calculateRewardFromStakes( _vaults[vault] .stakes, _vaults[vault] .totalStake, getFutureUnlockedRewards(timestamp), getFutureTotalStakeUnits(timestamp), timestamp, _aludel .rewardScaling ) .reward; } function getCurrentStakeReward(address vault, uint256 stakeAmount) external view override returns (uint256 reward) { // calculate rewards return calculateRewardFromStakes( _vaults[vault] .stakes, stakeAmount, getCurrentUnlockedRewards(), getCurrentTotalStakeUnits(), block .timestamp, _aludel .rewardScaling ) .reward; } function getFutureStakeReward( address vault, uint256 stakeAmount, uint256 timestamp ) external view override returns (uint256 reward) { // calculate rewards return calculateRewardFromStakes( _vaults[vault] .stakes, stakeAmount, getFutureUnlockedRewards(timestamp), getFutureTotalStakeUnits(timestamp), timestamp, _aludel .rewardScaling ) .reward; } function getCurrentVaultStakeUnits(address vault) public view override returns (uint256 stakeUnits) { // calculate stake units return getFutureVaultStakeUnits(vault, block.timestamp); } function getFutureVaultStakeUnits(address vault, uint256 timestamp) public view override returns (uint256 stakeUnits) { // calculate stake units return calculateTotalStakeUnits(_vaults[vault].stakes, timestamp); } /* pure functions */ function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp) public pure override returns (uint256 totalStakeUnits) { for (uint256 index; index < stakes.length; index++) { // reference stake StakeData memory stakeData = stakes[index]; // calculate stake units uint256 stakeUnits = calculateStakeUnits(stakeData.amount, stakeData.timestamp, timestamp); // add to running total totalStakeUnits = totalStakeUnits.add(stakeUnits); } } function calculateStakeUnits( uint256 amount, uint256 start, uint256 end ) public pure override returns (uint256 stakeUnits) { // calculate duration uint256 duration = end.sub(start); // calculate stake units stakeUnits = duration.mul(amount); // explicit return return stakeUnits; } function calculateUnlockedRewards( RewardSchedule[] memory rewardSchedules, uint256 rewardBalance, uint256 sharesOutstanding, uint256 timestamp ) public pure override returns (uint256 unlockedRewards) { // return 0 if no registered schedules if (rewardSchedules.length == 0) { return 0; } // calculate reward shares locked across all reward schedules uint256 sharesLocked; for (uint256 index = 0; index < rewardSchedules.length; index++) { // fetch reward schedule storage reference RewardSchedule memory schedule = rewardSchedules[index]; // caculate amount of shares available on this schedule // if (now - start) < duration // sharesLocked = shares - (shares * (now - start) / duration) // else // sharesLocked = 0 uint256 currentSharesLocked = 0; if (timestamp.sub(schedule.start) < schedule.duration) { currentSharesLocked = schedule.shares.sub( schedule.shares.mul(timestamp.sub(schedule.start)).div(schedule.duration) ); } // add to running total sharesLocked = sharesLocked.add(currentSharesLocked); } // convert shares to reward // rewardLocked = sharesLocked * rewardBalance / sharesOutstanding uint256 rewardLocked = sharesLocked.mul(rewardBalance).div(sharesOutstanding); // calculate amount available // unlockedRewards = rewardBalance - rewardLocked unlockedRewards = rewardBalance.sub(rewardLocked); // explicit return return unlockedRewards; } function calculateRewardFromStakes( StakeData[] memory stakes, uint256 unstakeAmount, uint256 unlockedRewards, uint256 totalStakeUnits, uint256 timestamp, RewardScaling memory rewardScaling ) public pure override returns (RewardOutput memory out) { uint256 stakesToDrop = 0; while (unstakeAmount > 0) { // fetch vault stake storage reference StakeData memory lastStake = stakes[stakes.length.sub(stakesToDrop).sub(1)]; // calculate stake duration uint256 stakeDuration = timestamp.sub(lastStake.timestamp); uint256 currentAmount; if (lastStake.amount > unstakeAmount) { // set current amount to remaining unstake amount currentAmount = unstakeAmount; // amount of last stake is reduced out.lastStakeAmount = lastStake.amount.sub(unstakeAmount); } else { // set current amount to amount of last stake currentAmount = lastStake.amount; // add to stakes to drop stakesToDrop += 1; } // update remaining unstakeAmount unstakeAmount = unstakeAmount.sub(currentAmount); // calculate reward amount uint256 currentReward = calculateReward( unlockedRewards, currentAmount, stakeDuration, totalStakeUnits, rewardScaling ); // update cumulative reward out.reward = out.reward.add(currentReward); // update cached unlockedRewards unlockedRewards = unlockedRewards.sub(currentReward); // calculate time weighted stake uint256 stakeUnits = currentAmount.mul(stakeDuration); // update cached totalStakeUnits totalStakeUnits = totalStakeUnits.sub(stakeUnits); } // explicit return return RewardOutput( out.lastStakeAmount, stakes.length.sub(stakesToDrop), out.reward, totalStakeUnits ); } function calculateReward( uint256 unlockedRewards, uint256 stakeAmount, uint256 stakeDuration, uint256 totalStakeUnits, RewardScaling memory rewardScaling ) public pure override returns (uint256 reward) { // calculate time weighted stake uint256 stakeUnits = stakeAmount.mul(stakeDuration); // calculate base reward // baseReward = unlockedRewards * stakeUnits / totalStakeUnits uint256 baseReward = 0; if (totalStakeUnits != 0) { // scale reward according to proportional weight baseReward = unlockedRewards.mul(stakeUnits).div(totalStakeUnits); } // calculate scaled reward // if no scaling or scaling period completed // reward = baseReward // else // minReward = baseReward * scalingFloor / scalingCeiling // bonusReward = baseReward // * (scalingCeiling - scalingFloor) / scalingCeiling // * duration / scalingTime // reward = minReward + bonusReward if (stakeDuration >= rewardScaling.time || rewardScaling.floor == rewardScaling.ceiling) { // no reward scaling applied reward = baseReward; } else { // calculate minimum reward using scaling floor uint256 minReward = baseReward.mul(rewardScaling.floor).div(rewardScaling.ceiling); // calculate bonus reward with vested portion of scaling factor uint256 bonusReward = baseReward .mul(stakeDuration) .mul(rewardScaling.ceiling.sub(rewardScaling.floor)) .div(rewardScaling.ceiling) .div(rewardScaling.time); // add minimum reward and bonus reward reward = minReward.add(bonusReward); } // explicit return return reward; } /* admin functions */ /// @notice Add funds to the Aludel /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - increase _aludel.rewardSharesOutstanding /// - append to _aludel.rewardSchedules /// token transfer: transfer staking tokens from msg.sender to reward pool /// @param amount uint256 Amount of reward tokens to deposit /// @param duration uint256 Duration over which to linearly unlock rewards function fund(uint256 amount, uint256 duration) external override onlyOwner onlyOnline { // validate duration require(duration != 0, "Aludel: invalid duration"); // create new reward shares // if existing rewards on this Aludel // mint new shares proportional to % change in rewards remaining // newShares = remainingShares * newReward / remainingRewards // else // mint new shares with BASE_SHARES_PER_WEI initial conversion rate // store as fixed point number with same of decimals as reward token uint256 newRewardShares; if (_aludel.rewardSharesOutstanding > 0) { uint256 remainingRewards = IERC20(_aludel.rewardToken).balanceOf(_aludel.rewardPool); newRewardShares = _aludel.rewardSharesOutstanding.mul(amount).div(remainingRewards); } else { newRewardShares = amount.mul(BASE_SHARES_PER_WEI); } // add reward shares to total _aludel.rewardSharesOutstanding = _aludel.rewardSharesOutstanding.add(newRewardShares); // store new reward schedule _aludel.rewardSchedules.push(RewardSchedule(duration, block.timestamp, newRewardShares)); // transfer reward tokens to reward pool TransferHelper.safeTransferFrom( _aludel.rewardToken, msg.sender, _aludel.rewardPool, amount ); // emit event emit AludelFunded(amount, duration); } /// @notice Add vault factory to whitelist /// @dev use this function to enable stakes to vaults coming from the specified /// factory contract /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - append to _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function registerVaultFactory(address factory) external override onlyOwner notShutdown { // add factory to set require(_vaultFactorySet.add(factory), "Aludel: vault factory already registered"); // emit event emit VaultFactoryRegistered(factory); } /// @notice Remove vault factory from whitelist /// @dev use this function to disable new stakes to vaults coming from the specified /// factory contract. /// note: vaults with existing stakes from this factory are sill able to unstake /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - remove from _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function removeVaultFactory(address factory) external override onlyOwner notShutdown { // remove factory from set require(_vaultFactorySet.remove(factory), "Aludel: vault factory not registered"); // emit event emit VaultFactoryRemoved(factory); } /// @notice Register bonus token for distribution /// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - append to _bonusTokenSet /// token transfer: none /// @param bonusToken address The address of the bonus token function registerBonusToken(address bonusToken) external override onlyOwner onlyOnline { // verify valid bonus token _validateAddress(bonusToken); // verify bonus token count require(_bonusTokenSet.length() < MAX_REWARD_TOKENS, "Aludel: max bonus tokens reached "); // add token to set assert(_bonusTokenSet.add(bonusToken)); // emit event emit BonusTokenRegistered(bonusToken); } /// @notice Rescue tokens from RewardPool /// @dev use this function to rescue tokens from RewardPool contract /// without distributing to stakers or triggering emergency shutdown /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: none /// token transfer: transfer requested token from RewardPool to recipient /// @param token address The address of the token to rescue /// @param recipient address The address of the recipient /// @param amount uint256 The amount of tokens to rescue function rescueTokensFromRewardPool( address token, address recipient, uint256 amount ) external override onlyOwner onlyOnline { // verify recipient _validateAddress(recipient); // check not attempting to unstake reward token require(token != _aludel.rewardToken, "Aludel: invalid address"); // check not attempting to wthdraw bonus token require(!_bonusTokenSet.contains(token), "Aludel: invalid address"); // transfer tokens to recipient IRewardPool(_aludel.rewardPool).sendERC20(token, recipient, amount); } /* user functions */ /// @notice Stake tokens /// access control: anyone with a valid permission /// state machine: /// - can be called multiple times /// - only online /// - when vault exists on this Aludel /// state scope: /// - append to _vaults[vault].stakes /// - increase _vaults[vault].totalStake /// - increase _aludel.totalStake /// - increase _aludel.totalStakeUnits /// - increase _aludel.lastUpdate /// token transfer: transfer staking tokens from msg.sender to vault /// @param vault address The address of the vault to stake from /// @param amount uint256 The amount of staking tokens to stake /// @param permission bytes The signed lock permission for the universal vault function stake( address vault, uint256 amount, bytes calldata permission ) external override onlyOnline { // verify vault is valid require(isValidVault(vault), "Aludel: vault is not registered"); // verify non-zero amount require(amount != 0, "Aludel: no amount staked"); // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // verify stakes boundary not reached require( vaultData.stakes.length < MAX_STAKES_PER_VAULT, "Aludel: MAX_STAKES_PER_VAULT reached" ); // update cached sum of stake units across all vaults _updateTotalStakeUnits(); // store amount and timestamp vaultData.stakes.push(StakeData(amount, block.timestamp)); // update cached total vault and Aludel amounts vaultData.totalStake = vaultData.totalStake.add(amount); _aludel.totalStake = _aludel.totalStake.add(amount); // call lock on vault IUniversalVault(vault).lock(_aludel.stakingToken, amount, permission); // emit event emit Staked(vault, amount); } /// @notice Unstake staking tokens and claim reward /// @dev rewards can only be claimed when unstaking, thus reseting the reward multiplier /// access control: anyone with a valid permission /// state machine: /// - when vault exists on this Aludel /// - after stake from vault /// - can be called multiple times while sufficient stake remains /// - only online /// state scope: /// - decrease _aludel.rewardSharesOutstanding /// - decrease _aludel.totalStake /// - increase _aludel.lastUpdate /// - modify _aludel.totalStakeUnits /// - modify _vaults[vault].stakes /// - decrease _vaults[vault].totalStake /// token transfer: /// - transfer reward tokens from reward pool to vault /// - transfer bonus tokens from reward pool to vault /// @param vault address The vault to unstake from /// @param amount uint256 The amount of staking tokens to unstake /// @param permission bytes The signed lock permission for the universal vault function unstakeAndClaim( address vault, uint256 amount, bytes calldata permission ) external override onlyOnline { // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // verify non-zero amount require(amount != 0, "Aludel: no amount unstaked"); // check for sufficient vault stake amount require(vaultData.totalStake >= amount, "Aludel: insufficient vault stake"); // check for sufficient Aludel stake amount // if this check fails, there is a bug in stake accounting assert(_aludel.totalStake >= amount); // update cached sum of stake units across all vaults _updateTotalStakeUnits(); // get reward amount remaining uint256 remainingRewards = IERC20(_aludel.rewardToken).balanceOf(_aludel.rewardPool); // calculate vested portion of reward pool uint256 unlockedRewards = calculateUnlockedRewards( _aludel.rewardSchedules, remainingRewards, _aludel.rewardSharesOutstanding, block.timestamp ); // calculate vault time weighted reward with scaling RewardOutput memory out = calculateRewardFromStakes( vaultData.stakes, amount, unlockedRewards, _aludel.totalStakeUnits, block.timestamp, _aludel.rewardScaling ); // update stake data in storage if (out.newStakesCount == 0) { // all stakes have been unstaked delete vaultData.stakes; } else { // some stakes have been completely or partially unstaked // delete fully unstaked stakes while (vaultData.stakes.length > out.newStakesCount) vaultData.stakes.pop(); // update stake amount when lastStakeAmount is set if (out.lastStakeAmount > 0) { // update partially unstaked stake vaultData.stakes[out.newStakesCount.sub(1)].amount = out.lastStakeAmount; } } // update cached stake totals vaultData.totalStake = vaultData.totalStake.sub(amount); _aludel.totalStake = _aludel.totalStake.sub(amount); _aludel.totalStakeUnits = out.newTotalStakeUnits; // unlock staking tokens from vault IUniversalVault(vault).unlock(_aludel.stakingToken, amount, permission); // emit event emit Unstaked(vault, amount); // only perform on non-zero reward if (out.reward > 0) { // calculate shares to burn // sharesToBurn = sharesOutstanding * reward / remainingRewards uint256 sharesToBurn = _aludel.rewardSharesOutstanding.mul(out.reward).div(remainingRewards); // burn claimed shares _aludel.rewardSharesOutstanding = _aludel.rewardSharesOutstanding.sub(sharesToBurn); // transfer bonus tokens from reward pool to vault if (_bonusTokenSet.length() > 0) { for (uint256 index = 0; index < _bonusTokenSet.length(); index++) { // fetch bonus token address reference address bonusToken = _bonusTokenSet.at(index); // calculate bonus token amount // bonusAmount = bonusRemaining * reward / remainingRewards uint256 bonusAmount = IERC20(bonusToken).balanceOf(_aludel.rewardPool).mul(out.reward).div( remainingRewards ); // transfer bonus token IRewardPool(_aludel.rewardPool).sendERC20(bonusToken, vault, bonusAmount); // emit event emit RewardClaimed(vault, bonusToken, bonusAmount); } } // transfer reward tokens from reward pool to vault IRewardPool(_aludel.rewardPool).sendERC20(_aludel.rewardToken, vault, out.reward); // emit event emit RewardClaimed(vault, _aludel.rewardToken, out.reward); } } /// @notice Exit Aludel without claiming reward /// @dev This function should never revert when correctly called by the vault. /// A max number of stakes per vault is set with MAX_STAKES_PER_VAULT to /// place an upper bound on the for loop in calculateTotalStakeUnits(). /// access control: only callable by the vault directly /// state machine: /// - when vault exists on this Aludel /// - when active stake from this vault /// - any power state /// state scope: /// - decrease _aludel.totalStake /// - increase _aludel.lastUpdate /// - modify _aludel.totalStakeUnits /// - delete _vaults[vault] /// token transfer: none function rageQuit() external override { // fetch vault storage reference VaultData storage _vaultData = _vaults[msg.sender]; // revert if no active stakes require(_vaultData.stakes.length != 0, "Aludel: no stake"); // update cached sum of stake units across all vaults _updateTotalStakeUnits(); // emit event emit Unstaked(msg.sender, _vaultData.totalStake); // update cached totals _aludel.totalStake = _aludel.totalStake.sub(_vaultData.totalStake); _aludel.totalStakeUnits = _aludel.totalStakeUnits.sub( calculateTotalStakeUnits(_vaultData.stakes, block.timestamp) ); // delete stake data delete _vaults[msg.sender]; } /* convenience functions */ function _updateTotalStakeUnits() private { // update cached totalStakeUnits _aludel.totalStakeUnits = getCurrentTotalStakeUnits(); // update cached lastUpdate _aludel.lastUpdate = block.timestamp; } function _validateAddress(address target) private view { // sanity check target for potential input errors require(isValidAddress(target), "Aludel: invalid address"); } function _truncateStakesArray(StakeData[] memory array, uint256 newLength) private pure returns (StakeData[] memory newArray) { newArray = new StakeData[](newLength); for (uint256 index = 0; index < newLength; index++) { newArray[index] = array[index]; } return newArray; } }
contract Aludel is IAludel, Powered, Ownable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /* constants */ // An upper bound on the number of active stakes per vault is required to prevent // calls to rageQuit() from reverting. // With 30 stakes in a vault, ragequit costs 432811 gas which is conservatively lower // than the hardcoded limit of 500k gas on the vault. // This limit is configurable and could be increased in a future deployment. // Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide // an error code that allows for reliably catching out-of-gas errors on remote calls. uint256 public constant MAX_STAKES_PER_VAULT = 30; uint256 public constant MAX_REWARD_TOKENS = 50; uint256 public constant BASE_SHARES_PER_WEI = 1000000; /* storage */ AludelData private _aludel; mapping(address => VaultData) private _vaults; EnumerableSet.AddressSet private _bonusTokenSet; EnumerableSet.AddressSet private _vaultFactorySet; /* initializer */ /// @notice Initizalize Aludel /// access control: only proxy constructor /// state machine: can only be called once /// state scope: set initialization variables /// token transfer: none /// @param ownerAddress address The admin address /// @param rewardPoolFactory address The factory to use for deploying the RewardPool /// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch /// @param stakingToken address The address of the staking token for this Aludel /// @param rewardToken address The address of the reward token for this Aludel /// @param rewardScaling RewardScaling The config for reward scaling floor, ceiling, and time constructor( address ownerAddress, address rewardPoolFactory, address powerSwitchFactory, address stakingToken, address rewardToken, RewardScaling memory rewardScaling ) { // the scaling floor must be smaller than ceiling require(rewardScaling.floor <= rewardScaling.ceiling, "Aludel: floor above ceiling"); // setting rewardScalingTime to 0 would cause divide by zero error // to disable reward scaling, use rewardScalingFloor == rewardScalingCeiling require(rewardScaling.time != 0, "Aludel: scaling time cannot be zero"); // deploy power switch address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(ownerAddress)); // deploy reward pool address rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch)); // set internal configs Ownable.transferOwnership(ownerAddress); Powered._setPowerSwitch(powerSwitch); // commit to storage _aludel.stakingToken = stakingToken; _aludel.rewardToken = rewardToken; _aludel.rewardPool = rewardPool; _aludel.rewardScaling = rewardScaling; // emit event emit AludelCreated(rewardPool, powerSwitch); } /* getter functions */ function getBonusTokenSetLength() external view override returns (uint256 length) { return _bonusTokenSet.length(); } function getBonusTokenAtIndex(uint256 index) external view override returns (address bonusToken) { return _bonusTokenSet.at(index); } function getVaultFactorySetLength() external view override returns (uint256 length) { return _vaultFactorySet.length(); } function getVaultFactoryAtIndex(uint256 index) external view override returns (address factory) { return _vaultFactorySet.at(index); } function isValidVault(address target) public view override returns (bool validity) { // validate target is created from whitelisted vault factory for (uint256 index = 0; index < _vaultFactorySet.length(); index++) { if (IInstanceRegistry(_vaultFactorySet.at(index)).isInstance(target)) { return true; } } // explicit return return false; } function isValidAddress(address target) public view override returns (bool validity) { // sanity check target for potential input errors return target != address(this) && target != address(0) && target != _aludel.stakingToken && target != _aludel.rewardToken && target != _aludel.rewardPool && !_bonusTokenSet.contains(target); } /* Aludel getters */ function getAludelData() external view override returns (AludelData memory aludel) { return _aludel; } function getCurrentUnlockedRewards() public view override returns (uint256 unlockedRewards) { // calculate reward available based on state return getFutureUnlockedRewards(block.timestamp); } function getFutureUnlockedRewards(uint256 timestamp) public view override returns (uint256 unlockedRewards) { // get reward amount remaining uint256 remainingRewards = IERC20(_aludel.rewardToken).balanceOf(_aludel.rewardPool); // calculate reward available based on state unlockedRewards = calculateUnlockedRewards( _aludel.rewardSchedules, remainingRewards, _aludel.rewardSharesOutstanding, timestamp ); // explicit return return unlockedRewards; } function getCurrentTotalStakeUnits() public view override returns (uint256 totalStakeUnits) { // calculate new stake units return getFutureTotalStakeUnits(block.timestamp); } function getFutureTotalStakeUnits(uint256 timestamp) public view override returns (uint256 totalStakeUnits) { // return early if no change if (timestamp == _aludel.lastUpdate) return _aludel.totalStakeUnits; // calculate new stake units uint256 newStakeUnits = calculateStakeUnits(_aludel.totalStake, _aludel.lastUpdate, timestamp); // add to cached total totalStakeUnits = _aludel.totalStakeUnits.add(newStakeUnits); // explicit return return totalStakeUnits; } /* vault getters */ function getVaultData(address vault) external view override returns (VaultData memory vaultData) { return _vaults[vault]; } function getCurrentVaultReward(address vault) external view override returns (uint256 reward) { // calculate rewards return calculateRewardFromStakes( _vaults[vault] .stakes, _vaults[vault] .totalStake, getCurrentUnlockedRewards(), getCurrentTotalStakeUnits(), block .timestamp, _aludel .rewardScaling ) .reward; } function getFutureVaultReward(address vault, uint256 timestamp) external view override returns (uint256 reward) { // calculate rewards return calculateRewardFromStakes( _vaults[vault] .stakes, _vaults[vault] .totalStake, getFutureUnlockedRewards(timestamp), getFutureTotalStakeUnits(timestamp), timestamp, _aludel .rewardScaling ) .reward; } function getCurrentStakeReward(address vault, uint256 stakeAmount) external view override returns (uint256 reward) { // calculate rewards return calculateRewardFromStakes( _vaults[vault] .stakes, stakeAmount, getCurrentUnlockedRewards(), getCurrentTotalStakeUnits(), block .timestamp, _aludel .rewardScaling ) .reward; } function getFutureStakeReward( address vault, uint256 stakeAmount, uint256 timestamp ) external view override returns (uint256 reward) { // calculate rewards return calculateRewardFromStakes( _vaults[vault] .stakes, stakeAmount, getFutureUnlockedRewards(timestamp), getFutureTotalStakeUnits(timestamp), timestamp, _aludel .rewardScaling ) .reward; } function getCurrentVaultStakeUnits(address vault) public view override returns (uint256 stakeUnits) { // calculate stake units return getFutureVaultStakeUnits(vault, block.timestamp); } function getFutureVaultStakeUnits(address vault, uint256 timestamp) public view override returns (uint256 stakeUnits) { // calculate stake units return calculateTotalStakeUnits(_vaults[vault].stakes, timestamp); } /* pure functions */ function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp) public pure override returns (uint256 totalStakeUnits) { for (uint256 index; index < stakes.length; index++) { // reference stake StakeData memory stakeData = stakes[index]; // calculate stake units uint256 stakeUnits = calculateStakeUnits(stakeData.amount, stakeData.timestamp, timestamp); // add to running total totalStakeUnits = totalStakeUnits.add(stakeUnits); } } function calculateStakeUnits( uint256 amount, uint256 start, uint256 end ) public pure override returns (uint256 stakeUnits) { // calculate duration uint256 duration = end.sub(start); // calculate stake units stakeUnits = duration.mul(amount); // explicit return return stakeUnits; } function calculateUnlockedRewards( RewardSchedule[] memory rewardSchedules, uint256 rewardBalance, uint256 sharesOutstanding, uint256 timestamp ) public pure override returns (uint256 unlockedRewards) { // return 0 if no registered schedules if (rewardSchedules.length == 0) { return 0; } // calculate reward shares locked across all reward schedules uint256 sharesLocked; for (uint256 index = 0; index < rewardSchedules.length; index++) { // fetch reward schedule storage reference RewardSchedule memory schedule = rewardSchedules[index]; // caculate amount of shares available on this schedule // if (now - start) < duration // sharesLocked = shares - (shares * (now - start) / duration) // else // sharesLocked = 0 uint256 currentSharesLocked = 0; if (timestamp.sub(schedule.start) < schedule.duration) { currentSharesLocked = schedule.shares.sub( schedule.shares.mul(timestamp.sub(schedule.start)).div(schedule.duration) ); } // add to running total sharesLocked = sharesLocked.add(currentSharesLocked); } // convert shares to reward // rewardLocked = sharesLocked * rewardBalance / sharesOutstanding uint256 rewardLocked = sharesLocked.mul(rewardBalance).div(sharesOutstanding); // calculate amount available // unlockedRewards = rewardBalance - rewardLocked unlockedRewards = rewardBalance.sub(rewardLocked); // explicit return return unlockedRewards; } function calculateRewardFromStakes( StakeData[] memory stakes, uint256 unstakeAmount, uint256 unlockedRewards, uint256 totalStakeUnits, uint256 timestamp, RewardScaling memory rewardScaling ) public pure override returns (RewardOutput memory out) { uint256 stakesToDrop = 0; while (unstakeAmount > 0) { // fetch vault stake storage reference StakeData memory lastStake = stakes[stakes.length.sub(stakesToDrop).sub(1)]; // calculate stake duration uint256 stakeDuration = timestamp.sub(lastStake.timestamp); uint256 currentAmount; if (lastStake.amount > unstakeAmount) { // set current amount to remaining unstake amount currentAmount = unstakeAmount; // amount of last stake is reduced out.lastStakeAmount = lastStake.amount.sub(unstakeAmount); } else { // set current amount to amount of last stake currentAmount = lastStake.amount; // add to stakes to drop stakesToDrop += 1; } // update remaining unstakeAmount unstakeAmount = unstakeAmount.sub(currentAmount); // calculate reward amount uint256 currentReward = calculateReward( unlockedRewards, currentAmount, stakeDuration, totalStakeUnits, rewardScaling ); // update cumulative reward out.reward = out.reward.add(currentReward); // update cached unlockedRewards unlockedRewards = unlockedRewards.sub(currentReward); // calculate time weighted stake uint256 stakeUnits = currentAmount.mul(stakeDuration); // update cached totalStakeUnits totalStakeUnits = totalStakeUnits.sub(stakeUnits); } // explicit return return RewardOutput( out.lastStakeAmount, stakes.length.sub(stakesToDrop), out.reward, totalStakeUnits ); } function calculateReward( uint256 unlockedRewards, uint256 stakeAmount, uint256 stakeDuration, uint256 totalStakeUnits, RewardScaling memory rewardScaling ) public pure override returns (uint256 reward) { // calculate time weighted stake uint256 stakeUnits = stakeAmount.mul(stakeDuration); // calculate base reward // baseReward = unlockedRewards * stakeUnits / totalStakeUnits uint256 baseReward = 0; if (totalStakeUnits != 0) { // scale reward according to proportional weight baseReward = unlockedRewards.mul(stakeUnits).div(totalStakeUnits); } // calculate scaled reward // if no scaling or scaling period completed // reward = baseReward // else // minReward = baseReward * scalingFloor / scalingCeiling // bonusReward = baseReward // * (scalingCeiling - scalingFloor) / scalingCeiling // * duration / scalingTime // reward = minReward + bonusReward if (stakeDuration >= rewardScaling.time || rewardScaling.floor == rewardScaling.ceiling) { // no reward scaling applied reward = baseReward; } else { // calculate minimum reward using scaling floor uint256 minReward = baseReward.mul(rewardScaling.floor).div(rewardScaling.ceiling); // calculate bonus reward with vested portion of scaling factor uint256 bonusReward = baseReward .mul(stakeDuration) .mul(rewardScaling.ceiling.sub(rewardScaling.floor)) .div(rewardScaling.ceiling) .div(rewardScaling.time); // add minimum reward and bonus reward reward = minReward.add(bonusReward); } // explicit return return reward; } /* admin functions */ /// @notice Add funds to the Aludel /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - increase _aludel.rewardSharesOutstanding /// - append to _aludel.rewardSchedules /// token transfer: transfer staking tokens from msg.sender to reward pool /// @param amount uint256 Amount of reward tokens to deposit /// @param duration uint256 Duration over which to linearly unlock rewards function fund(uint256 amount, uint256 duration) external override onlyOwner onlyOnline { // validate duration require(duration != 0, "Aludel: invalid duration"); // create new reward shares // if existing rewards on this Aludel // mint new shares proportional to % change in rewards remaining // newShares = remainingShares * newReward / remainingRewards // else // mint new shares with BASE_SHARES_PER_WEI initial conversion rate // store as fixed point number with same of decimals as reward token uint256 newRewardShares; if (_aludel.rewardSharesOutstanding > 0) { uint256 remainingRewards = IERC20(_aludel.rewardToken).balanceOf(_aludel.rewardPool); newRewardShares = _aludel.rewardSharesOutstanding.mul(amount).div(remainingRewards); } else { newRewardShares = amount.mul(BASE_SHARES_PER_WEI); } // add reward shares to total _aludel.rewardSharesOutstanding = _aludel.rewardSharesOutstanding.add(newRewardShares); // store new reward schedule _aludel.rewardSchedules.push(RewardSchedule(duration, block.timestamp, newRewardShares)); // transfer reward tokens to reward pool TransferHelper.safeTransferFrom( _aludel.rewardToken, msg.sender, _aludel.rewardPool, amount ); // emit event emit AludelFunded(amount, duration); } /// @notice Add vault factory to whitelist /// @dev use this function to enable stakes to vaults coming from the specified /// factory contract /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - append to _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function registerVaultFactory(address factory) external override onlyOwner notShutdown { // add factory to set require(_vaultFactorySet.add(factory), "Aludel: vault factory already registered"); // emit event emit VaultFactoryRegistered(factory); } /// @notice Remove vault factory from whitelist /// @dev use this function to disable new stakes to vaults coming from the specified /// factory contract. /// note: vaults with existing stakes from this factory are sill able to unstake /// access control: only admin /// state machine: /// - can be called multiple times /// - not shutdown /// state scope: /// - remove from _vaultFactorySet /// token transfer: none /// @param factory address The address of the vault factory function removeVaultFactory(address factory) external override onlyOwner notShutdown { // remove factory from set require(_vaultFactorySet.remove(factory), "Aludel: vault factory not registered"); // emit event emit VaultFactoryRemoved(factory); } /// @notice Register bonus token for distribution /// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: /// - append to _bonusTokenSet /// token transfer: none /// @param bonusToken address The address of the bonus token function registerBonusToken(address bonusToken) external override onlyOwner onlyOnline { // verify valid bonus token _validateAddress(bonusToken); // verify bonus token count require(_bonusTokenSet.length() < MAX_REWARD_TOKENS, "Aludel: max bonus tokens reached "); // add token to set assert(_bonusTokenSet.add(bonusToken)); // emit event emit BonusTokenRegistered(bonusToken); } /// @notice Rescue tokens from RewardPool /// @dev use this function to rescue tokens from RewardPool contract /// without distributing to stakers or triggering emergency shutdown /// access control: only admin /// state machine: /// - can be called multiple times /// - only online /// state scope: none /// token transfer: transfer requested token from RewardPool to recipient /// @param token address The address of the token to rescue /// @param recipient address The address of the recipient /// @param amount uint256 The amount of tokens to rescue function rescueTokensFromRewardPool( address token, address recipient, uint256 amount ) external override onlyOwner onlyOnline { // verify recipient _validateAddress(recipient); // check not attempting to unstake reward token require(token != _aludel.rewardToken, "Aludel: invalid address"); // check not attempting to wthdraw bonus token require(!_bonusTokenSet.contains(token), "Aludel: invalid address"); // transfer tokens to recipient IRewardPool(_aludel.rewardPool).sendERC20(token, recipient, amount); } /* user functions */ /// @notice Stake tokens /// access control: anyone with a valid permission /// state machine: /// - can be called multiple times /// - only online /// - when vault exists on this Aludel /// state scope: /// - append to _vaults[vault].stakes /// - increase _vaults[vault].totalStake /// - increase _aludel.totalStake /// - increase _aludel.totalStakeUnits /// - increase _aludel.lastUpdate /// token transfer: transfer staking tokens from msg.sender to vault /// @param vault address The address of the vault to stake from /// @param amount uint256 The amount of staking tokens to stake /// @param permission bytes The signed lock permission for the universal vault function stake( address vault, uint256 amount, bytes calldata permission ) external override onlyOnline { // verify vault is valid require(isValidVault(vault), "Aludel: vault is not registered"); // verify non-zero amount require(amount != 0, "Aludel: no amount staked"); // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // verify stakes boundary not reached require( vaultData.stakes.length < MAX_STAKES_PER_VAULT, "Aludel: MAX_STAKES_PER_VAULT reached" ); // update cached sum of stake units across all vaults _updateTotalStakeUnits(); // store amount and timestamp vaultData.stakes.push(StakeData(amount, block.timestamp)); // update cached total vault and Aludel amounts vaultData.totalStake = vaultData.totalStake.add(amount); _aludel.totalStake = _aludel.totalStake.add(amount); // call lock on vault IUniversalVault(vault).lock(_aludel.stakingToken, amount, permission); // emit event emit Staked(vault, amount); } /// @notice Unstake staking tokens and claim reward /// @dev rewards can only be claimed when unstaking, thus reseting the reward multiplier /// access control: anyone with a valid permission /// state machine: /// - when vault exists on this Aludel /// - after stake from vault /// - can be called multiple times while sufficient stake remains /// - only online /// state scope: /// - decrease _aludel.rewardSharesOutstanding /// - decrease _aludel.totalStake /// - increase _aludel.lastUpdate /// - modify _aludel.totalStakeUnits /// - modify _vaults[vault].stakes /// - decrease _vaults[vault].totalStake /// token transfer: /// - transfer reward tokens from reward pool to vault /// - transfer bonus tokens from reward pool to vault /// @param vault address The vault to unstake from /// @param amount uint256 The amount of staking tokens to unstake /// @param permission bytes The signed lock permission for the universal vault function unstakeAndClaim( address vault, uint256 amount, bytes calldata permission ) external override onlyOnline { // fetch vault storage reference VaultData storage vaultData = _vaults[vault]; // verify non-zero amount require(amount != 0, "Aludel: no amount unstaked"); // check for sufficient vault stake amount require(vaultData.totalStake >= amount, "Aludel: insufficient vault stake"); // check for sufficient Aludel stake amount // if this check fails, there is a bug in stake accounting assert(_aludel.totalStake >= amount); // update cached sum of stake units across all vaults _updateTotalStakeUnits(); // get reward amount remaining uint256 remainingRewards = IERC20(_aludel.rewardToken).balanceOf(_aludel.rewardPool); // calculate vested portion of reward pool uint256 unlockedRewards = calculateUnlockedRewards( _aludel.rewardSchedules, remainingRewards, _aludel.rewardSharesOutstanding, block.timestamp ); // calculate vault time weighted reward with scaling RewardOutput memory out = calculateRewardFromStakes( vaultData.stakes, amount, unlockedRewards, _aludel.totalStakeUnits, block.timestamp, _aludel.rewardScaling ); // update stake data in storage if (out.newStakesCount == 0) { // all stakes have been unstaked delete vaultData.stakes; } else { // some stakes have been completely or partially unstaked // delete fully unstaked stakes while (vaultData.stakes.length > out.newStakesCount) vaultData.stakes.pop(); // update stake amount when lastStakeAmount is set if (out.lastStakeAmount > 0) { // update partially unstaked stake vaultData.stakes[out.newStakesCount.sub(1)].amount = out.lastStakeAmount; } } // update cached stake totals vaultData.totalStake = vaultData.totalStake.sub(amount); _aludel.totalStake = _aludel.totalStake.sub(amount); _aludel.totalStakeUnits = out.newTotalStakeUnits; // unlock staking tokens from vault IUniversalVault(vault).unlock(_aludel.stakingToken, amount, permission); // emit event emit Unstaked(vault, amount); // only perform on non-zero reward if (out.reward > 0) { // calculate shares to burn // sharesToBurn = sharesOutstanding * reward / remainingRewards uint256 sharesToBurn = _aludel.rewardSharesOutstanding.mul(out.reward).div(remainingRewards); // burn claimed shares _aludel.rewardSharesOutstanding = _aludel.rewardSharesOutstanding.sub(sharesToBurn); // transfer bonus tokens from reward pool to vault if (_bonusTokenSet.length() > 0) { for (uint256 index = 0; index < _bonusTokenSet.length(); index++) { // fetch bonus token address reference address bonusToken = _bonusTokenSet.at(index); // calculate bonus token amount // bonusAmount = bonusRemaining * reward / remainingRewards uint256 bonusAmount = IERC20(bonusToken).balanceOf(_aludel.rewardPool).mul(out.reward).div( remainingRewards ); // transfer bonus token IRewardPool(_aludel.rewardPool).sendERC20(bonusToken, vault, bonusAmount); // emit event emit RewardClaimed(vault, bonusToken, bonusAmount); } } // transfer reward tokens from reward pool to vault IRewardPool(_aludel.rewardPool).sendERC20(_aludel.rewardToken, vault, out.reward); // emit event emit RewardClaimed(vault, _aludel.rewardToken, out.reward); } } /// @notice Exit Aludel without claiming reward /// @dev This function should never revert when correctly called by the vault. /// A max number of stakes per vault is set with MAX_STAKES_PER_VAULT to /// place an upper bound on the for loop in calculateTotalStakeUnits(). /// access control: only callable by the vault directly /// state machine: /// - when vault exists on this Aludel /// - when active stake from this vault /// - any power state /// state scope: /// - decrease _aludel.totalStake /// - increase _aludel.lastUpdate /// - modify _aludel.totalStakeUnits /// - delete _vaults[vault] /// token transfer: none function rageQuit() external override { // fetch vault storage reference VaultData storage _vaultData = _vaults[msg.sender]; // revert if no active stakes require(_vaultData.stakes.length != 0, "Aludel: no stake"); // update cached sum of stake units across all vaults _updateTotalStakeUnits(); // emit event emit Unstaked(msg.sender, _vaultData.totalStake); // update cached totals _aludel.totalStake = _aludel.totalStake.sub(_vaultData.totalStake); _aludel.totalStakeUnits = _aludel.totalStakeUnits.sub( calculateTotalStakeUnits(_vaultData.stakes, block.timestamp) ); // delete stake data delete _vaults[msg.sender]; } /* convenience functions */ function _updateTotalStakeUnits() private { // update cached totalStakeUnits _aludel.totalStakeUnits = getCurrentTotalStakeUnits(); // update cached lastUpdate _aludel.lastUpdate = block.timestamp; } function _validateAddress(address target) private view { // sanity check target for potential input errors require(isValidAddress(target), "Aludel: invalid address"); } function _truncateStakesArray(StakeData[] memory array, uint256 newLength) private pure returns (StakeData[] memory newArray) { newArray = new StakeData[](newLength); for (uint256 index = 0; index < newLength; index++) { newArray[index] = array[index]; } return newArray; } }
6,107
122
// Sets the maximum bet _max_bet the new maximum bet /
function setMaxBet(uint256 _max_bet) external onlyOwner { max_bet = _max_bet; }
function setMaxBet(uint256 _max_bet) external onlyOwner { max_bet = _max_bet; }
5,868
99
// the user balance to work with (share asset) from the user's balance index
UserBalance storage ub = us.userBalances[balanceIndex];
UserBalance storage ub = us.userBalances[balanceIndex];
21,892
50
// Whitelist Spotter to read the Osm data (only necessary if it is the first time the token is being added to an ilk) !!!!!!!! Only if PIP_BAL = Osm or PIP_BAL = Median and hasn't been already whitelisted due a previous deployed ilk
OsmAbstract(PIP_BAL).kiss(MCD_SPOT);
OsmAbstract(PIP_BAL).kiss(MCD_SPOT);
31,767
528
// solium-disable function-order Below, a few functions must be public to allow bytes memory parameters, but their being so triggers errors because public functions should be grouped below external functions. Since these would be external if it were possible, we ignore the issue.
contract DepositLog {
contract DepositLog {
31,736
28
// Ensure executed price is not lower than the order price: executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator
require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" );
require( executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator), "limit price not satisfied" );
19,772
338
// Overflows are incredibly unrealistic. balance or numberMinted overflow if current value of either + quantity > 1.8e19 (264) - 1 _totalMinted overflows if _totalMinted + amount > 1.2e77 (2256) - 1
unchecked { _incrementAddressMintCounter(buyer, amount); _totalMinted += uint64(amount); }
unchecked { _incrementAddressMintCounter(buyer, amount); _totalMinted += uint64(amount); }
19,227
83
// Allow any customer who hold tokens to claim BTC tokenAmount Amount of tokens to be exchanged (needs to be multiplied by 10^18) userBtcAddress BTC address on which users willing to receive payment/!\ gas cost for calling this method : 37kgas /!\ /
function claimBTC(uint256 tokenAmount, string memory userBtcAddress) public virtual returns (bool) { _transfer(_msgSender(), owner(), tokenAmount); emit BtcToBePaid(_msgSender(), userBtcAddress, tokenAmount); return true; }
function claimBTC(uint256 tokenAmount, string memory userBtcAddress) public virtual returns (bool) { _transfer(_msgSender(), owner(), tokenAmount); emit BtcToBePaid(_msgSender(), userBtcAddress, tokenAmount); return true; }
84,153
195
// Redeem bonds. Parameters ---------------- |redemption_epochs|: An array of bonds to be redeemed. The bonds are identified by their redemption epochs. Returns ---------------- The number of successfully redeemed bonds.
function redeemBonds(uint[] memory redemption_epochs)
function redeemBonds(uint[] memory redemption_epochs)
13,896
203
// Calculate value for ERC20
address[] memory fromAddresses = new address[](tokenAddresses.length - 1); // Sub ETH uint256[] memory amounts = new uint256[](tokenAddresses.length - 1); uint index = 0; for (uint256 i = 1; i < tokenAddresses.length; i++) { fromAddresses[index] = tokenAddresses[i]; amounts[index] = IERC20(tokenAddresses[i]).balanceOf(address(this)); index++; }
address[] memory fromAddresses = new address[](tokenAddresses.length - 1); // Sub ETH uint256[] memory amounts = new uint256[](tokenAddresses.length - 1); uint index = 0; for (uint256 i = 1; i < tokenAddresses.length; i++) { fromAddresses[index] = tokenAddresses[i]; amounts[index] = IERC20(tokenAddresses[i]).balanceOf(address(this)); index++; }
3,902
13
// address(0) turns this contract into a native token staking pool
if(address(stakeToken) == address(0)) { isNativeTokenStaking = true; }
if(address(stakeToken) == address(0)) { isNativeTokenStaking = true; }
38,433
243
// Get this addesses contribution record
OrderBook storage order = orders[_addressToApprove];
OrderBook storage order = orders[_addressToApprove];
25,717
76
// If `account` had not been already granted `role`, emits a {RoleGranted}event. Requirements: - the caller must have ``role``'s admin role. /
function grantRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), 'AccessControl: sender must be an admin to grant'); _grantRole(role, account); }
function grantRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), 'AccessControl: sender must be an admin to grant'); _grantRole(role, account); }
20,048
6
// Flag to mark if a pause caused the fee to be waived. /
bool feeWaived;
bool feeWaived;
9,946
175
// Verify the Lengths add up to calldata size
verifyProofLength(add4(mul32(3), blockHeaderLength, transactionRootLength, transactionsLength))
verifyProofLength(add4(mul32(3), blockHeaderLength, transactionRootLength, transactionsLength))
21,505
21
// Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred /
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
4,543
20
// total number of tokens initially simplified from wei
function initialARXtokenSupply() constant returns (uint256 initialARXtokenSupplyCount) { initialARXtokenSupplyCount = safeDiv(initialARXSupplyInWei,1 ether); }
function initialARXtokenSupply() constant returns (uint256 initialARXtokenSupplyCount) { initialARXtokenSupplyCount = safeDiv(initialARXSupplyInWei,1 ether); }
26,885
22
// Only copy if we aren't removing the last index
if(nEndingIndex != a_nIndex) {
if(nEndingIndex != a_nIndex) {
31,128
43
// Cached data for the protocol fee
ProtocolFeeData protocolFeeData; ModeTime modeTime;
ProtocolFeeData protocolFeeData; ModeTime modeTime;
27,395
127
// See {IERC721Metadata-tokenURI}./
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")): ""; }
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")): ""; }
4,157
12
// can't claim any rewards from before sleep time
owner.pepeDebt = (accPepePerShare * owner.shareSize) / 1e12; totalShares += owner.shareSize; totalAsleep += userBalance; emit Sleep(msg.sender, block.timestamp + _seconds);
owner.pepeDebt = (accPepePerShare * owner.shareSize) / 1e12; totalShares += owner.shareSize; totalAsleep += userBalance; emit Sleep(msg.sender, block.timestamp + _seconds);
5,150
19
// Core harvest function.Get rewards from markets entered /
function _claimRewards() internal { IRewardDistributor(rewardDistributor).claimReward(0, payable(address(this)), markets); if (isNearRewardActive) { IRewardDistributor(rewardDistributor).claimReward(nearRewardIndex, payable(address(this)), markets); } }
function _claimRewards() internal { IRewardDistributor(rewardDistributor).claimReward(0, payable(address(this)), markets); if (isNearRewardActive) { IRewardDistributor(rewardDistributor).claimReward(nearRewardIndex, payable(address(this)), markets); } }
33,779
166
// |/Deposit (lock) funds to the relay contract for cross-chain transfer/
function deposit( address receiver, uint256 amount, uint256 toChainId
function deposit( address receiver, uint256 amount, uint256 toChainId
44,506
60
// Adds to a user's timelock balance.It will attempt to sweep before updating the balance./ Note that this will overwrite the previous unlock timestamp./user The user whose timelock balance should increase/amount The amount to increase by/timestamp The new unlock timestamp
function _mintTimelock(address user, uint256 amount, uint256 timestamp) internal { // Sweep the old balance, if any address[] memory users = new address[](1); users[0] = user; _sweepTimelockBalances(users); timelockTotalSupply = timelockTotalSupply.add(amount); _timelockBalances[user] = _timelockBalances[user].add(amount); _unlockTimestamps[user] = timestamp; // if the funds should already be unlocked if (timestamp <= _currentTime()) { _sweepTimelockBalances(users); } }
function _mintTimelock(address user, uint256 amount, uint256 timestamp) internal { // Sweep the old balance, if any address[] memory users = new address[](1); users[0] = user; _sweepTimelockBalances(users); timelockTotalSupply = timelockTotalSupply.add(amount); _timelockBalances[user] = _timelockBalances[user].add(amount); _unlockTimestamps[user] = timestamp; // if the funds should already be unlocked if (timestamp <= _currentTime()) { _sweepTimelockBalances(users); } }
16,378
59
// Total ETH
uint256 private _totalETH;
uint256 private _totalETH;
34,603
3
// List of all games tracked by the Nova Game contract
uint[] public games;
uint[] public games;
43,611
137
// vars added for v3
bool private v3Initialized; IRewardsDistributor private rewardsDistributor;
bool private v3Initialized; IRewardsDistributor private rewardsDistributor;
75,836
184
// YVAULT with Governance.
contract YVAULT is ERC20, Ownable { using SafeMath for uint256; uint256 public constant initialSupply = 1000; // 1k constructor () public ERC20("YVAULT.FINANCE", "YVAULT", 18, 2, initialSupply) { createUniswapPairMainnet(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); } IUniswapV2Router02 public uniswapRouterV2; IUniswapV2Factory public uniswapFactory; address public tokenUniswapPair; function createUniswapPairMainnet(address router, address factory) onlyOwner public returns (address) { uniswapRouterV2 = IUniswapV2Router02(router != address(0) ? router : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // For testing uniswapFactory = IUniswapV2Factory(factory != address(0) ? factory : 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); // For testing require(tokenUniswapPair == address(0), "Token: pool already created"); tokenUniswapPair = uniswapFactory.createPair( address(uniswapRouterV2.WETH()), address(this) ); return tokenUniswapPair; } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function setBurnrate(uint8 burnrate_) public onlyOwner { _setupBurnrate(burnrate_); } function setBurnEnable(bool burnEnabled_) public onlyOwner { _setBurnEnable(burnEnabled_); } function setYvaultMaster(address _yvaultMaster) public onlyOwner { _setYvaultMaster(_yvaultMaster); } /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "YVAULT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "YVAULT::delegateBySig: invalid nonce"); require(now <= expiry, "YVAULT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "YVAULT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying YVAULTs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "YVAULT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract YVAULT is ERC20, Ownable { using SafeMath for uint256; uint256 public constant initialSupply = 1000; // 1k constructor () public ERC20("YVAULT.FINANCE", "YVAULT", 18, 2, initialSupply) { createUniswapPairMainnet(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); } IUniswapV2Router02 public uniswapRouterV2; IUniswapV2Factory public uniswapFactory; address public tokenUniswapPair; function createUniswapPairMainnet(address router, address factory) onlyOwner public returns (address) { uniswapRouterV2 = IUniswapV2Router02(router != address(0) ? router : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // For testing uniswapFactory = IUniswapV2Factory(factory != address(0) ? factory : 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); // For testing require(tokenUniswapPair == address(0), "Token: pool already created"); tokenUniswapPair = uniswapFactory.createPair( address(uniswapRouterV2.WETH()), address(this) ); return tokenUniswapPair; } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function setBurnrate(uint8 burnrate_) public onlyOwner { _setupBurnrate(burnrate_); } function setBurnEnable(bool burnEnabled_) public onlyOwner { _setBurnEnable(burnEnabled_); } function setYvaultMaster(address _yvaultMaster) public onlyOwner { _setYvaultMaster(_yvaultMaster); } /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "YVAULT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "YVAULT::delegateBySig: invalid nonce"); require(now <= expiry, "YVAULT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "YVAULT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying YVAULTs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "YVAULT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
34,503