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
124
// Deposits of a user
struct UserDeposits { // Set of (unique) deposit IDs uint256[] ids; // Mapping from deposit ID to deposit data mapping(uint256 => Deposit) data; }
struct UserDeposits { // Set of (unique) deposit IDs uint256[] ids; // Mapping from deposit ID to deposit data mapping(uint256 => Deposit) data; }
13,735
30
// ico2
uint public ico2StartTime = 1536855600; uint256 public ico2PerEth = 1100000000000000;
uint public ico2StartTime = 1536855600; uint256 public ico2PerEth = 1100000000000000;
2,323
0
// Event is called whenever a winner is called /
event SetWinner(string positionName, string winnerLastName);
event SetWinner(string positionName, string winnerLastName);
24,121
30
// withdrawing the not ensured balance - only admin
function withdrawNotEnsuredBalance() public { require(admins[msg.sender] == true, 'you are not allowed'); payable(msg.sender).transfer(address(this).balance - ensuredBalance); }
function withdrawNotEnsuredBalance() public { require(admins[msg.sender] == true, 'you are not allowed'); payable(msg.sender).transfer(address(this).balance - ensuredBalance); }
40,967
1
// : staticData struct fields don't change after initialization
staticData.factory = _factory; staticData.fundingPool = _fundingPool; staticData.collToken = _collToken; staticData.arranger = _arranger; if (_whitelistAuthority != address(0)) { staticData.whitelistAuthority = _whitelistAuthority; }
staticData.factory = _factory; staticData.fundingPool = _fundingPool; staticData.collToken = _collToken; staticData.arranger = _arranger; if (_whitelistAuthority != address(0)) { staticData.whitelistAuthority = _whitelistAuthority; }
38,428
171
// pragma solidity ^0.5.12; // import "./lpTokenWrapper.sol"; // import "./rewardsDecayHolder.sol"; // import "./lib.sol"; // import "./ReentrancyGuard.sol"; // class for handling distributions FL tokens as reward for providing liquidity for FL & USDFL tokens/
contract StakingRewardsDecay is LPTokenWrapper, Auth, ReentrancyGuard { address public gov; address public aggregator; uint256 public totalRewards = 0; struct EpochData { mapping(address => uint256) userRewardPerTokenPaid; mapping(address => uint256) rewards; uint256 initreward; uint256 duration; uint256 starttime; uint256 periodFinish; uint256 rewardRate; uint256 lastUpdateTime; uint256 rewardPerTokenStored; uint256 lastTotalSupply; bool closed; } uint256 public EPOCHCOUNT = 0; uint256 public epochInited = 0; EpochData[] public epochs; mapping(bytes32 => address) public pairNameToGem; mapping(address => uint256) public lastClaimedEpoch; mapping(address => uint256) public yetNotClaimedOldEpochRewards; uint256 public currentEpoch; StakingRewardsDecayHolder public holder; event RewardAdded(uint256 reward, uint256 epoch, uint256 duration, uint256 starttime); event StopRewarding(); event Staked(address indexed user, address indexed gem, uint256 amount); event Withdrawn(address indexed user, address indexed gem, uint256 amount); event RewardTakeStock(address indexed user, uint256 reward, uint256 epoch); event RewardPaid(address indexed user, uint256 reward); constructor() public { deployer = msg.sender; } /** * @dev initialization can be called only once * _gov - FL token contract * epochCount - how many epochs we will use */ function initialize(address _gov, uint256 epochCount) public initializer { // only deployer can initialize require(deployer == msg.sender); gov = _gov; require(gov != address(0)); require(epochCount > 0); EPOCHCOUNT = epochCount; EpochData memory data; for (uint256 i = 0; i < epochCount; i++) { epochs.push(data); } holder = new StakingRewardsDecayHolder(address(this)); } /** * @dev setup aggregator contract (RewardDecayAggregator) which allow to claim FL * tokens from hirisk & lowrisk contracts in one tx */ function setupAggregator(address _aggregator) public { require(deployer == msg.sender); require(_aggregator != address(0)); require(aggregator == address(0)); //only one set allowed aggregator = _aggregator; } /** * @dev returns time when rewarding will start */ function getStartTime() public view returns (uint256) { return epochs[0].starttime; } /** * @dev check is time allow to start rewarding */ modifier checkStart() { require(block.timestamp >= getStartTime(), "not start"); require(epochInited == EPOCHCOUNT, "not all epochs was inited"); _; } /** * @dev init specific rewarding epoch * reward - how many Fl tokens we have to distribute in this epoch * starttime - time to start rewarding * duration - duration of each epoch * idx - id of epoch */ function initRewardAmount( uint256 reward, uint256 starttime, uint256 duration, uint256 idx ) public { // only deployer can require(deployer == msg.sender); require(epochInited == 0, "not allowed after approve"); initEpoch(reward, starttime, duration, idx); } /** * @dev setup checker contract which will be used to check * that LP pair used for FL rewarding contains only approved stables */ function setupGemForRewardChecker(address a) public { require(deployer == msg.sender); gemForRewardChecker = IGemForRewardChecker(a); } /** * @dev core func to init specific rewarding epoch * reward - how many Fl tokens we have to distribute in this epoch * starttime - time to start rewarding * duration - duration of each epoch * idx - id of epoch */ function initEpoch( uint256 reward, uint256 starttime, uint256 duration, uint256 idx ) internal { require(idx < EPOCHCOUNT, "idx < EPOCHCOUNT"); require(duration > 0, "duration > 0"); require(starttime >= block.timestamp, "starttime > block.timestamp"); EpochData storage epoch = epochs[idx]; epoch.rewardPerTokenStored = 0; epoch.starttime = starttime; epoch.duration = duration; epoch.rewardRate = reward.div(duration); require(epoch.rewardRate > 0, "zero rewardRate"); epoch.initreward = reward; epoch.lastUpdateTime = starttime; epoch.periodFinish = starttime.add(duration); emit RewardAdded(reward, idx, duration, starttime); } /** * @dev init all reward epochs in one call * rewards - array of reward to distribute (one digit for one epoch) * starttime - time to start rewarding * duration - duration of each epoch */ function initAllEpochs( uint256[] memory rewards, uint256 starttime, uint256 duration ) public { // only deployer can require(deployer == msg.sender); require(epochInited == 0, "not allowed after approve"); require(duration > 0); require(starttime > 0); assert(rewards.length == EPOCHCOUNT); uint256 time = starttime; for (uint256 i = 0; i < EPOCHCOUNT; i++) { initEpoch(rewards[i], time, duration, i); time = time.add(duration); } } /** * @dev returns reward rate for specific epoch */ function getEpochRewardRate(uint256 epochIdx) public view returns (uint256) { return epochs[epochIdx].rewardRate; } /** * @dev returns epoch start time for specific epoch */ function getEpochStartTime(uint256 epochIdx) public view returns (uint256) { return epochs[epochIdx].starttime; } /** * @dev returns epoch finish time for specific epoch */ function getEpochFinishTime(uint256 epochIdx) public view returns (uint256) { return epochs[epochIdx].periodFinish; } /** * @dev calculate total reward to distribute for all epochs */ function getTotalRewards() public view returns (uint256 result) { require(epochInited == EPOCHCOUNT, "not inited"); result = 0; for (uint256 i = 0; i < EPOCHCOUNT; i++) { result = result.add(epochs[i].initreward); } } /** * @dev calculate total time to reward for all epochs */ function getTotalRewardTime() public view returns (uint256 result) { require(epochInited == EPOCHCOUNT, "not inited"); result = 0; for (uint256 i = 0; i < EPOCHCOUNT; i++) { result = result.add(epochs[i].duration); } } /** * @dev we need to call this func after all epochs will finnally configured * only one call allowed */ function approveEpochsConsistency() public { require(deployer == msg.sender); require(epochInited == 0, "double call not allowed"); uint256 totalReward = epochs[0].initreward; require(getStartTime() > 0); for (uint256 i = 1; i < EPOCHCOUNT; i++) { EpochData storage epoch = epochs[i]; require(epoch.starttime > 0); require(epoch.starttime == epochs[i - 1].periodFinish); totalReward = totalReward.add(epoch.initreward); } require(IERC20(gov).balanceOf(address(this)) >= totalReward, "GOV balance not enought"); epochInited = EPOCHCOUNT; } /** * @dev set deployer prop to NULL to prevent further calling registerPairDesc by deployer(admin) * and prevent some other initialisation calls * needed for fair decentralization */ function resetDeployer() public { // only deployer can do it require(deployer == msg.sender); require(epochInited == EPOCHCOUNT); deployer = address(0); } /** * @dev calculate and return current epoch index */ function calcCurrentEpoch() public view returns (uint256 res) { res = 0; for ( uint256 i = currentEpoch; i < EPOCHCOUNT && epochs[i].starttime <= block.timestamp; i++ ) { res = i; } } /** * @dev calculate current epoch index and store it inside contract storage */ modifier updateCurrentEpoch() { currentEpoch = calcCurrentEpoch(); uint256 supply = totalSupply(); epochs[currentEpoch].lastTotalSupply = supply; for (int256 i = int256(currentEpoch) - 1; i >= 0; i--) { EpochData storage epoch = epochs[uint256(i)]; if (epoch.closed) { break; } epoch.lastTotalSupply = supply; epoch.closed = true; } _; } /** * @dev register LP pair which have to be rewarded when it will be locked * gem - address of LP token contract * adapter - address of adapter contract of LP token contract needed to * calculate USD value of specific amount of LP tokens * factor - multiplicator (actually eq 1) * name - name of LP pair to indentificate in GUI. have to be unique */ function registerPairDesc( address gem, address adapter, uint256 factor, bytes32 name ) public auth nonReentrant { require(gem != address(0x0), "gem is null"); require(adapter != address(0x0), "adapter is null"); require(checkGem(gem), "bad gem"); require(pairNameToGem[name] == address(0) || pairNameToGem[name] == gem, "duplicate name"); if (pairDescs[gem].name != "") { delete pairNameToGem[pairDescs[gem].name]; } registerGem(gem); pairDescs[gem] = PairDesc({ gem: gem, adapter: adapter, factor: factor, staker: address(0), name: name }); pairNameToGem[name] = gem; } /** * @dev returns LP pair statistic for specific user account * return values: * gem - address of LP token * avail - amount of tokens on user wallet * locked - amount of tokens locked for rewarding by user * lockedValue - USD value of tokens locked for rewarding by user * availValue - USD value of tokens on user wallet */ function getPairInfo(bytes32 name, address account) public view returns ( address gem, uint256 avail, uint256 locked, uint256 lockedValue, uint256 availValue ) { gem = pairNameToGem[name]; if (gem == address(0)) { return (address(0), 0, 0, 0, 0); } PairDesc storage desc = pairDescs[gem]; locked = holder.amounts(gem, account); lockedValue = IAdapter(desc.adapter).calc(gem, locked, desc.factor); avail = IERC20(gem).balanceOf(account); availValue = IAdapter(desc.adapter).calc(gem, avail, desc.factor); } /** * @dev returns USD value of 1 LP token with specific name */ function getPrice(bytes32 name) public view returns (uint256) { address gem = pairNameToGem[name]; if (gem == address(0)) { return 0; } PairDesc storage desc = pairDescs[gem]; return IAdapter(desc.adapter).calc(gem, 1, desc.factor); } /** * @dev returns current rewarding speed. How many tokens distributed in one hour * at current epoch */ function getRewardPerHour() public view returns (uint256) { EpochData storage epoch = epochs[calcCurrentEpoch()]; return epoch.rewardRate * 3600; } /** * @dev returns current time with cutting by rewarding finish time * value calculated for specific epoch */ function lastTimeRewardApplicable(EpochData storage epoch) internal view returns (uint256) { assert(block.timestamp >= epoch.starttime); return Math.min(block.timestamp, epoch.periodFinish); } /** * @dev returns current rewarding speed per one USD value of LP pair * value calculated for specific epoch * lastTotalSupply corresponded for current epoch have to be provided */ function rewardPerToken(EpochData storage epoch, uint256 lastTotalSupply) internal view returns (uint256) { if (lastTotalSupply == 0) { return epoch.rewardPerTokenStored; } return epoch.rewardPerTokenStored.add( lastTimeRewardApplicable(epoch) .sub(epoch.lastUpdateTime) .mul(epoch.rewardRate) .mul(1e18 * (10**decimals)) .div(lastTotalSupply) ); } /** * @dev returns how many FL tokens specific user already earned for specific epoch * lastTotalSupply corresponded for current epoch have to be provided */ function earnedEpoch( address account, EpochData storage epoch, uint256 lastTotalSupply ) internal view returns (uint256) { return balanceOf(account) .mul( rewardPerToken(epoch, lastTotalSupply).sub(epoch.userRewardPerTokenPaid[account]) ) .div(1e18 * (10**decimals)) .add(epoch.rewards[account]); } /** * @dev returns how many FL tokens of specific user already earned remains unclaimed */ function earned(address account) public view returns (uint256 acc) { uint256 currentSupply = totalSupply(); int256 lastClaimedEpochIdx = int256(lastClaimedEpoch[account]); for (int256 i = int256(calcCurrentEpoch()); i >= lastClaimedEpochIdx; i--) { EpochData storage epoch = epochs[uint256(i)]; uint256 epochTotalSupply = currentSupply; if (epoch.closed) { epochTotalSupply = epoch.lastTotalSupply; } acc = acc.add(earnedEpoch(account, epoch, epochTotalSupply)); } acc = acc.add(yetNotClaimedOldEpochRewards[account]); } /** * @dev returns how many FL tokens specific user already earned for specified epoch * also it clear reward cache */ function getRewardEpoch(address account, EpochData storage epoch) internal returns (uint256) { uint256 reward = earnedEpoch(account, epoch, epoch.lastTotalSupply); if (reward > 0) { epoch.rewards[account] = 0; return reward; } return 0; } /** * @dev returns how many FL tokens specific user already earned from moment of last claiming epoch * also this func update last claiming epoch */ function takeStockReward(address account) internal returns (uint256 acc) { for (uint256 i = lastClaimedEpoch[account]; i <= currentEpoch; i++) { uint256 reward = getRewardEpoch(account, epochs[i]); acc = acc.add(reward); emit RewardTakeStock(account, reward, i); } lastClaimedEpoch[account] = currentEpoch; } /** * @dev recalculate and update yetNotClaimedOldEpochRewards cache */ function gatherOldEpochReward(address account) internal { if (currentEpoch == 0) { return; } uint256 acc = takeStockReward(account); yetNotClaimedOldEpochRewards[account] = yetNotClaimedOldEpochRewards[account].add(acc); } /** * @dev called when we lock LP tokens for specific epoch (we expect current epoch here) */ function stakeEpoch( uint256 amount, address gem, address usr, EpochData storage epoch ) internal updateReward(usr, epoch) { gatherOldEpochReward(usr); stakeLp(amount, gem, usr); emit Staked(usr, gem, amount); } /** * @dev called by LP token holder contract when we lock LP tokens * only LP token holder contract allow to call this func */ function stake( address account, uint256 amount, address gem ) public nonReentrant checkStart updateCurrentEpoch { require(address(holder) == msg.sender); assert(amount > 0); stakeEpoch(amount, gem, account, epochs[currentEpoch]); } /** * @dev called when we unlock LP tokens for specific epoch (we expect current epoch here) */ function withdrawEpoch( uint256 amount, address gem, address usr, EpochData storage epoch ) internal updateReward(usr, epoch) { gatherOldEpochReward(usr); withdrawLp(amount, gem, usr); emit Withdrawn(usr, gem, amount); } /** * @dev called by LP token holder contract when we unlock LP tokens * only LP token holder contract allow to call this func */ function withdraw( address account, uint256 amount, address gem ) public nonReentrant checkStart updateCurrentEpoch { require(address(holder) == msg.sender); assert(amount > 0); withdrawEpoch(amount, gem, account, epochs[currentEpoch]); } /** * @dev core func to actual transferting rewarded FL tokens to user wallet */ function getRewardCore(address account) internal checkStart updateCurrentEpoch updateReward(account, epochs[currentEpoch]) returns (uint256 acc) { acc = takeStockReward(account); acc = acc.add(yetNotClaimedOldEpochRewards[account]); yetNotClaimedOldEpochRewards[account] = 0; if (acc > 0) { totalRewards = totalRewards.add(acc); IERC20(gov).safeTransfer(account, acc); emit RewardPaid(account, acc); } } /** * @dev func to actual transferting rewarded FL tokens to user wallet */ function getReward() public nonReentrant returns (uint256) { return getRewardCore(msg.sender); } /** * @dev func to actual transferting rewarded FL tokens to user wallet * we call this func from aggregator contract (RewardDecayAggregator) to allow to claim FL * tokens from hirisk & lowrisk contracts in one tx */ function getRewardEx(address account) public nonReentrant returns (uint256) { require(aggregator == msg.sender); return getRewardCore(account); } /** * @dev update some internal rewarding props */ modifier updateReward(address account, EpochData storage epoch) { assert(account != address(0)); epoch.rewardPerTokenStored = rewardPerToken(epoch, epoch.lastTotalSupply); epoch.lastUpdateTime = lastTimeRewardApplicable(epoch); epoch.rewards[account] = earnedEpoch(account, epoch, epoch.lastTotalSupply); epoch.userRewardPerTokenPaid[account] = epoch.rewardPerTokenStored; _; } }
contract StakingRewardsDecay is LPTokenWrapper, Auth, ReentrancyGuard { address public gov; address public aggregator; uint256 public totalRewards = 0; struct EpochData { mapping(address => uint256) userRewardPerTokenPaid; mapping(address => uint256) rewards; uint256 initreward; uint256 duration; uint256 starttime; uint256 periodFinish; uint256 rewardRate; uint256 lastUpdateTime; uint256 rewardPerTokenStored; uint256 lastTotalSupply; bool closed; } uint256 public EPOCHCOUNT = 0; uint256 public epochInited = 0; EpochData[] public epochs; mapping(bytes32 => address) public pairNameToGem; mapping(address => uint256) public lastClaimedEpoch; mapping(address => uint256) public yetNotClaimedOldEpochRewards; uint256 public currentEpoch; StakingRewardsDecayHolder public holder; event RewardAdded(uint256 reward, uint256 epoch, uint256 duration, uint256 starttime); event StopRewarding(); event Staked(address indexed user, address indexed gem, uint256 amount); event Withdrawn(address indexed user, address indexed gem, uint256 amount); event RewardTakeStock(address indexed user, uint256 reward, uint256 epoch); event RewardPaid(address indexed user, uint256 reward); constructor() public { deployer = msg.sender; } /** * @dev initialization can be called only once * _gov - FL token contract * epochCount - how many epochs we will use */ function initialize(address _gov, uint256 epochCount) public initializer { // only deployer can initialize require(deployer == msg.sender); gov = _gov; require(gov != address(0)); require(epochCount > 0); EPOCHCOUNT = epochCount; EpochData memory data; for (uint256 i = 0; i < epochCount; i++) { epochs.push(data); } holder = new StakingRewardsDecayHolder(address(this)); } /** * @dev setup aggregator contract (RewardDecayAggregator) which allow to claim FL * tokens from hirisk & lowrisk contracts in one tx */ function setupAggregator(address _aggregator) public { require(deployer == msg.sender); require(_aggregator != address(0)); require(aggregator == address(0)); //only one set allowed aggregator = _aggregator; } /** * @dev returns time when rewarding will start */ function getStartTime() public view returns (uint256) { return epochs[0].starttime; } /** * @dev check is time allow to start rewarding */ modifier checkStart() { require(block.timestamp >= getStartTime(), "not start"); require(epochInited == EPOCHCOUNT, "not all epochs was inited"); _; } /** * @dev init specific rewarding epoch * reward - how many Fl tokens we have to distribute in this epoch * starttime - time to start rewarding * duration - duration of each epoch * idx - id of epoch */ function initRewardAmount( uint256 reward, uint256 starttime, uint256 duration, uint256 idx ) public { // only deployer can require(deployer == msg.sender); require(epochInited == 0, "not allowed after approve"); initEpoch(reward, starttime, duration, idx); } /** * @dev setup checker contract which will be used to check * that LP pair used for FL rewarding contains only approved stables */ function setupGemForRewardChecker(address a) public { require(deployer == msg.sender); gemForRewardChecker = IGemForRewardChecker(a); } /** * @dev core func to init specific rewarding epoch * reward - how many Fl tokens we have to distribute in this epoch * starttime - time to start rewarding * duration - duration of each epoch * idx - id of epoch */ function initEpoch( uint256 reward, uint256 starttime, uint256 duration, uint256 idx ) internal { require(idx < EPOCHCOUNT, "idx < EPOCHCOUNT"); require(duration > 0, "duration > 0"); require(starttime >= block.timestamp, "starttime > block.timestamp"); EpochData storage epoch = epochs[idx]; epoch.rewardPerTokenStored = 0; epoch.starttime = starttime; epoch.duration = duration; epoch.rewardRate = reward.div(duration); require(epoch.rewardRate > 0, "zero rewardRate"); epoch.initreward = reward; epoch.lastUpdateTime = starttime; epoch.periodFinish = starttime.add(duration); emit RewardAdded(reward, idx, duration, starttime); } /** * @dev init all reward epochs in one call * rewards - array of reward to distribute (one digit for one epoch) * starttime - time to start rewarding * duration - duration of each epoch */ function initAllEpochs( uint256[] memory rewards, uint256 starttime, uint256 duration ) public { // only deployer can require(deployer == msg.sender); require(epochInited == 0, "not allowed after approve"); require(duration > 0); require(starttime > 0); assert(rewards.length == EPOCHCOUNT); uint256 time = starttime; for (uint256 i = 0; i < EPOCHCOUNT; i++) { initEpoch(rewards[i], time, duration, i); time = time.add(duration); } } /** * @dev returns reward rate for specific epoch */ function getEpochRewardRate(uint256 epochIdx) public view returns (uint256) { return epochs[epochIdx].rewardRate; } /** * @dev returns epoch start time for specific epoch */ function getEpochStartTime(uint256 epochIdx) public view returns (uint256) { return epochs[epochIdx].starttime; } /** * @dev returns epoch finish time for specific epoch */ function getEpochFinishTime(uint256 epochIdx) public view returns (uint256) { return epochs[epochIdx].periodFinish; } /** * @dev calculate total reward to distribute for all epochs */ function getTotalRewards() public view returns (uint256 result) { require(epochInited == EPOCHCOUNT, "not inited"); result = 0; for (uint256 i = 0; i < EPOCHCOUNT; i++) { result = result.add(epochs[i].initreward); } } /** * @dev calculate total time to reward for all epochs */ function getTotalRewardTime() public view returns (uint256 result) { require(epochInited == EPOCHCOUNT, "not inited"); result = 0; for (uint256 i = 0; i < EPOCHCOUNT; i++) { result = result.add(epochs[i].duration); } } /** * @dev we need to call this func after all epochs will finnally configured * only one call allowed */ function approveEpochsConsistency() public { require(deployer == msg.sender); require(epochInited == 0, "double call not allowed"); uint256 totalReward = epochs[0].initreward; require(getStartTime() > 0); for (uint256 i = 1; i < EPOCHCOUNT; i++) { EpochData storage epoch = epochs[i]; require(epoch.starttime > 0); require(epoch.starttime == epochs[i - 1].periodFinish); totalReward = totalReward.add(epoch.initreward); } require(IERC20(gov).balanceOf(address(this)) >= totalReward, "GOV balance not enought"); epochInited = EPOCHCOUNT; } /** * @dev set deployer prop to NULL to prevent further calling registerPairDesc by deployer(admin) * and prevent some other initialisation calls * needed for fair decentralization */ function resetDeployer() public { // only deployer can do it require(deployer == msg.sender); require(epochInited == EPOCHCOUNT); deployer = address(0); } /** * @dev calculate and return current epoch index */ function calcCurrentEpoch() public view returns (uint256 res) { res = 0; for ( uint256 i = currentEpoch; i < EPOCHCOUNT && epochs[i].starttime <= block.timestamp; i++ ) { res = i; } } /** * @dev calculate current epoch index and store it inside contract storage */ modifier updateCurrentEpoch() { currentEpoch = calcCurrentEpoch(); uint256 supply = totalSupply(); epochs[currentEpoch].lastTotalSupply = supply; for (int256 i = int256(currentEpoch) - 1; i >= 0; i--) { EpochData storage epoch = epochs[uint256(i)]; if (epoch.closed) { break; } epoch.lastTotalSupply = supply; epoch.closed = true; } _; } /** * @dev register LP pair which have to be rewarded when it will be locked * gem - address of LP token contract * adapter - address of adapter contract of LP token contract needed to * calculate USD value of specific amount of LP tokens * factor - multiplicator (actually eq 1) * name - name of LP pair to indentificate in GUI. have to be unique */ function registerPairDesc( address gem, address adapter, uint256 factor, bytes32 name ) public auth nonReentrant { require(gem != address(0x0), "gem is null"); require(adapter != address(0x0), "adapter is null"); require(checkGem(gem), "bad gem"); require(pairNameToGem[name] == address(0) || pairNameToGem[name] == gem, "duplicate name"); if (pairDescs[gem].name != "") { delete pairNameToGem[pairDescs[gem].name]; } registerGem(gem); pairDescs[gem] = PairDesc({ gem: gem, adapter: adapter, factor: factor, staker: address(0), name: name }); pairNameToGem[name] = gem; } /** * @dev returns LP pair statistic for specific user account * return values: * gem - address of LP token * avail - amount of tokens on user wallet * locked - amount of tokens locked for rewarding by user * lockedValue - USD value of tokens locked for rewarding by user * availValue - USD value of tokens on user wallet */ function getPairInfo(bytes32 name, address account) public view returns ( address gem, uint256 avail, uint256 locked, uint256 lockedValue, uint256 availValue ) { gem = pairNameToGem[name]; if (gem == address(0)) { return (address(0), 0, 0, 0, 0); } PairDesc storage desc = pairDescs[gem]; locked = holder.amounts(gem, account); lockedValue = IAdapter(desc.adapter).calc(gem, locked, desc.factor); avail = IERC20(gem).balanceOf(account); availValue = IAdapter(desc.adapter).calc(gem, avail, desc.factor); } /** * @dev returns USD value of 1 LP token with specific name */ function getPrice(bytes32 name) public view returns (uint256) { address gem = pairNameToGem[name]; if (gem == address(0)) { return 0; } PairDesc storage desc = pairDescs[gem]; return IAdapter(desc.adapter).calc(gem, 1, desc.factor); } /** * @dev returns current rewarding speed. How many tokens distributed in one hour * at current epoch */ function getRewardPerHour() public view returns (uint256) { EpochData storage epoch = epochs[calcCurrentEpoch()]; return epoch.rewardRate * 3600; } /** * @dev returns current time with cutting by rewarding finish time * value calculated for specific epoch */ function lastTimeRewardApplicable(EpochData storage epoch) internal view returns (uint256) { assert(block.timestamp >= epoch.starttime); return Math.min(block.timestamp, epoch.periodFinish); } /** * @dev returns current rewarding speed per one USD value of LP pair * value calculated for specific epoch * lastTotalSupply corresponded for current epoch have to be provided */ function rewardPerToken(EpochData storage epoch, uint256 lastTotalSupply) internal view returns (uint256) { if (lastTotalSupply == 0) { return epoch.rewardPerTokenStored; } return epoch.rewardPerTokenStored.add( lastTimeRewardApplicable(epoch) .sub(epoch.lastUpdateTime) .mul(epoch.rewardRate) .mul(1e18 * (10**decimals)) .div(lastTotalSupply) ); } /** * @dev returns how many FL tokens specific user already earned for specific epoch * lastTotalSupply corresponded for current epoch have to be provided */ function earnedEpoch( address account, EpochData storage epoch, uint256 lastTotalSupply ) internal view returns (uint256) { return balanceOf(account) .mul( rewardPerToken(epoch, lastTotalSupply).sub(epoch.userRewardPerTokenPaid[account]) ) .div(1e18 * (10**decimals)) .add(epoch.rewards[account]); } /** * @dev returns how many FL tokens of specific user already earned remains unclaimed */ function earned(address account) public view returns (uint256 acc) { uint256 currentSupply = totalSupply(); int256 lastClaimedEpochIdx = int256(lastClaimedEpoch[account]); for (int256 i = int256(calcCurrentEpoch()); i >= lastClaimedEpochIdx; i--) { EpochData storage epoch = epochs[uint256(i)]; uint256 epochTotalSupply = currentSupply; if (epoch.closed) { epochTotalSupply = epoch.lastTotalSupply; } acc = acc.add(earnedEpoch(account, epoch, epochTotalSupply)); } acc = acc.add(yetNotClaimedOldEpochRewards[account]); } /** * @dev returns how many FL tokens specific user already earned for specified epoch * also it clear reward cache */ function getRewardEpoch(address account, EpochData storage epoch) internal returns (uint256) { uint256 reward = earnedEpoch(account, epoch, epoch.lastTotalSupply); if (reward > 0) { epoch.rewards[account] = 0; return reward; } return 0; } /** * @dev returns how many FL tokens specific user already earned from moment of last claiming epoch * also this func update last claiming epoch */ function takeStockReward(address account) internal returns (uint256 acc) { for (uint256 i = lastClaimedEpoch[account]; i <= currentEpoch; i++) { uint256 reward = getRewardEpoch(account, epochs[i]); acc = acc.add(reward); emit RewardTakeStock(account, reward, i); } lastClaimedEpoch[account] = currentEpoch; } /** * @dev recalculate and update yetNotClaimedOldEpochRewards cache */ function gatherOldEpochReward(address account) internal { if (currentEpoch == 0) { return; } uint256 acc = takeStockReward(account); yetNotClaimedOldEpochRewards[account] = yetNotClaimedOldEpochRewards[account].add(acc); } /** * @dev called when we lock LP tokens for specific epoch (we expect current epoch here) */ function stakeEpoch( uint256 amount, address gem, address usr, EpochData storage epoch ) internal updateReward(usr, epoch) { gatherOldEpochReward(usr); stakeLp(amount, gem, usr); emit Staked(usr, gem, amount); } /** * @dev called by LP token holder contract when we lock LP tokens * only LP token holder contract allow to call this func */ function stake( address account, uint256 amount, address gem ) public nonReentrant checkStart updateCurrentEpoch { require(address(holder) == msg.sender); assert(amount > 0); stakeEpoch(amount, gem, account, epochs[currentEpoch]); } /** * @dev called when we unlock LP tokens for specific epoch (we expect current epoch here) */ function withdrawEpoch( uint256 amount, address gem, address usr, EpochData storage epoch ) internal updateReward(usr, epoch) { gatherOldEpochReward(usr); withdrawLp(amount, gem, usr); emit Withdrawn(usr, gem, amount); } /** * @dev called by LP token holder contract when we unlock LP tokens * only LP token holder contract allow to call this func */ function withdraw( address account, uint256 amount, address gem ) public nonReentrant checkStart updateCurrentEpoch { require(address(holder) == msg.sender); assert(amount > 0); withdrawEpoch(amount, gem, account, epochs[currentEpoch]); } /** * @dev core func to actual transferting rewarded FL tokens to user wallet */ function getRewardCore(address account) internal checkStart updateCurrentEpoch updateReward(account, epochs[currentEpoch]) returns (uint256 acc) { acc = takeStockReward(account); acc = acc.add(yetNotClaimedOldEpochRewards[account]); yetNotClaimedOldEpochRewards[account] = 0; if (acc > 0) { totalRewards = totalRewards.add(acc); IERC20(gov).safeTransfer(account, acc); emit RewardPaid(account, acc); } } /** * @dev func to actual transferting rewarded FL tokens to user wallet */ function getReward() public nonReentrant returns (uint256) { return getRewardCore(msg.sender); } /** * @dev func to actual transferting rewarded FL tokens to user wallet * we call this func from aggregator contract (RewardDecayAggregator) to allow to claim FL * tokens from hirisk & lowrisk contracts in one tx */ function getRewardEx(address account) public nonReentrant returns (uint256) { require(aggregator == msg.sender); return getRewardCore(account); } /** * @dev update some internal rewarding props */ modifier updateReward(address account, EpochData storage epoch) { assert(account != address(0)); epoch.rewardPerTokenStored = rewardPerToken(epoch, epoch.lastTotalSupply); epoch.lastUpdateTime = lastTimeRewardApplicable(epoch); epoch.rewards[account] = earnedEpoch(account, epoch, epoch.lastTotalSupply); epoch.userRewardPerTokenPaid[account] = epoch.rewardPerTokenStored; _; } }
37,934
197
// these are our standard approvals. want = Curve LP token
want.approve(address(proxy), type(uint256).max); crv.approve(sushiswap, type(uint256).max);
want.approve(address(proxy), type(uint256).max); crv.approve(sushiswap, type(uint256).max);
29,971
58
// The operator can call this method once they receive the event "RandomNumberCreated" triggered by the VRF v2 consumer contract (RandomNumber.sol)/_raffleId Id of the raffle/_normalizedRandomNumber index of the array that contains the winner of the raffle. Generated by chainlink/it is the method that sets the winner and transfers funds/called by Chainlink callback
function transferFunds(uint256 _raffleId, uint256 _normalizedRandomNumber) internal nonReentrant
function transferFunds(uint256 _raffleId, uint256 _normalizedRandomNumber) internal nonReentrant
7,401
1
// Swap fees can be set to a fixed value at construction, or delegated to the ProtocolFeePercentagesProvider if passing the special sentinel value.
uint256 public constant DELEGATE_PROTOCOL_SWAP_FEES_SENTINEL = type(uint256).max; bool private immutable _delegatedProtocolSwapFees;
uint256 public constant DELEGATE_PROTOCOL_SWAP_FEES_SENTINEL = type(uint256).max; bool private immutable _delegatedProtocolSwapFees;
21,449
10
// Safely get the address from the resolver
bytes32 result = 0; assembly { let status := staticcall(gasLimit, resolver, add(bytecode, 32), mload(bytecode), 0, 32)
bytes32 result = 0; assembly { let status := staticcall(gasLimit, resolver, add(bytecode, 32), mload(bytecode), 0, 32)
29,360
25
// Admin functions for adding and removing tokens from the wrapped token system
function addToken(address token) public onlyOwner { supportedTokens[token] = true; }
function addToken(address token) public onlyOwner { supportedTokens[token] = true; }
9,425
309
// Returns the downcasted int96 from int256, reverting onoverflow (when the input is less than smallest int96 orgreater than largest int96). Counterpart to Solidity's `int96` operator. Requirements: - input must fit into 96 bits _Available since v4.7._ /
function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); require(downcasted == value, "SafeCast: value doesn't fit in 96 bits"); }
function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); require(downcasted == value, "SafeCast: value doesn't fit in 96 bits"); }
14,568
77
// Standard ERC20 transferFrom function
* @param _from {address} * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; return doTransfer(_from, _to, _amount); }
* @param _from {address} * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; return doTransfer(_from, _to, _amount); }
15,386
6
// Returns the links of a node as and array
function getNode(CLL storage self, uint n) internal view returns (uint[2])
function getNode(CLL storage self, uint n) internal view returns (uint[2])
30,215
103
// Calls `IERC20Token(token).approve()`./Reverts if `false` is returned or if the return/data length is nonzero and not 32 bytes./token The address of the token contract./spender The address that receives an allowance./allowance The allowance to set.
function approve( address token, address spender, uint256 allowance ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).approve.selector, spender,
function approve( address token, address spender, uint256 allowance ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).approve.selector, spender,
16,454
13
// transfers utility tokens for user rewards
function transferTokensToTimelocker() external onlyRole(ADMIN_ROLE) { uint256 baseReward = token.getBaseReward(); token.transfer(address(timelocker), baseReward); }
function transferTokensToTimelocker() external onlyRole(ADMIN_ROLE) { uint256 baseReward = token.getBaseReward(); token.transfer(address(timelocker), baseReward); }
31,183
27
// swap and repay borrow for sender
function swapAndRepay(ISmartWalletImplementation.SwapAndRepayParams calldata params) external payable override nonReentrant returns (uint256 destAmount) { require(params.tradePath.length >= 1, "invalid tradePath"); require(supportedLendings.contains(params.lendingContract), "unsupported lending");
function swapAndRepay(ISmartWalletImplementation.SwapAndRepayParams calldata params) external payable override nonReentrant returns (uint256 destAmount) { require(params.tradePath.length >= 1, "invalid tradePath"); require(supportedLendings.contains(params.lendingContract), "unsupported lending");
78,164
42
// emission
totalSupply += _value; balances[owner] += _value; return true;
totalSupply += _value; balances[owner] += _value; return true;
32,993
9
// Returns true if the address is pausable admin and false if not
function isPausableAdmin(address addr) external view returns (bool) { return pausableAdminSet[addr]; // T:[ACL-2,3] }
function isPausableAdmin(address addr) external view returns (bool) { return pausableAdminSet[addr]; // T:[ACL-2,3] }
6,870
9
// Returns data about a specific observation index/index The element of the observations array to fetch/You most likely want to use observe() instead of this method to get an observation as of some amount of time/ ago, rather than at a specific index in the array./ return blockTimestamp The timestamp of the observation,/ return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,/ return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,/ return initialized whether the observation has been initialized and the
function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized );
function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized );
4,312
18
// setter for global pause state _paused) true to pause all auctions, false to unpause all auctions /
function setGlobalPaused(bool _paused) external onlyAdmin { globalPaused = _paused; }
function setGlobalPaused(bool _paused) external onlyAdmin { globalPaused = _paused; }
6,635
47
// See {BEP20-balanceOf}. /
function balanceOf(address account) external view returns (uint256) { return _balances[account]; }
function balanceOf(address account) external view returns (uint256) { return _balances[account]; }
24,589
0
// With hardhat-deploy proxies the ownerAddress is zero only for the implementation contract if the implementation contract want to be used as standalone it simply has to execute the `proxied` function This ensure the ownerAddress is never zero post deployment
if (ownerAddress == address(0)) {
if (ownerAddress == address(0)) {
17,466
3
// place eip-1167 runtime code in memory.
bytes memory runtimeCode = abi.encodePacked( bytes10(0x363d3d373d3d3d363d73), logicContract, bytes15(0x5af43d82803e903d91602b57fd5bf3) );
bytes memory runtimeCode = abi.encodePacked( bytes10(0x363d3d373d3d3d363d73), logicContract, bytes15(0x5af43d82803e903d91602b57fd5bf3) );
24,683
158
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
uint64 numberMinted;
1,275
77
// Called from pool's hourly strategy
function deploy_capital(uint256 amount) external override { require(msg.sender == address(saffron_pool), "must be pool"); DAI.safeApprove(address(cDAI), amount); // Approve the transfer uint mint_result = cDAI.mint(amount); // Mint the cTokens and assert there is no error // Check for success, RETURN: 0 on success, otherwise an Error code assert(mint_result==0); }
function deploy_capital(uint256 amount) external override { require(msg.sender == address(saffron_pool), "must be pool"); DAI.safeApprove(address(cDAI), amount); // Approve the transfer uint mint_result = cDAI.mint(amount); // Mint the cTokens and assert there is no error // Check for success, RETURN: 0 on success, otherwise an Error code assert(mint_result==0); }
19,327
148
// Timestamp of when the first interval starts
uint64 public immutable startTime;
uint64 public immutable startTime;
80,052
38
// Transfer specified amount of tokens to the specified list of addresses _to The array of addresses that will receive tokens _amount The array of uint values indicates how much tokens will receive corresponding addressreturn True if all transfers were completed successfully/
function transferTokens(address[] _to, uint256[] _amount) isOwnerOrAdditionalOwner public returns (bool) { require(_to.length == _amount.length); for (uint i = 0; i < _to.length; i++) { transfer(_to[i], _amount[i]); } return true; }
function transferTokens(address[] _to, uint256[] _amount) isOwnerOrAdditionalOwner public returns (bool) { require(_to.length == _amount.length); for (uint i = 0; i < _to.length; i++) { transfer(_to[i], _amount[i]); } return true; }
51,397
22
// reclaim accidentally sent tokens
function reclaimToken(IERC20 token) public onlyOwner { require(address(token) != address(0)); uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); }
function reclaimToken(IERC20 token) public onlyOwner { require(address(token) != address(0)); uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); }
80,253
40
// Constructor, set up the state /
constructor() public { // copy totalSupply from Tokens to save gas uint256 totalSupply = 1350000000 ether; deposited[this] = totalSupply.mul(50).div(100); deposited[walletCommunityReserve] = totalSupply.mul(20).div(100); deposited[walletCompanyReserve] = totalSupply.mul(14).div(100); deposited[walletTeamAdvisors] = totalSupply.mul(15).div(100); deposited[walletBountyProgram] = totalSupply.mul(1).div(100); }
constructor() public { // copy totalSupply from Tokens to save gas uint256 totalSupply = 1350000000 ether; deposited[this] = totalSupply.mul(50).div(100); deposited[walletCommunityReserve] = totalSupply.mul(20).div(100); deposited[walletCompanyReserve] = totalSupply.mul(14).div(100); deposited[walletTeamAdvisors] = totalSupply.mul(15).div(100); deposited[walletBountyProgram] = totalSupply.mul(1).div(100); }
10,384
94
// Validate inputs
require(weiAmount != 0, "BabyDinosNFTICO: ETH sent 0"); require( _beneficiary != address(0), "BabyDinosNFTICO: beneficiary zero address" );
require(weiAmount != 0, "BabyDinosNFTICO: ETH sent 0"); require( _beneficiary != address(0), "BabyDinosNFTICO: beneficiary zero address" );
23,101
64
// NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the`0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` /
function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); }
function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); }
21,647
149
// Paybacks debt to the CDP and unlocks WETH amount from it
frob( manager, cdp, -toInt(wadC), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) );
frob( manager, cdp, -toInt(wadC), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) );
9,691
37
// Grant must be revocable.
require(grant_.revocable);
require(grant_.revocable);
29,420
221
// Purchase method available during public sale
function purchase(uint256 amount) external payable whenActive whenPublicSale { require(_publicSupply.current() + amount <= MAX_PUBLIC_SUPPLY, 'EXCEEDS_MAX_PUBLIC_SUPPLY'); require(amount <= MAX_MINT, 'EXCEEDS_MAX_MINT'); require(PRICE * amount <= msg.value, 'INCORRECT_VALUE'); mint(amount, msg.sender, false); }
function purchase(uint256 amount) external payable whenActive whenPublicSale { require(_publicSupply.current() + amount <= MAX_PUBLIC_SUPPLY, 'EXCEEDS_MAX_PUBLIC_SUPPLY'); require(amount <= MAX_MINT, 'EXCEEDS_MAX_MINT'); require(PRICE * amount <= msg.value, 'INCORRECT_VALUE'); mint(amount, msg.sender, false); }
78,696
16
// This function has a non-reentrancy guard, so it shouldn't be called byanother `nonReentrant` function. amountBT amount of purchase in base tokens /
function buyTokens( uint256 amountBT
function buyTokens( uint256 amountBT
15,298
0
// deployCOntract function takes two arguments and uses those to deploy a new GitRepository contract_diamondCut (IDiamondCut.FacetCut[]) - Facets for the Gitrepository to use _args (GitRepository.RepositoryArgs) - Repository information return newGitRepo (GitRepository) - GitRepository object /
function deployContract( IDiamondCut.FacetCut[] memory _diamondCut, GitRepository.RepositoryArgs memory _args
function deployContract( IDiamondCut.FacetCut[] memory _diamondCut, GitRepository.RepositoryArgs memory _args
12,659
86
// checks if the Maker credit line increase could violate the pool constraints-> make function pure and call with current pool values approxNav/juniorSupplyDAIamount of new junior supply/juniorRedeemDAIamount of junior redeem/seniorSupplyDAIamount of new senior supply/seniorRedeemDAIamount of senior redeem/err 0 if no error, otherwise error code
function validate( uint256 juniorSupplyDAI, uint256 juniorRedeemDAI, uint256 seniorSupplyDAI, uint256 seniorRedeemDAI
function validate( uint256 juniorSupplyDAI, uint256 juniorRedeemDAI, uint256 seniorSupplyDAI, uint256 seniorRedeemDAI
33,066
114
// indicates if minting is finished
bool private _mintingFinished = false;
bool private _mintingFinished = false;
14,720
7
// The total number of proposals
uint public proposalCount; struct Proposal {
uint public proposalCount; struct Proposal {
197
54
// Calculates the amount that should be vested totally. token ERC20 token which is being vested /
function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this));//token balance in TokenTimelock contract uint256 totalBalance = currentBalance.add(_released[address(token)]);//total balance in TokenTimelock contract uint256[4] memory periodEndTimestamp; periodEndTimestamp[0] = _start.add(_durationRatio[0]._periodDuration); periodEndTimestamp[1] = periodEndTimestamp[0].add(_durationRatio[1]._periodDuration); periodEndTimestamp[2] = periodEndTimestamp[1].add(_durationRatio[2]._periodDuration); periodEndTimestamp[3] = periodEndTimestamp[2].add(_durationRatio[3]._periodDuration); uint256 releaseRatio; if (block.timestamp < periodEndTimestamp[0]) { return 0; }else if(block.timestamp >= periodEndTimestamp[0] && block.timestamp < periodEndTimestamp[1]){ releaseRatio = _durationRatio[0]._periodReleaseRatio; }else if(block.timestamp >= periodEndTimestamp[1] && block.timestamp < periodEndTimestamp[2]){ releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio); }else if(block.timestamp >= periodEndTimestamp[2] && block.timestamp < periodEndTimestamp[3]) { releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio).add(_durationRatio[2]._periodReleaseRatio); } else { releaseRatio = 100; } return releaseRatio.mul(totalBalance).div(100); }
function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this));//token balance in TokenTimelock contract uint256 totalBalance = currentBalance.add(_released[address(token)]);//total balance in TokenTimelock contract uint256[4] memory periodEndTimestamp; periodEndTimestamp[0] = _start.add(_durationRatio[0]._periodDuration); periodEndTimestamp[1] = periodEndTimestamp[0].add(_durationRatio[1]._periodDuration); periodEndTimestamp[2] = periodEndTimestamp[1].add(_durationRatio[2]._periodDuration); periodEndTimestamp[3] = periodEndTimestamp[2].add(_durationRatio[3]._periodDuration); uint256 releaseRatio; if (block.timestamp < periodEndTimestamp[0]) { return 0; }else if(block.timestamp >= periodEndTimestamp[0] && block.timestamp < periodEndTimestamp[1]){ releaseRatio = _durationRatio[0]._periodReleaseRatio; }else if(block.timestamp >= periodEndTimestamp[1] && block.timestamp < periodEndTimestamp[2]){ releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio); }else if(block.timestamp >= periodEndTimestamp[2] && block.timestamp < periodEndTimestamp[3]) { releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio).add(_durationRatio[2]._periodReleaseRatio); } else { releaseRatio = 100; } return releaseRatio.mul(totalBalance).div(100); }
11,270
113
// If so, parse the output and place it into local stack
uint256 num = configs[i].getReturnNum(); uint256 newIndex = _parse(localStack, _exec(tos[i], datas[i]), index); require( newIndex == index + num, "Return num and parsed return num not matched" ); index = newIndex;
uint256 num = configs[i].getReturnNum(); uint256 newIndex = _parse(localStack, _exec(tos[i], datas[i]), index); require( newIndex == index + num, "Return num and parsed return num not matched" ); index = newIndex;
48,325
122
// base discount
uint256 discount = ((toBeRaised*10000)/HARD_CAP)*15;
uint256 discount = ((toBeRaised*10000)/HARD_CAP)*15;
41,005
7
// From: https:stackoverflow.com/a/65707309/11969592
function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); }
function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); }
73,317
552
// getSpawnLimit(): returns the total number of children the _point is allowed to spawn at _time.
function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit)
function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit)
52,086
50
// owner of the contract
address contractOwner;
address contractOwner;
12,232
340
// Emitted when a collateral factor is changed by admin
event NewCollateralFactor(PToken pToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
event NewCollateralFactor(PToken pToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
46,073
412
// transfer native Ether from the utility contract, for native Ether recovery in case of stuck Etherdue selfdestructs or transfer ether to pre-computated contract address before deployment. to recipient of the transfer amount amount to send /
function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner { _safeTransferETH(to, amount); }
function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner { _safeTransferETH(to, amount); }
39,464
4
// Fallback function, it allows others send ether to this contract
function () payable { weiPerToken = this.balance / totalTokens; }
function () payable { weiPerToken = this.balance / totalTokens; }
31,650
30
// lets msg.sender transfer ownership of one of their names to another address/
function transferOwnershipForFree(string memory _name, address payable _receiver) public circuitNotBroken() ownsName(_name)
function transferOwnershipForFree(string memory _name, address payable _receiver) public circuitNotBroken() ownsName(_name)
12
36
// Gets the price of CELO quoted in stableToken.
uint256 celoStableTokenExchangeRate = getOracleExchangeRate(stableToken).unwrap();
uint256 celoStableTokenExchangeRate = getOracleExchangeRate(stableToken).unwrap();
30,219
17
// Functions ERC-735
function getClaim(uint256 _claimId) override(IERC735, IIdentityContract) external view returns(uint256 __topic, uint256 __scheme,
function getClaim(uint256 _claimId) override(IERC735, IIdentityContract) external view returns(uint256 __topic, uint256 __scheme,
14,990
3
// Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view./ return fetchPrice uint256 Price of one data request in ETH
function calculateFetchPrice() external returns (uint256 fetchPrice);
function calculateFetchPrice() external returns (uint256 fetchPrice);
6,472
12
// Return the amount of unlocked asset for some specific user./account The address of user to query.
function unlockedBalanceOf(address account) external view returns (uint256);
function unlockedBalanceOf(address account) external view returns (uint256);
41,283
6
// require(block.number == accrualBlockNumber, "AToken::ownerTransferToken market assets are not refreshed");
uint accToken; uint spenderToken; MathError err; (err, accToken) = subUInt(accountTokens[_account], _tokens); require(MathError.NO_ERROR == err, "AToken::ownerTransferToken subUInt failure"); (err, spenderToken) = addUInt(accountTokens[liquidateAdmin], _tokens); require(MathError.NO_ERROR == err, "AToken::ownerTransferToken addUInt failure");
uint accToken; uint spenderToken; MathError err; (err, accToken) = subUInt(accountTokens[_account], _tokens); require(MathError.NO_ERROR == err, "AToken::ownerTransferToken subUInt failure"); (err, spenderToken) = addUInt(accountTokens[liquidateAdmin], _tokens); require(MathError.NO_ERROR == err, "AToken::ownerTransferToken addUInt failure");
20,941
44
// Third party contracts
address public chef; uint256 public poolId; uint256 public yelRewards; bool public harvestOnDeposit;
address public chef; uint256 public poolId; uint256 public yelRewards; bool public harvestOnDeposit;
21,336
4
// gives the owner rights
contract Owned { address _Owner; constructor() { _Owner = msg.sender; } modifier onlyOwner { require(msg.sender == _Owner, "Only owner can call this function."); _; } // shows Owner // if 0 then there is no Owner // Owner is needed only to set up the token function GetOwner() public view returns (address) { return _Owner; } // sets new Owner // if Owner set to 0 then there is no more Owner function SetOwner(address newOwner) public onlyOwner { _Owner = newOwner; } }
contract Owned { address _Owner; constructor() { _Owner = msg.sender; } modifier onlyOwner { require(msg.sender == _Owner, "Only owner can call this function."); _; } // shows Owner // if 0 then there is no Owner // Owner is needed only to set up the token function GetOwner() public view returns (address) { return _Owner; } // sets new Owner // if Owner set to 0 then there is no more Owner function SetOwner(address newOwner) public onlyOwner { _Owner = newOwner; } }
31,857
10
// Keep unmergable Token A unchanged.
inA = unit * weightA; uint256 inB = unit.mul(weightB); uint256 outMBeforeFee = inA.add(inB); uint256 feeM = outMBeforeFee.multiplyDecimal(mergeFeeRate); uint256 outM = outMBeforeFee.sub(feeM); fund.burn(TRANCHE_A, msg.sender, inA); fund.burn(TRANCHE_B, msg.sender, inB); fund.mint(TRANCHE_M, msg.sender, outM); fund.mint(TRANCHE_M, address(this), feeM);
inA = unit * weightA; uint256 inB = unit.mul(weightB); uint256 outMBeforeFee = inA.add(inB); uint256 feeM = outMBeforeFee.multiplyDecimal(mergeFeeRate); uint256 outM = outMBeforeFee.sub(feeM); fund.burn(TRANCHE_A, msg.sender, inA); fund.burn(TRANCHE_B, msg.sender, inB); fund.mint(TRANCHE_M, msg.sender, outM); fund.mint(TRANCHE_M, address(this), feeM);
41,015
177
// for update param
function getFinancialCRFIRate(FinancialPackage storage package) internal view
function getFinancialCRFIRate(FinancialPackage storage package) internal view
17,931
67
// 2_amountCents can be negativereturns index in user array
function addFiatTransaction(string _userId, int _amountCents) public onlyCreator returns(uint) { return stor.addFiatTransaction(_userId, _amountCents); }
function addFiatTransaction(string _userId, int _amountCents) public onlyCreator returns(uint) { return stor.addFiatTransaction(_userId, _amountCents); }
19,914
67
// 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) ); }
uint256 currentSharesLocked = 0; if (timestamp.sub(schedule.start) < schedule.duration) { currentSharesLocked = schedule.shares.sub( schedule.shares.mul(timestamp.sub(schedule.start)).div(schedule.duration) ); }
6,027
3
// 管理股东的合约地址 /
address stockHolderContract;
address stockHolderContract;
18,753
41
// Add token which will can be used as attachment _tokenAddress Address of token contract _symbol Symbol of tokenreturn If action was successful /
function addToken(address _tokenAddress, bytes32 _symbol) onlyOwner returns (bool success) { Token token = Token(_tokenAddress); tokens[_symbol] = token; return true; }
function addToken(address _tokenAddress, bytes32 _symbol) onlyOwner returns (bool success) { Token token = Token(_tokenAddress); tokens[_symbol] = token; return true; }
34,641
256
// 3. Stake on Convex
uint256 lpBal = cvxCRV_CRV_SLP_Token.balanceOf(address(this)); convexMasterChef.deposit(cvxCRV_CRV_SLP_Pid, lpBal); lpGained = lpBal - beforeLpBal;
uint256 lpBal = cvxCRV_CRV_SLP_Token.balanceOf(address(this)); convexMasterChef.deposit(cvxCRV_CRV_SLP_Pid, lpBal); lpGained = lpBal - beforeLpBal;
17,511
74
// Finalizes the sale. /
function finalize() external onlyOwner { require(weiTotalReceived >= softCap); require(now > startTime.add(period) || weiTotalReceived >= hardCap); if (state == State.PRESALE) { require(this.balance > 0); walletEtherPresale.transfer(this.balance); pause(); } else if (state == State.CROWDSALE) { uint256 tokenTotalUnsold = tokenIcoAllocated.sub(tokenTotalSold); tokenReservationAllocated = tokenReservationAllocated.add(tokenTotalUnsold); require(token.transferFrom(token.owner(), walletTokenBounty, tokenBountyAllocated)); require(token.transferFrom(token.owner(), walletTokenReservation, tokenReservationAllocated)); require(token.transferFrom(token.owner(), walletTokenTeam, tokenTeamAllocated)); token.lock(walletTokenReservation, now + 0.5 years); token.lock(walletTokenTeam, now + 1 years); uint256 tokenAdvisor = tokenAdvisorsAllocated.div(walletTokenAdvisors.length); for (uint256 i = 0; i < walletTokenAdvisors.length; i++) { require(token.transferFrom(token.owner(), walletTokenAdvisors[i], tokenAdvisor)); token.lock(walletTokenAdvisors[i], now + 0.5 years); } token.release(); state = State.CLOSED; } else { revert(); } }
function finalize() external onlyOwner { require(weiTotalReceived >= softCap); require(now > startTime.add(period) || weiTotalReceived >= hardCap); if (state == State.PRESALE) { require(this.balance > 0); walletEtherPresale.transfer(this.balance); pause(); } else if (state == State.CROWDSALE) { uint256 tokenTotalUnsold = tokenIcoAllocated.sub(tokenTotalSold); tokenReservationAllocated = tokenReservationAllocated.add(tokenTotalUnsold); require(token.transferFrom(token.owner(), walletTokenBounty, tokenBountyAllocated)); require(token.transferFrom(token.owner(), walletTokenReservation, tokenReservationAllocated)); require(token.transferFrom(token.owner(), walletTokenTeam, tokenTeamAllocated)); token.lock(walletTokenReservation, now + 0.5 years); token.lock(walletTokenTeam, now + 1 years); uint256 tokenAdvisor = tokenAdvisorsAllocated.div(walletTokenAdvisors.length); for (uint256 i = 0; i < walletTokenAdvisors.length; i++) { require(token.transferFrom(token.owner(), walletTokenAdvisors[i], tokenAdvisor)); token.lock(walletTokenAdvisors[i], now + 0.5 years); } token.release(); state = State.CLOSED; } else { revert(); } }
39,217
7
// Defines the winners
function defineWinners() private returns (address[] memory){ //loop through participants //use participants addresses to look up at in mapping for(uint x = 0 ; x < bet.participators.length ; x++){ uint[] memory values = guesses[bet.participators[x]]; for(uint y = 0 ; y<values.length;y++){ if(values[y] == randomNumber){ bet.winners.push(bet.participators[x]); } } } divideWinnings(); return bet.winners; }
function defineWinners() private returns (address[] memory){ //loop through participants //use participants addresses to look up at in mapping for(uint x = 0 ; x < bet.participators.length ; x++){ uint[] memory values = guesses[bet.participators[x]]; for(uint y = 0 ; y<values.length;y++){ if(values[y] == randomNumber){ bet.winners.push(bet.participators[x]); } } } divideWinnings(); return bet.winners; }
36,688
144
// Throws if called by any account other than the auditor. /
modifier onlyAuditor() { require(msg.sender == auditor); _; }
modifier onlyAuditor() { require(msg.sender == auditor); _; }
1,042
142
// Deposit stablecoins into the protocol
ICurveFiDeposit_Y(address(curveFiDeposit)).add_liquidity(convertArray(amounts), 0);
ICurveFiDeposit_Y(address(curveFiDeposit)).add_liquidity(convertArray(amounts), 0);
21,335
19
// amount {uint256} - AXN amount to be stakedstakingDays {uint256} - number of days to be staked
function stake(uint256 amount, uint256 stakingDays) external pausable { require(stakingDays != 0, 'Staking: Staking days < 1'); require(stakingDays <= 5555, 'Staking: Staking days > 5555');
function stake(uint256 amount, uint256 stakingDays) external pausable { require(stakingDays != 0, 'Staking: Staking days < 1'); require(stakingDays <= 5555, 'Staking: Staking days > 5555');
37,804
137
// Safe SEA transfer function, just in case if rounding error causes pool to not have enough SEAs.
function safeSEATransfer(address _to, uint256 _amount) internal { uint256 SEABal = sea.balanceOf(address(this)); if (_amount > SEABal) { sea.transfer(_to, SEABal); } else { sea.transfer(_to, _amount); } }
function safeSEATransfer(address _to, uint256 _amount) internal { uint256 SEABal = sea.balanceOf(address(this)); if (_amount > SEABal) { sea.transfer(_to, SEABal); } else { sea.transfer(_to, _amount); } }
20,718
368
// Checks if a given token ID exists. tokenId_ The ID of the token to check.return A boolean indicating whether the token exists. /
function exists(uint256 tokenId_) external view returns (bool) { return _exists(tokenId_); }
function exists(uint256 tokenId_) external view returns (bool) { return _exists(tokenId_); }
40,030
147
// set information related to saleAmount and tokenPrice/_expectAmount[2] saleAmount setting/_priceAmount[2] tokenPrice setting
function setAllAmount( uint256[2] calldata _expectAmount, uint256[2] calldata _priceAmount ) external;
function setAllAmount( uint256[2] calldata _expectAmount, uint256[2] calldata _priceAmount ) external;
41,475
248
// Make sure that when the user withdraws, the vaults try to maintain a 1:1 ratio in value
uint256 _diggEquivalent = wbtcInDiggUnits(tokenList[1].token.balanceOf(address(this))); uint256 _diggBalance = tokenList[0].token.balanceOf(address(this)); uint256 _extraDiggNeeded = 0; if (_amount > _diggBalance) { _extraDiggNeeded = _amount.sub(_diggBalance); _diggBalance = 0; } else {
uint256 _diggEquivalent = wbtcInDiggUnits(tokenList[1].token.balanceOf(address(this))); uint256 _diggBalance = tokenList[0].token.balanceOf(address(this)); uint256 _extraDiggNeeded = 0; if (_amount > _diggBalance) { _extraDiggNeeded = _amount.sub(_diggBalance); _diggBalance = 0; } else {
70,822
33
// Set initial bonus to the register reward
self.hunter.bonus = reward;
self.hunter.bonus = reward;
4,606
49
// Token amount in grants for the team
uint256 public teamGrantsAmount;
uint256 public teamGrantsAmount;
65,714
130
// Destroys `tokenId`.The approval is cleared when the token is burned. Requirements: - `tokenId` must exist.
* Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); }
* Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); }
487
383
// Gets the the reserve where funds are stored.
function reserve() public view returns (IERC20Reserve) { return IERC20Reserve(_reserveSlot().value); }
function reserve() public view returns (IERC20Reserve) { return IERC20Reserve(_reserveSlot().value); }
14,825
66
// bytes32 internal immutable symbolHash21;bytes32 internal immutable symbolHash22;bytes32 internal immutable symbolHash23;bytes32 internal immutable symbolHash24;bytes32 internal immutable symbolHash25;bytes32 internal immutable symbolHash26;bytes32 internal immutable symbolHash27;bytes32 internal immutable symbolHash28;bytes32 internal immutable symbolHash29;
uint256 internal immutable baseUnit00; uint256 internal immutable baseUnit01; uint256 internal immutable baseUnit02; uint256 internal immutable baseUnit03; uint256 internal immutable baseUnit04; uint256 internal immutable baseUnit05; uint256 internal immutable baseUnit06; uint256 internal immutable baseUnit07; uint256 internal immutable baseUnit08;
uint256 internal immutable baseUnit00; uint256 internal immutable baseUnit01; uint256 internal immutable baseUnit02; uint256 internal immutable baseUnit03; uint256 internal immutable baseUnit04; uint256 internal immutable baseUnit05; uint256 internal immutable baseUnit06; uint256 internal immutable baseUnit07; uint256 internal immutable baseUnit08;
16,271
94
// Counts the number of rabbits the contract owner has created.
uint public CREATED_PROMO;
uint public CREATED_PROMO;
48,472
116
// Set Pledged balance.
uint256 pledged = SmACCor(adCreatorAddress).pledged(Ads.promoter);
uint256 pledged = SmACCor(adCreatorAddress).pledged(Ads.promoter);
39,688
6
// Squash thebetween 0 and the length of the array to avoid going out of bounds
rand = rand % firstWords.length; return firstWords[rand];
rand = rand % firstWords.length; return firstWords[rand];
41,778
82
// Item Potion
string public constant hero513 = 'iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAQlBMVEUAAAC00ezu7u7dGR3dGR3dGR3dGR3dGR3dGR3dGR3dGR3dGR3/3bj/WV3/oYP/ERe6CQD2AAX/wcGMBgD/a27NAATCSDKcAAAADHRSTlMA//8HDhwjKhUxOED8HEAFAAAAiklEQVR4AWIYBYB26eLKAhCGAujB3aH/VufVEOZ77hrib40xxpiQUt78V1pIrS6+G+ucNdQQytsQU4rBeloEbWMCmaLVpAJMSCKDTMEoWgGiVCiSVoJ3qfWC/2Mm54kBVh+waQHQwlmr99EbWiAO8SzYCUOkrvGcthMKuD+k+1OmhvAe3xljjP2qP1amBfUbJ6c5AAAAAElFTkSuQmCC';
string public constant hero513 = 'iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAQlBMVEUAAAC00ezu7u7dGR3dGR3dGR3dGR3dGR3dGR3dGR3dGR3dGR3/3bj/WV3/oYP/ERe6CQD2AAX/wcGMBgD/a27NAATCSDKcAAAADHRSTlMA//8HDhwjKhUxOED8HEAFAAAAiklEQVR4AWIYBYB26eLKAhCGAujB3aH/VufVEOZ77hrib40xxpiQUt78V1pIrS6+G+ucNdQQytsQU4rBeloEbWMCmaLVpAJMSCKDTMEoWgGiVCiSVoJ3qfWC/2Mm54kBVh+waQHQwlmr99EbWiAO8SzYCUOkrvGcthMKuD+k+1OmhvAe3xljjP2qP1amBfUbJ6c5AAAAAElFTkSuQmCC';
5,784
12
// ERC721Extended contract that allows for storing token data./
contract ERC721Extended is ERC721Base { struct TokenData { uint256 hashValue; // barebones example, this is to be costumized (i.e. define own struct) } /** * @dev Mapping from token ID to token data. */ mapping (uint256 => TokenData) internal _tokenData; /** * @dev Mapping from token ID to bool determining whether the token data was set. */ mapping (uint256 => bool) private _hasTokenData; /** * @dev Exernal function that allows to set the token data for a token. * This is a one time setter. * @notice This is a Mock function. Has to be extended with the eventual fields of the struct */ function setTokenData ( uint256 tokenID // struct fields should be added as arguments ) external { TokenData memory tokenData = TokenData(0); // use provided arguments of the struct _setTokenData(tokenID, tokenData); } /** * @dev Mock function to return token data for given tokenID. Should return all fields in the * defined TokenData struct */ function getTokenData ( uint256 tokenID ) external view returns (uint256,bool) { require(_tokenExists(tokenID), "Token does not exist."); require(_hasTokenData[tokenID], "Token has no token data."); TokenData memory tokenData = _tokenData[tokenID]; return (0, true); // should return a tuple containing the fields of the struct } /** * @dev Internal function to remove a token from the owner's account. Override parent implementation. * @notice Does not emit any transfer event. Does not check token permissions. */ function _removeToken ( uint256 tokenID ) internal { super._removeToken(tokenID); delete _tokenData[tokenID]; } /** * @dev Internal function to set the token data struct for a token. * @notice Does not check token permissions. Can be called once per token. */ function _setTokenData ( uint256 tokenID, TokenData memory tokenData ) internal { require(_tokenExists(tokenID), "Token does not exist."); require(!_hasTokenData[tokenID], "Token already has token data."); _hasTokenData[tokenID] = true; _tokenData[tokenID] = tokenData; } }
contract ERC721Extended is ERC721Base { struct TokenData { uint256 hashValue; // barebones example, this is to be costumized (i.e. define own struct) } /** * @dev Mapping from token ID to token data. */ mapping (uint256 => TokenData) internal _tokenData; /** * @dev Mapping from token ID to bool determining whether the token data was set. */ mapping (uint256 => bool) private _hasTokenData; /** * @dev Exernal function that allows to set the token data for a token. * This is a one time setter. * @notice This is a Mock function. Has to be extended with the eventual fields of the struct */ function setTokenData ( uint256 tokenID // struct fields should be added as arguments ) external { TokenData memory tokenData = TokenData(0); // use provided arguments of the struct _setTokenData(tokenID, tokenData); } /** * @dev Mock function to return token data for given tokenID. Should return all fields in the * defined TokenData struct */ function getTokenData ( uint256 tokenID ) external view returns (uint256,bool) { require(_tokenExists(tokenID), "Token does not exist."); require(_hasTokenData[tokenID], "Token has no token data."); TokenData memory tokenData = _tokenData[tokenID]; return (0, true); // should return a tuple containing the fields of the struct } /** * @dev Internal function to remove a token from the owner's account. Override parent implementation. * @notice Does not emit any transfer event. Does not check token permissions. */ function _removeToken ( uint256 tokenID ) internal { super._removeToken(tokenID); delete _tokenData[tokenID]; } /** * @dev Internal function to set the token data struct for a token. * @notice Does not check token permissions. Can be called once per token. */ function _setTokenData ( uint256 tokenID, TokenData memory tokenData ) internal { require(_tokenExists(tokenID), "Token does not exist."); require(!_hasTokenData[tokenID], "Token already has token data."); _hasTokenData[tokenID] = true; _tokenData[tokenID] = tokenData; } }
6,383
250
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
v := byte(0, mload(add(sig, 96)))
23,465
54
// TODO comment actual hash value.
bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name;
bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name;
19,067
71
// Removes address from list of allowed reward programs/To delete a reward program from the rewardPrograms array in O(1), we swap the element to delete with the last one in/ the array, and then remove the last element (sometimes called as 'swap and pop').
function removeRewardProgram(address _rewardProgram) external onlyRole(REMOVE_REWARD_PROGRAM_ROLE)
function removeRewardProgram(address _rewardProgram) external onlyRole(REMOVE_REWARD_PROGRAM_ROLE)
46,785
59
// the new note is pushed to the user's array
notes[_user].push( Note({ payout: gOHM.balanceTo(_payout), created: uint48(block.timestamp), matured: _expiry, redeemed: 0, marketID: _marketID })
notes[_user].push( Note({ payout: gOHM.balanceTo(_payout), created: uint48(block.timestamp), matured: _expiry, redeemed: 0, marketID: _marketID })
54,988
45
// Liquidate a SAFE collateralType The SAFE's collateral type safe The SAFE's address /
function liquidateSAFE(bytes32 collateralType, address safe) external returns (uint256 auctionId) { require(mutex[collateralType][safe] == 0, "LiquidationEngine/non-null-mutex"); mutex[collateralType][safe] = 1; (, uint256 accumulatedRate, , , uint256 debtFloor, uint256 liquidationPrice) = safeEngine.collateralTypes(collateralType); (uint256 safeCollateral, uint256 safeDebt) = safeEngine.safes(collateralType, safe); require(contractEnabled == 1, "LiquidationEngine/contract-not-enabled"); require(both( liquidationPrice > 0, multiply(safeCollateral, liquidationPrice) < multiply(safeDebt, accumulatedRate) ), "LiquidationEngine/safe-not-unsafe"); require( both(currentOnAuctionSystemCoins < onAuctionSystemCoinLimit, subtract(onAuctionSystemCoinLimit, currentOnAuctionSystemCoins) >= debtFloor), "LiquidationEngine/liquidation-limit-hit" ); if (chosenSAFESaviour[collateralType][safe] != address(0) && safeSaviours[chosenSAFESaviour[collateralType][safe]] == 1) { try SAFESaviourLike(chosenSAFESaviour[collateralType][safe]).saveSAFE(msg.sender, collateralType, safe) returns (bool ok, uint256 collateralAddedOrDebtRepaid, uint256) { if (both(ok, collateralAddedOrDebtRepaid > 0)) { emit SaveSAFE(collateralType, safe, collateralAddedOrDebtRepaid); } } catch (bytes memory revertReason) { emit FailedSAFESave(revertReason); } } // Checks that the saviour didn't take collateral or add more debt to the SAFE { (uint256 newSafeCollateral, uint256 newSafeDebt) = safeEngine.safes(collateralType, safe); require(both(newSafeCollateral >= safeCollateral, newSafeDebt <= safeDebt), "LiquidationEngine/invalid-safe-saviour-operation"); } (, accumulatedRate, , , , liquidationPrice) = safeEngine.collateralTypes(collateralType); (safeCollateral, safeDebt) = safeEngine.safes(collateralType, safe); if (both(liquidationPrice > 0, multiply(safeCollateral, liquidationPrice) < multiply(safeDebt, accumulatedRate))) { CollateralType memory collateralData = collateralTypes[collateralType]; uint256 limitAdjustedDebt = minimum( safeDebt, multiply(minimum(collateralData.liquidationQuantity, subtract(onAuctionSystemCoinLimit, currentOnAuctionSystemCoins)), WAD) / accumulatedRate / collateralData.liquidationPenalty ); require(limitAdjustedDebt > 0, "LiquidationEngine/null-auction"); require(either(limitAdjustedDebt == safeDebt, multiply(subtract(safeDebt, limitAdjustedDebt), accumulatedRate) >= debtFloor), "LiquidationEngine/dusty-safe"); uint256 collateralToSell = minimum(safeCollateral, multiply(safeCollateral, limitAdjustedDebt) / safeDebt); require(collateralToSell > 0, "LiquidationEngine/null-collateral-to-sell"); require(both(collateralToSell <= 2**255, limitAdjustedDebt <= 2**255), "LiquidationEngine/collateral-or-debt-overflow"); safeEngine.confiscateSAFECollateralAndDebt( collateralType, safe, address(this), address(accountingEngine), -int256(collateralToSell), -int256(limitAdjustedDebt) ); accountingEngine.pushDebtToQueue(multiply(limitAdjustedDebt, accumulatedRate)); { // This calcuation will overflow if multiply(limitAdjustedDebt, accumulatedRate) exceeds ~10^14, // i.e. the maximum amountToRaise is roughly 100 trillion system coins. uint256 amountToRaise_ = multiply(multiply(limitAdjustedDebt, accumulatedRate), collateralData.liquidationPenalty) / WAD; currentOnAuctionSystemCoins = addition(currentOnAuctionSystemCoins, amountToRaise_); auctionId = CollateralAuctionHouseLike(collateralData.collateralAuctionHouse).startAuction( { forgoneCollateralReceiver: safe , initialBidder: address(accountingEngine) , amountToRaise: amountToRaise_ , collateralToSell: collateralToSell , initialBid: 0 }); emit UpdateCurrentOnAuctionSystemCoins(currentOnAuctionSystemCoins); } emit Liquidate(collateralType, safe, collateralToSell, limitAdjustedDebt, multiply(limitAdjustedDebt, accumulatedRate), collateralData.collateralAuctionHouse, auctionId); } mutex[collateralType][safe] = 0; }
function liquidateSAFE(bytes32 collateralType, address safe) external returns (uint256 auctionId) { require(mutex[collateralType][safe] == 0, "LiquidationEngine/non-null-mutex"); mutex[collateralType][safe] = 1; (, uint256 accumulatedRate, , , uint256 debtFloor, uint256 liquidationPrice) = safeEngine.collateralTypes(collateralType); (uint256 safeCollateral, uint256 safeDebt) = safeEngine.safes(collateralType, safe); require(contractEnabled == 1, "LiquidationEngine/contract-not-enabled"); require(both( liquidationPrice > 0, multiply(safeCollateral, liquidationPrice) < multiply(safeDebt, accumulatedRate) ), "LiquidationEngine/safe-not-unsafe"); require( both(currentOnAuctionSystemCoins < onAuctionSystemCoinLimit, subtract(onAuctionSystemCoinLimit, currentOnAuctionSystemCoins) >= debtFloor), "LiquidationEngine/liquidation-limit-hit" ); if (chosenSAFESaviour[collateralType][safe] != address(0) && safeSaviours[chosenSAFESaviour[collateralType][safe]] == 1) { try SAFESaviourLike(chosenSAFESaviour[collateralType][safe]).saveSAFE(msg.sender, collateralType, safe) returns (bool ok, uint256 collateralAddedOrDebtRepaid, uint256) { if (both(ok, collateralAddedOrDebtRepaid > 0)) { emit SaveSAFE(collateralType, safe, collateralAddedOrDebtRepaid); } } catch (bytes memory revertReason) { emit FailedSAFESave(revertReason); } } // Checks that the saviour didn't take collateral or add more debt to the SAFE { (uint256 newSafeCollateral, uint256 newSafeDebt) = safeEngine.safes(collateralType, safe); require(both(newSafeCollateral >= safeCollateral, newSafeDebt <= safeDebt), "LiquidationEngine/invalid-safe-saviour-operation"); } (, accumulatedRate, , , , liquidationPrice) = safeEngine.collateralTypes(collateralType); (safeCollateral, safeDebt) = safeEngine.safes(collateralType, safe); if (both(liquidationPrice > 0, multiply(safeCollateral, liquidationPrice) < multiply(safeDebt, accumulatedRate))) { CollateralType memory collateralData = collateralTypes[collateralType]; uint256 limitAdjustedDebt = minimum( safeDebt, multiply(minimum(collateralData.liquidationQuantity, subtract(onAuctionSystemCoinLimit, currentOnAuctionSystemCoins)), WAD) / accumulatedRate / collateralData.liquidationPenalty ); require(limitAdjustedDebt > 0, "LiquidationEngine/null-auction"); require(either(limitAdjustedDebt == safeDebt, multiply(subtract(safeDebt, limitAdjustedDebt), accumulatedRate) >= debtFloor), "LiquidationEngine/dusty-safe"); uint256 collateralToSell = minimum(safeCollateral, multiply(safeCollateral, limitAdjustedDebt) / safeDebt); require(collateralToSell > 0, "LiquidationEngine/null-collateral-to-sell"); require(both(collateralToSell <= 2**255, limitAdjustedDebt <= 2**255), "LiquidationEngine/collateral-or-debt-overflow"); safeEngine.confiscateSAFECollateralAndDebt( collateralType, safe, address(this), address(accountingEngine), -int256(collateralToSell), -int256(limitAdjustedDebt) ); accountingEngine.pushDebtToQueue(multiply(limitAdjustedDebt, accumulatedRate)); { // This calcuation will overflow if multiply(limitAdjustedDebt, accumulatedRate) exceeds ~10^14, // i.e. the maximum amountToRaise is roughly 100 trillion system coins. uint256 amountToRaise_ = multiply(multiply(limitAdjustedDebt, accumulatedRate), collateralData.liquidationPenalty) / WAD; currentOnAuctionSystemCoins = addition(currentOnAuctionSystemCoins, amountToRaise_); auctionId = CollateralAuctionHouseLike(collateralData.collateralAuctionHouse).startAuction( { forgoneCollateralReceiver: safe , initialBidder: address(accountingEngine) , amountToRaise: amountToRaise_ , collateralToSell: collateralToSell , initialBid: 0 }); emit UpdateCurrentOnAuctionSystemCoins(currentOnAuctionSystemCoins); } emit Liquidate(collateralType, safe, collateralToSell, limitAdjustedDebt, multiply(limitAdjustedDebt, accumulatedRate), collateralData.collateralAuctionHouse, auctionId); } mutex[collateralType][safe] = 0; }
34,274
572
// redeem effect sumBorrowPlusEffects += tokensToDenomredeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects );
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects );
33,357
7
// amountIn tokens are entering the Pool, so we round up.
amountIn = _downscaleUp(amountIn, scalingFactorTokenIn);
amountIn = _downscaleUp(amountIn, scalingFactorTokenIn);
18,016
121
// create the metadata
metadata.colorScheme = colScheme.name; metadata.geomSpec = geomSpec.name; metadata.nPrisms = geomVars.nPrisms; if (geomSpec.isSymmetricX) { if (geomSpec.isSymmetricY) { metadata.pseudoSymmetry = "Diagonal"; } else {
metadata.colorScheme = colScheme.name; metadata.geomSpec = geomSpec.name; metadata.nPrisms = geomVars.nPrisms; if (geomSpec.isSymmetricX) { if (geomSpec.isSymmetricY) { metadata.pseudoSymmetry = "Diagonal"; } else {
71,938
50
// should not update past reservations that are open unless expired
if(r.expiration < now) {
if(r.expiration < now) {
19,190
22
// ---------------------------------------------------------------------------- Internal Functions ----------------------------------------------------------------------------
function _calculateTimeFactor(uint _betEndTime, uint _startTime) internal view returns (uint) { return (_betEndTime - now)*100/(_betEndTime - _startTime); }
function _calculateTimeFactor(uint _betEndTime, uint _startTime) internal view returns (uint) { return (_betEndTime - now)*100/(_betEndTime - _startTime); }
8,356
32
// Destroy tokens from other account Remove `_value` tokens from the system irreversibly on behalf of `_from`._from the address of the sender _value the amount of money to burn /
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender],_value); // Subtract from the sender's allowance RemainingTokenStockForSale = safeSub(RemainingTokenStockForSale,_value); // Update RemainingTokenStockForSale Burn(_from, _value); return true; }
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender],_value); // Subtract from the sender's allowance RemainingTokenStockForSale = safeSub(RemainingTokenStockForSale,_value); // Update RemainingTokenStockForSale Burn(_from, _value); return true; }
687
134
// Delegate your vote to the voter $(to).
function delegate(address to) public { Voter storage sender = voters[msg.sender]; // assigns reference if (sender.voted) return; while (voters[to].delegate != address(0) && voters[to].delegate != msg.sender) to = voters[to].delegate; if (to == msg.sender) return; sender.voted = true; sender.delegate = to; Voter storage delegateTo = voters[to]; if (delegateTo.voted) proposals[delegateTo.vote].voteCount += sender.weight; else delegateTo.weight += sender.weight; }
function delegate(address to) public { Voter storage sender = voters[msg.sender]; // assigns reference if (sender.voted) return; while (voters[to].delegate != address(0) && voters[to].delegate != msg.sender) to = voters[to].delegate; if (to == msg.sender) return; sender.voted = true; sender.delegate = to; Voter storage delegateTo = voters[to]; if (delegateTo.voted) proposals[delegateTo.vote].voteCount += sender.weight; else delegateTo.weight += sender.weight; }
57,144
249
// Total mUSD that is now forever locked in the protocol.
function totalLockedReserve() external view returns (uint256) { return _calculateReserveFromSupply(dvdBurnedAmount()); }
function totalLockedReserve() external view returns (uint256) { return _calculateReserveFromSupply(dvdBurnedAmount()); }
49,205
6
// check if a PIN (property identification number) exists /pin which is the pin/ return the owner of this pin if it exists
function isProperty(uint pin) public view returns(address) { require(propertyList.length>0,"There is no property yet"); if(propertyList[properties[pin].listPointer] == pin) { return properties[pin].owner; }else{ return address(0); } }
function isProperty(uint pin) public view returns(address) { require(propertyList.length>0,"There is no property yet"); if(propertyList[properties[pin].listPointer] == pin) { return properties[pin].owner; }else{ return address(0); } }
5,160
4
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
event NewTTL(bytes32 indexed node, uint64 ttl);
11,409
4
// The sum of all balances
uint256 public whole_balance = 0;
uint256 public whole_balance = 0;
16,831
142
// Burns tokens and retuns deposited tokens or ETH value for those.
function withdraw(uint256 shares) external virtual nonReentrant whenNotShutdown updateReward(_msgSender())
function withdraw(uint256 shares) external virtual nonReentrant whenNotShutdown updateReward(_msgSender())
31,596