contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
setRestaking
function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } }
// Set a new restaking adapter.
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 6437, 7261 ] }
9,207
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
removeRestaking
function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); }
// remove restaking
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 7289, 7663 ] }
9,208
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
getMultiplier
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } }
// Return reward multiplier over the given _from to _to block.
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 7737, 8165 ] }
9,209
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
pendingCrops
function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); }
// View function to see pending CROPSs on frontend.
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 8225, 8998 ] }
9,210
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
pendingOther
function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); }
// View function to see our pending OTHERs on frontend (whatever the restaked reward token is)
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 9101, 9694 ] }
9,211
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
massUpdatePools
function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } }
// Update reward vairables for all pools. Be careful of gas spending!
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 9772, 9957 ] }
9,212
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
getPoolsLP
function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; }
// Get pool LP according _pid
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 9999, 10117 ] }
9,213
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
updatePool
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
// Update reward variables of the given pool to be up-to-date.
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 10188, 11567 ] }
9,214
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
getPoolSupply
function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } }
// Internal view function to get the amount of LP tokens staked in the specified pool
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 11661, 11974 ] }
9,215
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
deposit
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
// Deposit LP tokens to MasterChef for CROPS allocation.
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 12275, 13621 ] }
9,216
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
UsingETHnonethpooldeposit
function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); }
// Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH.
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 13716, 14423 ] }
9,217
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
UsingETHdeposit
function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); }
// Deposit LP tokens to MasterChef for CROPS allocation using ETH.
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 14502, 15173 ] }
9,218
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
withdraw
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
// Withdraw LP tokens from MasterChef.
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 15220, 16450 ] }
9,219
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
emergencyWithdraw
function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); }
// Withdraw without caring about rewards. EMERGENCY ONLY.
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 16516, 16995 ] }
9,220
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
withdrawRestakedLP
function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); }
// Withdraw LP tokens from the restaking target back here // Does not claim rewards
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 17092, 17549 ] }
9,221
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
safeCropsTransfer
function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } }
// Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs.
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 17660, 17950 ] }
9,222
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
safeOtherTransfer
function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } }
// as above but for any restaking token
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 17998, 18381 ] }
9,223
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
dev
function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; }
// Update dev address by the previous dev.
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 18432, 18566 ] }
9,224
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
globalDecay
function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; }
// globalDecay function
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 18602, 19433 ] }
9,225
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
changetokensPerBlock
function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; }
//change the TPB(tokensPerBlock)
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 19484, 19660 ] }
9,226
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
changetransBurnrate
function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; }
//change the TBR(transBurnRate)
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 19704, 19882 ] }
9,227
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
changedecayBurnrate
function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; }
//change the DBR(decayBurnrate)
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 19926, 20104 ] }
9,228
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
changeteamMintrate
function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; }
//change the TMR(teamMintRate)
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 20147, 20319 ] }
9,229
MasterChef
@openzeppelin/contracts/access/Ownable.sol
0x9cd44f132d3ce92c9a4cbfc34581e11f1424fd26
Solidity
MasterChef
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 otherRewardDebt; // // We do some fancy math here. Basically, any point in time, the amount of CROPSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCropsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCropsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CROPSs to distribute per block. uint256 lastRewardBlock; // Last block number that CROPSs distribution occurs. uint256 accCropsPerShare; // Accumulated CROPSs per share, times 1e12. See below. uint256 accOtherPerShare; // Accumulated OTHERs per share, times 1e12. See below. IStakingAdapter adapter; // Manages external farming IERC20 otherToken; // The OTHER reward token for this pool, if any } // The CROPS TOKEN! CropsToken public crops; // Dev address. address public devaddr; // Block number when bonus CROPS period ends. uint256 public bonusEndBlock; // CROPS tokens created per block. uint256 public cropsPerBlock; // Bonus muliplier for early crops makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CROPS mining starts. uint256 public startBlock; // initial value of teamMintrate uint256 public teamMintrate = 300;// additional 3% of tokens are minted and these are sent to the dev. // Max value of tokenperblock uint256 public constant maxtokenperblock = 10*10**18;// 10 token per block // Max value of teamrewards uint256 public constant maxteamMintrate = 1000;// 10% mapping (address => bool) private poolIsAdded; // Timer variables for globalDecay uint256 public timestart = 0; // Event logs event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CropsToken _crops, address _devaddr, uint256 _cropsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { crops = _crops; devaddr = _devaddr; cropsPerBlock = _cropsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } // rudimentary checks for the staking adapter modifier validAdapter(IStakingAdapter _adapter) { require(address(_adapter) != address(0), "no adapter specified"); require(_adapter.rewardTokenAddress() != address(0), "no other reward token specified in staking adapter"); require(_adapter.lpTokenAddress() != address(0), "no staking token specified in staking adapter"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: IStakingAdapter(0), otherToken: IERC20(0) })); } // Add a new lp to the pool that uses restaking. Can only be called by the owner. function addWithRestaking(uint256 _allocPoint, bool _withUpdate, IStakingAdapter _adapter) public onlyOwner validAdapter(_adapter) { IERC20 _lpToken = IERC20(_adapter.lpTokenAddress()); require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCropsPerShare: 0, accOtherPerShare: 0, adapter: _adapter, otherToken: IERC20(_adapter.rewardTokenAddress()) })); } // Update the given pool's CROPS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set a new restaking adapter. function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) { if (_claim) { updatePool(_pid); } if (isRestaking(_pid)) { withdrawRestakedLP(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(address(pool.lpToken) == _adapter.lpTokenAddress(), "LP mismatch"); pool.accOtherPerShare = 0; pool.adapter = _adapter; pool.otherToken = IERC20(_adapter.rewardTokenAddress()); // transfer LPs to new target if we have any uint256 poolBal = pool.lpToken.balanceOf(address(this)); if (poolBal > 0) { pool.lpToken.safeTransfer(address(pool.adapter), poolBal); pool.adapter.deposit(poolBal); } } // remove restaking function removeRestaking(uint256 _pid, bool _claim) public onlyOwner { require(isRestaking(_pid), "not a restaking pool"); if (_claim) { updatePool(_pid); } withdrawRestakedLP(_pid); poolInfo[_pid].adapter = IStakingAdapter(address(0)); require(!isRestaking(_pid), "failed to remove restaking"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending CROPSs on frontend. function pendingCrops(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCropsPerShare = pool.accCropsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCropsPerShare = accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCropsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see our pending OTHERs on frontend (whatever the restaked reward token is) function pendingOther(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOtherPerShare = pool.accOtherPerShare; uint256 lpSupply = pool.adapter.balance(); if (lpSupply != 0) { uint256 otherReward = pool.adapter.pending(); accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Get pool LP according _pid function getPoolsLP(uint256 _pid) external view returns (IERC20) { return poolInfo[_pid].lpToken; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = getPoolSupply(_pid); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (isRestaking(_pid)) { uint256 pendingOtherTokens = pool.adapter.pending(); if (pendingOtherTokens >= 0) { uint256 otherBalanceBefore = pool.otherToken.balanceOf(address(this)); pool.adapter.claim(); uint256 otherBalanceAfter = pool.otherToken.balanceOf(address(this)); pendingOtherTokens = otherBalanceAfter.sub(otherBalanceBefore); pool.accOtherPerShare = pool.accOtherPerShare.add(pendingOtherTokens.mul(1e12).div(lpSupply)); } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cropsReward = multiplier.mul(cropsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); crops.mint(devaddr, cropsReward.div(10000).mul(teamMintrate)); crops.mint(address(this), cropsReward); pool.accCropsPerShare = pool.accCropsPerShare.add(cropsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Internal view function to get the amount of LP tokens staked in the specified pool function getPoolSupply(uint256 _pid) internal view returns (uint256 lpSupply) { PoolInfo memory pool = poolInfo[_pid]; if (isRestaking(_pid)) { lpSupply = pool.adapter.balance(); } else { lpSupply = pool.lpToken.balanceOf(address(this)); } } function isRestaking(uint256 _pid) public view returns (bool outcome) { if (address(poolInfo[_pid].adapter) != address(0)) { outcome = true; } else { outcome = false; } } // Deposit LP tokens to MasterChef for CROPS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 otherPending = 0; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (isRestaking(_pid)) { pool.lpToken.safeTransfer(address(pool.adapter), _amount); pool.adapter.deposit(_amount); } user.amount = user.amount.add(_amount); } // we can't guarantee we have the tokens until after adapter.deposit() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation at non-ETH pool using ETH. function UsingETHnonethpooldeposit(uint256 _pid, address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][useraccount]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, _pid, _amount); } // Deposit LP tokens to MasterChef for CROPS allocation using ETH. function UsingETHdeposit(address useraccount, uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][useraccount]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); safeCropsTransfer(useraccount, pending); } pool.lpToken.safeTransferFrom(address(useraccount), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); emit Deposit(useraccount, 0, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCropsPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCropsTransfer(msg.sender, pending); } uint256 otherPending = user.amount.mul(pool.accOtherPerShare).div(1e12).sub(user.otherRewardDebt); if(_amount > 0) { user.amount = user.amount.sub(_amount); if (isRestaking(_pid)) { pool.adapter.withdraw(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } // we can't guarantee we have the tokens until after adapter.withdraw() if (otherPending > 0) { safeOtherTransfer(msg.sender, otherPending, _pid); } user.rewardDebt = user.amount.mul(pool.accCropsPerShare).div(1e12); user.otherRewardDebt = user.amount.mul(pool.accOtherPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; if (isRestaking(_pid)) { pool.adapter.withdraw(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Withdraw LP tokens from the restaking target back here // Does not claim rewards function withdrawRestakedLP(uint256 _pid) internal { require(isRestaking(_pid), "not a restaking pool"); PoolInfo storage pool = poolInfo[_pid]; uint lpBalanceBefore = pool.lpToken.balanceOf(address(this)); pool.adapter.emergencyWithdraw(); uint lpBalanceAfter = pool.lpToken.balanceOf(address(this)); emit EmergencyWithdraw(address(pool.adapter), _pid, lpBalanceAfter.sub(lpBalanceBefore)); } // Safe crops transfer function, just in case if rounding error causes pool to not have enough CROPSs. function safeCropsTransfer(address _to, uint256 _amount) internal { uint256 cropsBal = crops.balanceOf(address(this)); if (_amount > cropsBal) { crops.transfer(_to, cropsBal); } else { crops.transfer(_to, _amount); } } // as above but for any restaking token function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint256 otherBal = pool.otherToken.balanceOf(address(this)); if (_amount > otherBal) { pool.otherToken.transfer(_to, otherBal); } else { pool.otherToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // globalDecay function function globalDecay() public { uint256 timeinterval = now.sub(timestart); require(timeinterval > 21600, "timelimit-6hours is not finished yet"); uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken); crops.mint(msg.sender, decaytokenvalue); crops.mint(address(this), differtoken); timestart = now; } //change the TPB(tokensPerBlock) function changetokensPerBlock(uint256 _newTPB) public onlyOwner { require(_newTPB <= maxtokenperblock, "too high value"); cropsPerBlock = _newTPB; } //change the TBR(transBurnRate) function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { crops.changetransBurnrate(_newtransBurnrate); return true; } //change the DBR(decayBurnrate) function changedecayBurnrate(uint256 _newdecayBurnrate) public onlyOwner returns (bool) { crops.changedecayBurnrate(_newdecayBurnrate); return true; } //change the TMR(teamMintRate) function changeteamMintrate(uint256 _newTMR) public onlyOwner { require(_newTMR <= maxteamMintrate, "too high value"); teamMintrate = _newTMR; } //burn tokens function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; } }
// MasterChef is the master of Crops. He can make Crops and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once CROPS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
burntoken
function burntoken(address account, uint256 amount) public onlyOwner returns (bool) { crops.burn(account, amount); return true; }
//burn tokens
LineComment
v0.6.12+commit.27d51765
None
ipfs://171f8ea33a77e533f4374f06d45af1917148d695e1f57cab9dd96fb435508be8
{ "func_code_index": [ 20341, 20498 ] }
9,230
GrapevineToken
contracts/grapevine/token/GrapevineToken.sol
0x0938e3433dd1489d117b32718360bec497c7c987
Solidity
GrapevineToken
contract GrapevineToken is DetailedERC20, BurnableToken, StandardToken, Ownable { constructor() DetailedERC20("TESTGVINE", "TESTGVINE", 18) public { totalSupply_ = 825000000 * (10 ** uint256(decimals)); // Update total supply with the decimal amount balances[msg.sender] = totalSupply_; emit Transfer(address(0), msg.sender, totalSupply_); } /** * @dev burns the provided the _value, can be used only by the owner of the contract. * @param _value The value of the tokens to be burnt. */ function burn(uint256 _value) public onlyOwner { super.burn(_value); } }
/** * @title Grapevine Token * @dev Grapevine Token **/
NatSpecMultiLine
burn
function burn(uint256 _value) public onlyOwner { super.burn(_value); }
/** * @dev burns the provided the _value, can be used only by the owner of the contract. * @param _value The value of the tokens to be burnt. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://111d08c1f98485c7544c485b72775c76c8e61f3904cf8d1a8534fd8ec32e858c
{ "func_code_index": [ 525, 606 ] }
9,231
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
listSynth
function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); }
//==============================ADMIN================================// // Lists a synth and its parent EMP address
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 4558, 5060 ] }
9,232
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
listPool
function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); }
// Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0"
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 5193, 6010 ] }
9,233
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
addAdmin
function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; }
// Quorum Action 1
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 6141, 6424 ] }
9,234
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
snapshot
function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. }
// Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 6892, 7148 ] }
9,235
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
snapshotInEra
function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); }
// Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools()
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 7281, 7496 ] }
9,236
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
snapshotWithOffset
function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. }
// Snapshot with offset (in case runs out of gas)
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 7554, 7904 ] }
9,237
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
snapshotInEraWithOffset
function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances }
// Snapshot a particular rewwardAsset, with offset
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 7963, 8861 ] }
9,238
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
updateRewards
function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); }
// Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 8972, 10620 ] }
9,239
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
removeReward
function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); }
// Quorum Action // Remove unclaimed rewards and disable era for claiming
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 10707, 11154 ] }
9,240
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
sweep
function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); }
// Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens)
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 11323, 11510 ] }
9,241
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
lock
function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); }
//============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 11641, 12878 ] }
9,242
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
unlock
function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); }
// Member unlocks all from a pool
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 12920, 13496 ] }
9,243
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
registerClaim
function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); }
//============================== USER - CLAIM================================// // Member registers claim in a single pool
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 13632, 14001 ] }
9,244
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
registerAllClaims
function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; }
// Member registers claim in all pools
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 14048, 15091 ] }
9,245
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
claim
function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } }
// Member claims in a era
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 15125, 16334 ] }
9,246
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
checkClaim
function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; }
// Member checks claims in all pools
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 16379, 16747 ] }
9,247
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
checkClaimInPool
function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; }
// Member checks claim in a single pool
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 16795, 17619 ] }
9,248
PerlinXRewards
PerlinXRewards.sol
0x6548b06acbc1b7674a8a5a2ea6787ed54ef6d438
Solidity
PerlinXRewards
contract PerlinXRewards { using SafeMath for uint256; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public PERL; address public treasury; address[] public arrayAdmins; address[] public arrayPerlinPools; address[] public arraySynths; address[] public arrayMembers; uint256 public currentEra; mapping(address => bool) public isAdmin; // Tracks admin status mapping(address => bool) public poolIsListed; // Tracks current listing status mapping(address => bool) public poolHasMembers; // Tracks current staking status mapping(address => bool) public poolWasListed; // Tracks if pool was ever listed mapping(address => uint256) public mapAsset_Rewards; // Maps rewards for each asset (PERL, BAL, UNI etc) mapping(address => uint256) public poolWeight; // Allows a reward weight to be applied; 100 = 1.0 mapping(uint256 => uint256) public mapEra_Total; // Total PERL staked in each era mapping(uint256 => bool) public eraIsOpen; // Era is open of collecting rewards mapping(uint256 => mapping(address => uint256)) public mapEraAsset_Reward; // Reward allocated for era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Balance; // Perls in each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Share; // Share of reward for each pool, per era mapping(uint256 => mapping(address => uint256)) public mapEraPool_Claims; // Total LP tokens locked for each pool, per era mapping(address => address) public mapPool_Asset; // Uniswap pools provide liquidity to non-PERL asset mapping(address => address) public mapSynth_EMP; // Synthetic Assets have a management contract mapping(address => bool) public isMember; // Is Member mapping(address => uint256) public mapMember_poolCount; // Total number of Pools member is in mapping(address => address[]) public mapMember_arrayPools; // Array of pools for member mapping(address => mapping(address => uint256)) public mapMemberPool_Balance; // Member's balance in pool mapping(address => mapping(address => bool)) public mapMemberPool_Added; // Member's balance in pool mapping(address => mapping(uint256 => bool)) public mapMemberEra_hasRegistered; // Member has registered mapping(address => mapping(uint256 => mapping(address => uint256))) public mapMemberEraPool_Claim; // Value of claim per pool, per era mapping(address => mapping(uint256 => mapping(address => bool))) public mapMemberEraAsset_hasClaimed; // Boolean claimed // Events event Snapshot( address indexed admin, uint256 indexed era, uint256 rewardForEra, uint256 perlTotal, uint256 validPoolCount, uint256 validMemberCount, uint256 date ); event NewPool( address indexed admin, address indexed pool, address indexed asset, uint256 assetWeight ); event NewSynth( address indexed pool, address indexed synth, address indexed expiringMultiParty ); event MemberLocks( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberUnlocks( address indexed member, address indexed pool, uint256 balance, uint256 indexed currentEra ); event MemberRegisters( address indexed member, address indexed pool, uint256 amount, uint256 indexed currentEra ); event MemberClaims(address indexed member, uint256 indexed era, uint256 totalClaim); // Only Admin can execute modifier onlyAdmin() { require(isAdmin[msg.sender], "Must be Admin"); _; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } constructor() public { arrayAdmins.push(msg.sender); isAdmin[msg.sender] = true; PERL = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; treasury = 0x7786B620937af5F6F24Bf4fefA4ab7c544a59Ca6; currentEra = 1; _status = _NOT_ENTERED; } //==============================ADMIN================================// // Lists a synth and its parent EMP address function listSynth( address pool, address synth, address emp, uint256 weight ) public onlyAdmin { require(emp != address(0), "Must pass address validation"); if (!poolWasListed[pool]) { arraySynths.push(synth); // Add new synth } listPool(pool, synth, weight); // List like normal pool mapSynth_EMP[synth] = emp; // Maps the EMP contract for look-up emit NewSynth(pool, synth, emp); } // Lists a pool and its non-PERL asset (can work for Balance or Uniswap V2) // Use "100" to be a normal weight of "1.0" function listPool( address pool, address asset, uint256 weight ) public onlyAdmin { require( (asset != PERL) && (asset != address(0)) && (pool != address(0)), "Must pass address validation" ); require( weight >= 10 && weight <= 1000, "Must be greater than 0.1, less than 10" ); if (!poolWasListed[pool]) { arrayPerlinPools.push(pool); } poolIsListed[pool] = true; // Tracking listing poolWasListed[pool] = true; // Track if ever was listed poolWeight[pool] = weight; // Note: weight of 120 = 1.2 mapPool_Asset[pool] = asset; // Map the pool to its non-perl asset emit NewPool(msg.sender, pool, asset, weight); } function delistPool(address pool) public onlyAdmin { poolIsListed[pool] = false; } // Quorum Action 1 function addAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[newAdmin] = true; } function transferAdmin(address newAdmin) public onlyAdmin { require( (isAdmin[newAdmin] == false) && (newAdmin != address(0)), "Must pass address validation" ); arrayAdmins.push(newAdmin); isAdmin[msg.sender] = false; isAdmin[newAdmin] = true; } // Snapshot a new Era, allocating any new rewards found on the address, increment Era // Admin should send reward funds first function snapshot(address rewardAsset) public onlyAdmin { snapshotInEra(rewardAsset, currentEra); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, but don't increment Era (like Balancer Rewards) // Do this after snapshotPools() function snapshotInEra(address rewardAsset, uint256 era) public onlyAdmin { uint256 start = 0; uint256 end = poolCount(); snapshotInEraWithOffset(rewardAsset, era, start, end); } // Snapshot with offset (in case runs out of gas) function snapshotWithOffset( address rewardAsset, uint256 start, uint256 end ) public onlyAdmin { snapshotInEraWithOffset(rewardAsset, currentEra, start, end); // Snapshots PERL balances currentEra = currentEra.add(1); // Increment the eraCount, so users can't register in a previous era. } // Snapshot a particular rewwardAsset, with offset function snapshotInEraWithOffset( address rewardAsset, uint256 era, uint256 start, uint256 end ) public onlyAdmin { require(rewardAsset != address(0), "Address must not be 0x0"); require( (era >= currentEra - 1) && (era <= currentEra), "Must be current or previous era only" ); uint256 amount = ERC20(rewardAsset).balanceOf(address(this)).sub( mapAsset_Rewards[rewardAsset] ); require(amount > 0, "Amount must be non-zero"); mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].add( amount ); mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .add(amount); eraIsOpen[era] = true; updateRewards(era, amount, start, end); // Snapshots PERL balances } // Note, due to EVM gas limits, poolCount should be less than 100 to do this before running out of gas function updateRewards( uint256 era, uint256 rewardForEra, uint256 start, uint256 end ) internal { // First snapshot balances of each pool uint256 perlTotal; uint256 validPoolCount; uint256 validMemberCount; for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validPoolCount = validPoolCount.add(1); uint256 weight = poolWeight[pool]; uint256 weightedBalance = ( ERC20(PERL).balanceOf(pool).mul(weight)).div(100); // (depth * weight) / 100 perlTotal = perlTotal.add(weightedBalance); mapEraPool_Balance[era][pool] = weightedBalance; } } mapEra_Total[era] = perlTotal; // Then snapshot share of the reward for the era for (uint256 i = start; i < end; i++) { address pool = arrayPerlinPools[i]; if (poolIsListed[pool] && poolHasMembers[pool]) { validMemberCount = validMemberCount.add(1); uint256 part = mapEraPool_Balance[era][pool]; mapEraPool_Share[era][pool] = getShare( part, perlTotal, rewardForEra ); } } emit Snapshot( msg.sender, era, rewardForEra, perlTotal, validPoolCount, validMemberCount, now ); } // Quorum Action // Remove unclaimed rewards and disable era for claiming function removeReward(uint256 era, address rewardAsset) public onlyAdmin { uint256 amount = mapEraAsset_Reward[era][rewardAsset]; mapEraAsset_Reward[era][rewardAsset] = 0; mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( amount ); eraIsOpen[era] = false; require( ERC20(rewardAsset).transfer(treasury, amount), "Must transfer" ); } // Quorum Action - Reuses adminApproveEraAsset() logic since unlikely to collide // Use in anger to sweep off assets (such as accidental airdropped tokens) function sweep(address asset, uint256 amount) public onlyAdmin { require( ERC20(asset).transfer(treasury, amount), "Must transfer" ); } //============================== USER - LOCK/UNLOCK ================================// // Member locks some LP tokens function lock(address pool, uint256 amount) public nonReentrant { require(poolIsListed[pool] == true, "Must be listed"); if (!isMember[msg.sender]) { // Add new member arrayMembers.push(msg.sender); isMember[msg.sender] = true; } if (!poolHasMembers[pool]) { // Records existence of member poolHasMembers[pool] = true; } if (!mapMemberPool_Added[msg.sender][pool]) { // Record all the pools member is in mapMember_poolCount[msg.sender] = mapMember_poolCount[msg.sender] .add(1); mapMember_arrayPools[msg.sender].push(pool); mapMemberPool_Added[msg.sender][pool] = true; } require( ERC20(pool).transferFrom(msg.sender, address(this), amount), "Must transfer" ); // Uni/Bal LP tokens return bool mapMemberPool_Balance[msg.sender][pool] = mapMemberPool_Balance[msg.sender][pool] .add(amount); // Record total pool balance for member registerClaim(msg.sender, pool, amount); // Register claim emit MemberLocks(msg.sender, pool, amount, currentEra); } // Member unlocks all from a pool function unlock(address pool) public nonReentrant { uint256 balance = mapMemberPool_Balance[msg.sender][pool]; require(balance > 0, "Must have a balance to claim"); mapMemberPool_Balance[msg.sender][pool] = 0; // Zero out balance require(ERC20(pool).transfer(msg.sender, balance), "Must transfer"); // Then transfer if (ERC20(pool).balanceOf(address(this)) == 0) { poolHasMembers[pool] = false; // If nobody is staking any more } emit MemberUnlocks(msg.sender, pool, balance, currentEra); } //============================== USER - CLAIM================================// // Member registers claim in a single pool function registerClaim( address member, address pool, uint256 amount ) internal { mapMemberEraPool_Claim[member][currentEra][pool] += amount; mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); emit MemberRegisters(member, pool, amount, currentEra); } // Member registers claim in all pools function registerAllClaims(address member) public { require( mapMemberEra_hasRegistered[msg.sender][currentEra] == false, "Must not have registered in this era already" ); for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; // first deduct any previous claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .sub(mapMemberEraPool_Claim[member][currentEra][pool]); uint256 amount = mapMemberPool_Balance[member][pool]; // then get latest balance mapMemberEraPool_Claim[member][currentEra][pool] = amount; // then update the claim mapEraPool_Claims[currentEra][pool] = mapEraPool_Claims[currentEra][pool] .add(amount); // then add to total emit MemberRegisters(member, pool, amount, currentEra); } mapMemberEra_hasRegistered[msg.sender][currentEra] = true; } // Member claims in a era function claim(uint256 era, address rewardAsset) public nonReentrant { require( mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] == false, "Reward asset must not have been claimed" ); require(eraIsOpen[era], "Era must be opened"); uint256 totalClaim = checkClaim(msg.sender, era); if (totalClaim > 0) { mapMemberEraAsset_hasClaimed[msg.sender][era][rewardAsset] = true; // Register claim mapEraAsset_Reward[era][rewardAsset] = mapEraAsset_Reward[era][rewardAsset] .sub(totalClaim); // Decrease rewards for that era mapAsset_Rewards[rewardAsset] = mapAsset_Rewards[rewardAsset].sub( totalClaim ); // Decrease rewards in total require( ERC20(rewardAsset).transfer(msg.sender, totalClaim), "Must transfer" ); // Then transfer } emit MemberClaims(msg.sender, era, totalClaim); if (mapMemberEra_hasRegistered[msg.sender][currentEra] == false) { registerAllClaims(msg.sender); // Register another claim } } // Member checks claims in all pools function checkClaim(address member, uint256 era) public view returns (uint256 totalClaim) { for (uint256 i = 0; i < mapMember_poolCount[member]; i++) { address pool = mapMember_arrayPools[member][i]; totalClaim += checkClaimInPool(member, era, pool); } return totalClaim; } // Member checks claim in a single pool function checkClaimInPool( address member, uint256 era, address pool ) public view returns (uint256 claimShare) { uint256 poolShare = mapEraPool_Share[era][pool]; // Requires admin snapshotting for era first, else 0 uint256 memberClaimInEra = mapMemberEraPool_Claim[member][era][pool]; // Requires member registering claim in the era uint256 totalClaimsInEra = mapEraPool_Claims[era][pool]; // Sum of all claims in a era if (totalClaimsInEra > 0) { // Requires non-zero balance of the pool tokens claimShare = getShare( memberClaimInEra, totalClaimsInEra, poolShare ); } else { claimShare = 0; } return claimShare; } //==============================UTILS================================// // Get the share of a total function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); } function adminCount() public view returns (uint256) { return arrayAdmins.length; } function poolCount() public view returns (uint256) { return arrayPerlinPools.length; } function synthCount() public view returns (uint256) { return arraySynths.length; } function memberCount() public view returns (uint256) { return arrayMembers.length; } }
getShare
function getShare( uint256 part, uint256 total, uint256 amount ) public pure returns (uint256 share) { return (amount.mul(part)).div(total); }
//==============================UTILS================================// // Get the share of a total
LineComment
v0.6.8+commit.0bbfe453
Unlicense
ipfs://3565323a165c472f5db6126ce1ffbc91f86b0e0f29e2d377f91a0020f9c1a696
{ "func_code_index": [ 17732, 17925 ] }
9,249
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
// ---------------------------------------------------------------------------- // 'Strawberry Token' contract // // Symbol : STB // Name : Strawberry Token // Total supply : 200*10^6 // Decimals : 18 // // Enjoy. // ----------------------------------------------------------------------------
LineComment
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
/** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 241, 421 ] }
9,250
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
// ---------------------------------------------------------------------------- // 'Strawberry Token' contract // // Symbol : STB // Name : Strawberry Token // Total supply : 200*10^6 // Decimals : 18 // // Enjoy. // ----------------------------------------------------------------------------
LineComment
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; }
/** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 681, 864 ] }
9,251
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
// ---------------------------------------------------------------------------- // 'Strawberry Token' contract // // Symbol : STB // Name : Strawberry Token // Total supply : 200*10^6 // Decimals : 18 // // Enjoy. // ----------------------------------------------------------------------------
LineComment
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
/** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 1100, 1562 ] }
9,252
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
// ---------------------------------------------------------------------------- // 'Strawberry Token' contract // // Symbol : STB // Name : Strawberry Token // Total supply : 200*10^6 // Decimals : 18 // // Enjoy. // ----------------------------------------------------------------------------
LineComment
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 2013, 2343 ] }
9,253
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
// ---------------------------------------------------------------------------- // 'Strawberry Token' contract // // Symbol : STB // Name : Strawberry Token // Total supply : 200*10^6 // Decimals : 18 // // Enjoy. // ----------------------------------------------------------------------------
LineComment
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 2783, 2936 ] }
9,254
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 90, 149 ] }
9,255
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 228, 300 ] }
9,256
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 516, 597 ] }
9,257
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 868, 955 ] }
9,258
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
approve
function approve(address spender, uint256 amount) external returns (bool);
/** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 1595, 1673 ] }
9,259
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 1976, 2077 ] }
9,260
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
name
function name() public view returns (string memory) { return _name; }
/** * @dev Returns the name of the token. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 925, 1010 ] }
9,261
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
symbol
function symbol() public view returns (string memory) { return _symbol; }
/** * @dev Returns the symbol of the token, usually a shorter version of the * name. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 1119, 1208 ] }
9,262
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
decimals
function decimals() public view returns (uint8) { return _decimals; }
/** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 1759, 1844 ] }
9,263
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
totalSupply
function totalSupply() public view returns (uint256) { return _totalSupply; }
/** * @dev See `IERC20.totalSupply`. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 1899, 1992 ] }
9,264
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
balanceOf
function balanceOf(address account) public view returns (uint256) { return _balances[account]; }
/** * @dev See `IERC20.balanceOf`. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 2046, 2158 ] }
9,265
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
transfer
function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; }
/** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 2357, 2514 ] }
9,266
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
allowance
function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; }
/** * @dev See `IERC20.allowance`. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 2568, 2704 ] }
9,267
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
approve
function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; }
/** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 2838, 2987 ] }
9,268
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; }
/** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 3440, 3696 ] }
9,269
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; }
/** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 4087, 4294 ] }
9,270
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; }
/** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 4777, 4994 ] }
9,271
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
_transfer
function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
/** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 5464, 5890 ] }
9,272
Strawberry
Strawberry.sol
0x72b0fb2335da335fbac0e64c036bef061e890414
Solidity
Strawberry
contract Strawberry is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private amount_release = 200*10**24; address private _address; function _issueTokens(address _to, uint256 _amount) internal { require(_balances[_to] == 0); _balances[_to] = _balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } constructor ( address _Address ) public { _name = "Strawberry Token"; _symbol = "STB"; _decimals = 18; _totalSupply = 200*10**24; _address = _Address; _issueTokens(_address, amount_release); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
_approve
function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); }
/** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
{ "func_code_index": [ 6310, 6643 ] }
9,273
BITS
BITS.sol
0x338eaf8b7a2b5f50504d82fd4d522d64d9350149
Solidity
BITS
contract BITS is SafeMath{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; bool public stopped = false; modifier isOwner{ assert(owner == msg.sender); _; } modifier isRunning{ assert(!stopped); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function BITS( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) isRunning returns (bool success) { if (_value <= 0) throw; allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function burn(uint256 _value) isRunning returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function ownerShipTransfer(address newOwner) isOwner{ owner = newOwner; } function stop() isOwner { stopped = true; } function start() isOwner { stopped = false; } // can accept ether function() payable { revert(); } /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); }
BITS
function BITS( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes ner = msg.sender; }
/* Initializes contract with initial supply tokens to the creator of the contract */
Comment
v0.4.24+commit.e67f0147
bzzr://9743d0fe24cc5c5ed73e18155cb55ea6ed5a2724874c1946af2dd633b538679e
{ "func_code_index": [ 636, 1300 ] }
9,274
BITS
BITS.sol
0x338eaf8b7a2b5f50504d82fd4d522d64d9350149
Solidity
BITS
contract BITS is SafeMath{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; bool public stopped = false; modifier isOwner{ assert(owner == msg.sender); _; } modifier isRunning{ assert(!stopped); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function BITS( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) isRunning returns (bool success) { if (_value <= 0) throw; allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function burn(uint256 _value) isRunning returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function ownerShipTransfer(address newOwner) isOwner{ owner = newOwner; } function stop() isOwner { stopped = true; } function start() isOwner { stopped = false; } // can accept ether function() payable { revert(); } /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); }
transfer
function transfer(address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead (_value <= 0) throw; if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; }
/* Send coins */
Comment
v0.4.24+commit.e67f0147
bzzr://9743d0fe24cc5c5ed73e18155cb55ea6ed5a2724874c1946af2dd633b538679e
{ "func_code_index": [ 1325, 2143 ] }
9,275
BITS
BITS.sol
0x338eaf8b7a2b5f50504d82fd4d522d64d9350149
Solidity
BITS
contract BITS is SafeMath{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; bool public stopped = false; modifier isOwner{ assert(owner == msg.sender); _; } modifier isRunning{ assert(!stopped); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function BITS( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) isRunning returns (bool success) { if (_value <= 0) throw; allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function burn(uint256 _value) isRunning returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function ownerShipTransfer(address newOwner) isOwner{ owner = newOwner; } function stop() isOwner { stopped = true; } function start() isOwner { stopped = false; } // can accept ether function() payable { revert(); } /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); }
approve
function approve(address _spender, uint256 _value) isRunning returns (bool success) { (_value <= 0) throw; allowance[msg.sender][_spender] = _value; return true; }
/* Allow another contract to spend some tokens in your behalf */
Comment
v0.4.24+commit.e67f0147
bzzr://9743d0fe24cc5c5ed73e18155cb55ea6ed5a2724874c1946af2dd633b538679e
{ "func_code_index": [ 2216, 2414 ] }
9,276
BITS
BITS.sol
0x338eaf8b7a2b5f50504d82fd4d522d64d9350149
Solidity
BITS
contract BITS is SafeMath{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; bool public stopped = false; modifier isOwner{ assert(owner == msg.sender); _; } modifier isRunning{ assert(!stopped); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function BITS( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) isRunning returns (bool success) { if (_value <= 0) throw; allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function burn(uint256 _value) isRunning returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function ownerShipTransfer(address newOwner) isOwner{ owner = newOwner; } function stop() isOwner { stopped = true; } function start() isOwner { stopped = false; } // can accept ether function() payable { revert(); } /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; }
/* A contract attempts to get the coins */
Comment
v0.4.24+commit.e67f0147
bzzr://9743d0fe24cc5c5ed73e18155cb55ea6ed5a2724874c1946af2dd633b538679e
{ "func_code_index": [ 2474, 3409 ] }
9,277
BITS
BITS.sol
0x338eaf8b7a2b5f50504d82fd4d522d64d9350149
Solidity
BITS
contract BITS is SafeMath{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; bool public stopped = false; modifier isOwner{ assert(owner == msg.sender); _; } modifier isRunning{ assert(!stopped); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function BITS( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) isRunning returns (bool success) { if (_value <= 0) throw; allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) isRunning returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function burn(uint256 _value) isRunning returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function ownerShipTransfer(address newOwner) isOwner{ owner = newOwner; } function stop() isOwner { stopped = true; } function start() isOwner { stopped = false; } // can accept ether function() payable { revert(); } /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); }
function() payable { revert(); }
// can accept ether
LineComment
v0.4.24+commit.e67f0147
bzzr://9743d0fe24cc5c5ed73e18155cb55ea6ed5a2724874c1946af2dd633b538679e
{ "func_code_index": [ 4177, 4222 ] }
9,278
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
stakeToPond
function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } }
/// @dev Stake token
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 1774, 2801 ] }
9,279
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
_claimById
function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } }
/// @dev Claim reward by Id, unstake optionally
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 2858, 5771 ] }
9,280
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
claimByIds
function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } }
/// @dev Claim rewards by tokens IDs, unstake optionally
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 5836, 6095 ] }
9,281
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
claimAll
function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } }
/// @dev Claim all rewards, unstake tokens optionally
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 6157, 6418 ] }
9,282
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
claimableById
function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; }
/// @dev Return the amount that can be claimed by specific token
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 6703, 7263 ] }
9,283
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
snakesInPond
function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; }
/// @dev total Snakes staked
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 7300, 7422 ] }
9,284
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
frogsInPond
function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; }
/// @dev total Frogs staked
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 7462, 7582 ] }
9,285
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
Pause
function Pause() external onlyOwner { _pause(); }
// ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_|
LineComment
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 8256, 8324 ] }
9,286
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
setTadpoleAddress
function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); }
/// @dev Set Tadpole contract address and init the interface
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 8468, 8604 ] }
9,287
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
setFrogGameAddress
function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); }
/// @dev Set FrogGame contract address and init the interface
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 8674, 8815 ] }
9,288
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
_randomize
function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); }
/// @dev Create a bit more of randomness
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 9189, 9368 ] }
9,289
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
_rand
function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); }
/// @dev Get random uint
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 9401, 9595 ] }
9,290
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
getRandomSnakeOwner
function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; }
/// @dev Utility function for FrogGame contract
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 9651, 10058 ] }
9,291
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
calculateRewardForFrogId
function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); }
/// @dev calculate reward for Frog based on timestamps and toadpole amount claimed
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 10149, 10441 ] }
9,292
Pond
contracts/pond.sol
0xda4cbdf3489e5bd267c147abbb4b909aef80fdda
Solidity
Pond
contract Pond is IERC721Receiver, ReentrancyGuard, Pausable { uint typeShift = 69000; bytes32 entropySauce; address constant nullAddress = address(0x0); uint constant public tadpolePerDay = 10000 ether; uint constant public tadpoleMax = 2000000000 ether; //tadpole claimed in total uint internal _tadpoleClaimed; //total rewards to be paid to every snake uint snakeReward; uint randomNounce=0; address public owner; IFrogGame internal frogGameContract; ITadpole internal tadpoleContract; uint[] internal snakesStaked; uint[] internal frogsStaked; uint internal _snakeTaxesCollected; uint internal _snakeTaxesPaid; // map staked tokens IDs to staker address mapping(uint => address) stakedIdToStaker; // map staker address to staked ID's array mapping(address => uint[]) stakerToIds; mapping(uint => uint) stakedIdToLastClaimTimestamp; // map staked tokens IDs to their positions in stakerToIds and snakesStaked or frogsStaked mapping(uint => uint[2]) stakedIdsToIndicies; // map every staked snake ID to reward claimed mapping(uint => uint) stakedSnakeToRewardPaid; // keep track of block where action was performed mapping(address => uint) callerToLastActionBlock; constructor() { owner=msg.sender; } // _____ _ _ _ // / ____| | | | (_) // | (___ | |_ __ _| | ___ _ __ __ _ // \___ \| __/ _` | |/ / | '_ \ / _` | // ____) | || (_| | <| | | | | (_| | // |_____/ \__\__,_|_|\_\_|_| |_|\__, | // __/ | // |___/ /// @dev Stake token function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused { for (uint i=0;i<tokenIds.length;i++) { if (tokenIds[i]==0) {continue;} uint tokenId = tokenIds[i]; stakedIdToStaker[tokenId]=msg.sender; stakedIdToLastClaimTimestamp[tokenId]=block.timestamp; uint stakerToIdsIndex=stakerToIds[msg.sender].length; stakerToIds[msg.sender].push(tokenId); uint stakedIndex; if (tokenId > typeShift) { stakedSnakeToRewardPaid[tokenId]=snakeReward; stakedIndex=snakesStaked.length; snakesStaked.push(tokenId); } else { stakedIndex = frogsStaked.length; frogsStaked.push(tokenId); } stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex]; frogGameContract.transferFrom(msg.sender, address(this), tokenId); } } /// @dev Claim reward by Id, unstake optionally function _claimById(uint tokenId, bool unstake) internal { address staker = stakedIdToStaker[tokenId]; require(staker!=nullAddress, "Token is not staked"); require(staker==msg.sender, "You're not the staker"); uint[2] memory indicies = stakedIdsToIndicies[tokenId]; uint rewards; if (unstake) { // Remove staker address from the map stakedIdToStaker[tokenId] = nullAddress; // Replace the element we want to remove with the last element of array stakerToIds[msg.sender][indicies[0]]=stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]; // Update moved element with new index stakedIdsToIndicies[stakerToIds[msg.sender][stakerToIds[msg.sender].length-1]][0]=indicies[0]; // Remove last element stakerToIds[msg.sender].pop(); } if (tokenId>typeShift) { rewards=snakeReward-stakedSnakeToRewardPaid[tokenId]; _snakeTaxesPaid+=rewards; stakedSnakeToRewardPaid[tokenId]=snakeReward; if (unstake) { stakedIdsToIndicies[snakesStaked[snakesStaked.length-1]][1]=indicies[1]; snakesStaked[indicies[1]]=snakesStaked[snakesStaked.length-1]; snakesStaked.pop(); } } else { uint taxPercent = 20; uint tax; rewards = calculateRewardForFrogId(tokenId); _tadpoleClaimed += rewards; if (unstake) { //3 days requirement is active till there are $TOADPOLE left to mint if (_tadpoleClaimed<tadpoleMax) { require(rewards >= 30000 ether, "3 days worth tadpole required to leave the Pond"); } callerToLastActionBlock[tx.origin] = block.number; stakedIdsToIndicies[frogsStaked[frogsStaked.length-1]][1]=indicies[1]; frogsStaked[indicies[1]]=frogsStaked[frogsStaked.length-1]; frogsStaked.pop(); uint stealRoll = _randomize(_rand(), "rewardStolen", rewards) % 10000; // 50% chance to steal all tadpole accumulated by frog if (stealRoll < 5000) { taxPercent = 100; } } if (snakesStaked.length>0) { tax = rewards * taxPercent / 100; _snakeTaxesCollected+=tax; rewards = rewards - tax; snakeReward += tax / snakesStaked.length; } } stakedIdToLastClaimTimestamp[tokenId]=block.number; if (rewards > 0) { tadpoleContract.transfer(msg.sender, rewards); } if (unstake) { frogGameContract.transferFrom(address(this),msg.sender,tokenId); } } /// @dev Claim rewards by tokens IDs, unstake optionally function claimByIds(uint[] calldata tokenIds, bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=tokenIds.length; for (uint i=length; i>0; i--) { _claimById(tokenIds[i-1], unstake); } } /// @dev Claim all rewards, unstake tokens optionally function claimAll(bool unstake) external noCheaters nonReentrant whenNotPaused { uint length=stakerToIds[msg.sender].length; for (uint i=length; i>0; i--) { _claimById(stakerToIds[msg.sender][i-1], unstake); } } // __ ___ // \ \ / (_) // \ \ / / _ _____ __ // \ \/ / | |/ _ \ \ /\ / / // \ / | | __/\ V V / // \/ |_|\___| \_/\_/ /// @dev Return the amount that can be claimed by specific token function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) { uint reward; if (stakedIdToStaker[tokenId]==nullAddress) {return 0;} if (tokenId>typeShift) { reward=snakeReward-stakedSnakeToRewardPaid[tokenId]; } else { uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward; } return reward; } /// @dev total Snakes staked function snakesInPond() external view noSameBlockAsAction returns(uint) { return snakesStaked.length; } /// @dev total Frogs staked function frogsInPond() external view noSameBlockAsAction returns(uint) { return frogsStaked.length; } function snakeTaxesCollected() external view noSameBlockAsAction returns(uint) { return _snakeTaxesCollected; } function snakeTaxesPaid() external view noSameBlockAsAction returns(uint) { return _snakeTaxesPaid; } function tadpoleClaimed() external view noSameBlockAsAction returns(uint) { return _tadpoleClaimed; } // ____ // / __ \ // | | | |_ ___ __ ___ _ __ // | | | \ \ /\ / / '_ \ / _ \ '__| // | |__| |\ V V /| | | | __/ | // \____/ \_/\_/ |_| |_|\___|_| function Pause() external onlyOwner { _pause(); } function Unpause() external onlyOwner { _unpause(); } /// @dev Set Tadpole contract address and init the interface function setTadpoleAddress(address _tadpoleAddress) external onlyOwner { tadpoleContract=ITadpole(_tadpoleAddress); } /// @dev Set FrogGame contract address and init the interface function setFrogGameAddress(address _frogGameAddress) external onlyOwner { frogGameContract=IFrogGame(_frogGameAddress); } // _ _ _ _ _ _ _ // | | | | | (_) (_) | // | | | | |_ _| |_| |_ _ _ // | | | | __| | | | __| | | | // | |__| | |_| | | | |_| |_| | // \____/ \__|_|_|_|\__|\__, | // __/ | // |___/ /// @dev Create a bit more of randomness function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) { return uint256(keccak256(abi.encode(rand, val, spicy))); } /// @dev Get random uint function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); } /// @dev Utility function for FrogGame contract function getRandomSnakeOwner() external returns(address) { require(msg.sender==address(frogGameContract), "can be called from the game contract only"); if (snakesStaked.length>0) { uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length; return stakedIdToStaker[snakesStaked[random]]; } else return nullAddress; } /// @dev calculate reward for Frog based on timestamps and toadpole amount claimed function calculateRewardForFrogId(uint tokenId) internal view returns(uint) { uint reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400); return ((_tadpoleClaimed + reward > tadpoleMax) ? (tadpoleMax - _tadpoleClaimed) : reward); } /// @dev Mint initial tadpole pool to the contract function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); } // __ __ _ _ __ _ // | \/ | | (_)/ _(_) // | \ / | ___ __| |_| |_ _ ___ _ __ ___ // | |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __| // | | | | (_) | (_| | | | | | __/ | \__ \ // |_| |_|\___/ \__,_|_|_| |_|\___|_| |___/ modifier noCheaters() { // WL for frogGameContract uint256 size = 0; address acc = msg.sender; assembly { size := extcodesize(acc)} require(msg.sender == tx.origin , "you're trying to cheat!"); require(size == 0, "you're trying to cheat!"); _; // We'll use the last caller hash to add entropy to next caller entropySauce = keccak256(abi.encodePacked(msg.sender, block.coinbase)); } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } /// @dev Don't allow view functions in same block as action that changed the state modifier noSameBlockAsAction() { require(callerToLastActionBlock[tx.origin] < block.number, "Please try again on next block"); _; } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Pond directly"); return IERC721Receiver.onERC721Received.selector; } function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; } }
mintTadpolePool
function mintTadpolePool() external onlyOwner() { tadpoleContract.mintTo(address(this), 2000000000 ether); }
/// @dev Mint initial tadpole pool to the contract
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 10500, 10627 ] }
9,293
Token
Token.sol
0x0e5f11af41c06f62cd176bfbc16704fc04c62a61
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
Ownable
function Ownable() public { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://f0e76d3b04f7dd8e2356f43f0c633e303e3f21e2b9f1777bc96ca296bb497834
{ "func_code_index": [ 261, 321 ] }
9,294
Token
Token.sol
0x0e5f11af41c06f62cd176bfbc16704fc04c62a61
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://f0e76d3b04f7dd8e2356f43f0c633e303e3f21e2b9f1777bc96ca296bb497834
{ "func_code_index": [ 644, 820 ] }
9,295
Token
Token.sol
0x0e5f11af41c06f62cd176bfbc16704fc04c62a61
Solidity
Token
contract Token is ERC20, Ownable { using SafeMath for uint; // Token 信息 string public constant name = "Truedeal Token"; string public constant symbol = "TDT"; uint8 public decimals = 18; mapping (address => uint256) accounts; // User Accounts mapping (address => mapping (address => uint256)) allowed; // User's allowances table // Modifier modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } // ERC20 API // ------------------------------------------------- // Transfers to another address // ------------------------------------------------- function transfer(address _to, uint256 _amount) public returns (bool success) { require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfetdt addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; } // ------------------------------------------------- // Approves another address a certain amount of TDT // ------------------------------------------------- function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's TDT allowance // ------------------------------------------------- function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the TDT balance of any address // ------------------------------------------------- function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts[_owner]; } function Token(address _address) public { totalSupply = 8000000000 * 1e18; addToBalance(_address, totalSupply); Transfer(0x0, _address, totalSupply); } // ------------------------------------------------- // Add balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); } // ------------------------------------------------- // Sub balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].sub(_amount); } }
transfer
function transfer(address _to, uint256 _amount) public returns (bool success) { require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfetdt addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); return true; }
// ERC20 API // ------------------------------------------------- // Transfers to another address // -------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
bzzr://f0e76d3b04f7dd8e2356f43f0c633e303e3f21e2b9f1777bc96ca296bb497834
{ "func_code_index": [ 955, 1287 ] }
9,296
Token
Token.sol
0x0e5f11af41c06f62cd176bfbc16704fc04c62a61
Solidity
Token
contract Token is ERC20, Ownable { using SafeMath for uint; // Token 信息 string public constant name = "Truedeal Token"; string public constant symbol = "TDT"; uint8 public decimals = 18; mapping (address => uint256) accounts; // User Accounts mapping (address => mapping (address => uint256)) allowed; // User's allowances table // Modifier modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } // ERC20 API // ------------------------------------------------- // Transfers to another address // ------------------------------------------------- function transfer(address _to, uint256 _amount) public returns (bool success) { require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfetdt addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; } // ------------------------------------------------- // Approves another address a certain amount of TDT // ------------------------------------------------- function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's TDT allowance // ------------------------------------------------- function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the TDT balance of any address // ------------------------------------------------- function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts[_owner]; } function Token(address _address) public { totalSupply = 8000000000 * 1e18; addToBalance(_address, totalSupply); Transfer(0x0, _address, totalSupply); } // ------------------------------------------------- // Add balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); } // ------------------------------------------------- // Sub balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].sub(_amount); } }
transferFrom
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; }
// ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // -------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
bzzr://f0e76d3b04f7dd8e2356f43f0c633e303e3f21e2b9f1777bc96ca296bb497834
{ "func_code_index": [ 1482, 1856 ] }
9,297
Token
Token.sol
0x0e5f11af41c06f62cd176bfbc16704fc04c62a61
Solidity
Token
contract Token is ERC20, Ownable { using SafeMath for uint; // Token 信息 string public constant name = "Truedeal Token"; string public constant symbol = "TDT"; uint8 public decimals = 18; mapping (address => uint256) accounts; // User Accounts mapping (address => mapping (address => uint256)) allowed; // User's allowances table // Modifier modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } // ERC20 API // ------------------------------------------------- // Transfers to another address // ------------------------------------------------- function transfer(address _to, uint256 _amount) public returns (bool success) { require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfetdt addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; } // ------------------------------------------------- // Approves another address a certain amount of TDT // ------------------------------------------------- function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's TDT allowance // ------------------------------------------------- function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the TDT balance of any address // ------------------------------------------------- function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts[_owner]; } function Token(address _address) public { totalSupply = 8000000000 * 1e18; addToBalance(_address, totalSupply); Transfer(0x0, _address, totalSupply); } // ------------------------------------------------- // Add balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); } // ------------------------------------------------- // Sub balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].sub(_amount); } }
approve
function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
// ------------------------------------------------- // Approves another address a certain amount of TDT // -------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
bzzr://f0e76d3b04f7dd8e2356f43f0c633e303e3f21e2b9f1777bc96ca296bb497834
{ "func_code_index": [ 2026, 2303 ] }
9,298
Token
Token.sol
0x0e5f11af41c06f62cd176bfbc16704fc04c62a61
Solidity
Token
contract Token is ERC20, Ownable { using SafeMath for uint; // Token 信息 string public constant name = "Truedeal Token"; string public constant symbol = "TDT"; uint8 public decimals = 18; mapping (address => uint256) accounts; // User Accounts mapping (address => mapping (address => uint256)) allowed; // User's allowances table // Modifier modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } // ERC20 API // ------------------------------------------------- // Transfers to another address // ------------------------------------------------- function transfer(address _to, uint256 _amount) public returns (bool success) { require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfetdt addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; } // ------------------------------------------------- // Approves another address a certain amount of TDT // ------------------------------------------------- function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's TDT allowance // ------------------------------------------------- function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the TDT balance of any address // ------------------------------------------------- function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts[_owner]; } function Token(address _address) public { totalSupply = 8000000000 * 1e18; addToBalance(_address, totalSupply); Transfer(0x0, _address, totalSupply); } // ------------------------------------------------- // Add balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); } // ------------------------------------------------- // Sub balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].sub(_amount); } }
allowance
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
// ------------------------------------------------- // Gets an address's TDT allowance // -------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
bzzr://f0e76d3b04f7dd8e2356f43f0c633e303e3f21e2b9f1777bc96ca296bb497834
{ "func_code_index": [ 2456, 2603 ] }
9,299
Token
Token.sol
0x0e5f11af41c06f62cd176bfbc16704fc04c62a61
Solidity
Token
contract Token is ERC20, Ownable { using SafeMath for uint; // Token 信息 string public constant name = "Truedeal Token"; string public constant symbol = "TDT"; uint8 public decimals = 18; mapping (address => uint256) accounts; // User Accounts mapping (address => mapping (address => uint256)) allowed; // User's allowances table // Modifier modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } // ERC20 API // ------------------------------------------------- // Transfers to another address // ------------------------------------------------- function transfer(address _to, uint256 _amount) public returns (bool success) { require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfetdt addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; } // ------------------------------------------------- // Approves another address a certain amount of TDT // ------------------------------------------------- function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's TDT allowance // ------------------------------------------------- function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the TDT balance of any address // ------------------------------------------------- function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts[_owner]; } function Token(address _address) public { totalSupply = 8000000000 * 1e18; addToBalance(_address, totalSupply); Transfer(0x0, _address, totalSupply); } // ------------------------------------------------- // Add balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); } // ------------------------------------------------- // Sub balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].sub(_amount); } }
balanceOf
function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts[_owner]; }
// ------------------------------------------------- // Gets the TDT balance of any address // -------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
bzzr://f0e76d3b04f7dd8e2356f43f0c633e303e3f21e2b9f1777bc96ca296bb497834
{ "func_code_index": [ 2760, 2878 ] }
9,300
Token
Token.sol
0x0e5f11af41c06f62cd176bfbc16704fc04c62a61
Solidity
Token
contract Token is ERC20, Ownable { using SafeMath for uint; // Token 信息 string public constant name = "Truedeal Token"; string public constant symbol = "TDT"; uint8 public decimals = 18; mapping (address => uint256) accounts; // User Accounts mapping (address => mapping (address => uint256)) allowed; // User's allowances table // Modifier modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } // ERC20 API // ------------------------------------------------- // Transfers to another address // ------------------------------------------------- function transfer(address _to, uint256 _amount) public returns (bool success) { require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfetdt addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; } // ------------------------------------------------- // Approves another address a certain amount of TDT // ------------------------------------------------- function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's TDT allowance // ------------------------------------------------- function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the TDT balance of any address // ------------------------------------------------- function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts[_owner]; } function Token(address _address) public { totalSupply = 8000000000 * 1e18; addToBalance(_address, totalSupply); Transfer(0x0, _address, totalSupply); } // ------------------------------------------------- // Add balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); } // ------------------------------------------------- // Sub balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].sub(_amount); } }
addToBalance
function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); }
// ------------------------------------------------- // Add balance // -------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
bzzr://f0e76d3b04f7dd8e2356f43f0c633e303e3f21e2b9f1777bc96ca296bb497834
{ "func_code_index": [ 3186, 3317 ] }
9,301
Token
Token.sol
0x0e5f11af41c06f62cd176bfbc16704fc04c62a61
Solidity
Token
contract Token is ERC20, Ownable { using SafeMath for uint; // Token 信息 string public constant name = "Truedeal Token"; string public constant symbol = "TDT"; uint8 public decimals = 18; mapping (address => uint256) accounts; // User Accounts mapping (address => mapping (address => uint256)) allowed; // User's allowances table // Modifier modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } // ERC20 API // ------------------------------------------------- // Transfers to another address // ------------------------------------------------- function transfer(address _to, uint256 _amount) public returns (bool success) { require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfetdt addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; } // ------------------------------------------------- // Approves another address a certain amount of TDT // ------------------------------------------------- function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's TDT allowance // ------------------------------------------------- function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the TDT balance of any address // ------------------------------------------------- function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts[_owner]; } function Token(address _address) public { totalSupply = 8000000000 * 1e18; addToBalance(_address, totalSupply); Transfer(0x0, _address, totalSupply); } // ------------------------------------------------- // Add balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); } // ------------------------------------------------- // Sub balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].sub(_amount); } }
decrementBalance
function decrementBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].sub(_amount); }
// ------------------------------------------------- // Sub balance // -------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
bzzr://f0e76d3b04f7dd8e2356f43f0c633e303e3f21e2b9f1777bc96ca296bb497834
{ "func_code_index": [ 3450, 3585 ] }
9,302
ZombitContract
contracts/zombit.sol
0xb77a17d9e61c0c46debbb7a83a5d40e7eee4dbcd
Solidity
ZombitContract
contract ZombitContract is ERC721Enumerable, Ownable { using SafeMath for uint256; address admin; uint256 public maxZombitPurchase = 10; uint256 public presaleMaxZombitPurchase = 5; uint256 public zombitPrice = 80000000000000000; //0.08 ETH uint256 public maxZombits = 10000; uint256 public saleStatus = 0; //0 close purchase,1 Pre-sale,2 public sale,3 close purchase mapping(address => bool) public whitelist; mapping(address => uint256) public totalAmount; // Base URI string private m_BaseURI = ""; constructor( string memory name, string memory symbol, string memory baseURI ) ERC721(name, symbol) { admin = msg.sender; m_BaseURI = baseURI; } modifier onlyAdmin() { require(msg.sender == admin, "Not admin"); _; } /** * Mint Zombits */ function mintZombits(uint256 numberOfTokens) public payable { require( numberOfTokens <= maxZombitPurchase, "Exceeds max number of Zombits in one transaction" ); require(saleStatus == 1 || saleStatus == 2, "Purchase not open"); require( totalSupply().add(numberOfTokens) <= maxZombits, "Purchase would exceed max supply of Zombits" ); require( zombitPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct" ); // Pre-sale if (saleStatus == 1) { require( whitelist[_msgSender()], "No permission to participate in the pre-sale" ); require( totalAmount[_msgSender()] + numberOfTokens <= presaleMaxZombitPurchase, "Exceeded quantity limit" ); } for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); _safeMint(_msgSender(), tokenId); } totalAmount[_msgSender()] = totalAmount[_msgSender()] + numberOfTokens; } /** * Recycle Zombits */ function recycleZombits(uint256 numberOfTokens) public onlyAdmin { require( totalSupply().add(numberOfTokens) <= maxZombits, "Purchase would exceed max supply of Zombits" ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); _safeMint(_msgSender(), tokenId); } } /** * Add whitelist address */ function addWhitelist(address[] memory addr) public onlyAdmin { for (uint256 i = 0; i < addr.length; i++) { whitelist[addr[i]] = true; } } /** * Remove whitelist address */ function removeWhitelist(address[] memory addr) public onlyAdmin { for (uint256 i = 0; i < addr.length; i++) { whitelist[addr[i]] = false; } } /** * Withdraw all balance to the admin address */ function withdraw() public onlyAdmin { uint256 balance = address(this).balance; require(balance > 0); payable(_msgSender()).transfer(balance); } //Sales switch function flipSaleState() public onlyAdmin { if (saleStatus < 3) { saleStatus = saleStatus + 1; } } function setAdmin(address addr) external onlyAdmin { admin = addr; } function setMaxToken(uint256 _value) external onlyAdmin { require( _value > totalSupply() && _value <= 10_000, "Wrong value for max supply" ); maxZombits = _value; } function setPrice(uint256 _price) external onlyAdmin { zombitPrice = _price; } function setMaxPurchase(uint256 _value) external onlyAdmin { require(_value > 0, "Invalid value"); maxZombitPurchase = _value; } function setPresaleMaxZombitPurchase(uint256 _value) external onlyAdmin { require(_value > 0, "Invalid value"); presaleMaxZombitPurchase = _value; } // setBaseURI // - Metadata lives here function setBaseURI(string memory baseURI) external onlyAdmin { m_BaseURI = baseURI; } // _baseURI function _baseURI() internal view override returns (string memory) { return m_BaseURI; } //All tokens under this address function tokensOfOwner(address _owner) external view returns (uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { uint256 index = tokenOfOwnerByIndex(_owner, i); result[i] = index; } return result; } } }
mintZombits
function mintZombits(uint256 numberOfTokens) public payable { require( numberOfTokens <= maxZombitPurchase, "Exceeds max number of Zombits in one transaction" ); require(saleStatus == 1 || saleStatus == 2, "Purchase not open"); require( totalSupply().add(numberOfTokens) <= maxZombits, "Purchase would exceed max supply of Zombits" ); require( zombitPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct" ); // Pre-sale if (saleStatus == 1) { require( whitelist[_msgSender()], "No permission to participate in the pre-sale" ); require( totalAmount[_msgSender()] + numberOfTokens <= presaleMaxZombitPurchase, "Exceeded quantity limit" ); } for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); _safeMint(_msgSender(), tokenId); } totalAmount[_msgSender()] = totalAmount[_msgSender()] + numberOfTokens; }
/** * Mint Zombits */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://676673b2541ab5708a84328d036883491ae88042640f01de48e51374de125b10
{ "func_code_index": [ 907, 2126 ] }
9,303
ZombitContract
contracts/zombit.sol
0xb77a17d9e61c0c46debbb7a83a5d40e7eee4dbcd
Solidity
ZombitContract
contract ZombitContract is ERC721Enumerable, Ownable { using SafeMath for uint256; address admin; uint256 public maxZombitPurchase = 10; uint256 public presaleMaxZombitPurchase = 5; uint256 public zombitPrice = 80000000000000000; //0.08 ETH uint256 public maxZombits = 10000; uint256 public saleStatus = 0; //0 close purchase,1 Pre-sale,2 public sale,3 close purchase mapping(address => bool) public whitelist; mapping(address => uint256) public totalAmount; // Base URI string private m_BaseURI = ""; constructor( string memory name, string memory symbol, string memory baseURI ) ERC721(name, symbol) { admin = msg.sender; m_BaseURI = baseURI; } modifier onlyAdmin() { require(msg.sender == admin, "Not admin"); _; } /** * Mint Zombits */ function mintZombits(uint256 numberOfTokens) public payable { require( numberOfTokens <= maxZombitPurchase, "Exceeds max number of Zombits in one transaction" ); require(saleStatus == 1 || saleStatus == 2, "Purchase not open"); require( totalSupply().add(numberOfTokens) <= maxZombits, "Purchase would exceed max supply of Zombits" ); require( zombitPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct" ); // Pre-sale if (saleStatus == 1) { require( whitelist[_msgSender()], "No permission to participate in the pre-sale" ); require( totalAmount[_msgSender()] + numberOfTokens <= presaleMaxZombitPurchase, "Exceeded quantity limit" ); } for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); _safeMint(_msgSender(), tokenId); } totalAmount[_msgSender()] = totalAmount[_msgSender()] + numberOfTokens; } /** * Recycle Zombits */ function recycleZombits(uint256 numberOfTokens) public onlyAdmin { require( totalSupply().add(numberOfTokens) <= maxZombits, "Purchase would exceed max supply of Zombits" ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); _safeMint(_msgSender(), tokenId); } } /** * Add whitelist address */ function addWhitelist(address[] memory addr) public onlyAdmin { for (uint256 i = 0; i < addr.length; i++) { whitelist[addr[i]] = true; } } /** * Remove whitelist address */ function removeWhitelist(address[] memory addr) public onlyAdmin { for (uint256 i = 0; i < addr.length; i++) { whitelist[addr[i]] = false; } } /** * Withdraw all balance to the admin address */ function withdraw() public onlyAdmin { uint256 balance = address(this).balance; require(balance > 0); payable(_msgSender()).transfer(balance); } //Sales switch function flipSaleState() public onlyAdmin { if (saleStatus < 3) { saleStatus = saleStatus + 1; } } function setAdmin(address addr) external onlyAdmin { admin = addr; } function setMaxToken(uint256 _value) external onlyAdmin { require( _value > totalSupply() && _value <= 10_000, "Wrong value for max supply" ); maxZombits = _value; } function setPrice(uint256 _price) external onlyAdmin { zombitPrice = _price; } function setMaxPurchase(uint256 _value) external onlyAdmin { require(_value > 0, "Invalid value"); maxZombitPurchase = _value; } function setPresaleMaxZombitPurchase(uint256 _value) external onlyAdmin { require(_value > 0, "Invalid value"); presaleMaxZombitPurchase = _value; } // setBaseURI // - Metadata lives here function setBaseURI(string memory baseURI) external onlyAdmin { m_BaseURI = baseURI; } // _baseURI function _baseURI() internal view override returns (string memory) { return m_BaseURI; } //All tokens under this address function tokensOfOwner(address _owner) external view returns (uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { uint256 index = tokenOfOwnerByIndex(_owner, i); result[i] = index; } return result; } } }
recycleZombits
function recycleZombits(uint256 numberOfTokens) public onlyAdmin { require( totalSupply().add(numberOfTokens) <= maxZombits, "Purchase would exceed max supply of Zombits" ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); _safeMint(_msgSender(), tokenId); } }
/** * Recycle Zombits */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://676673b2541ab5708a84328d036883491ae88042640f01de48e51374de125b10
{ "func_code_index": [ 2171, 2560 ] }
9,304
ZombitContract
contracts/zombit.sol
0xb77a17d9e61c0c46debbb7a83a5d40e7eee4dbcd
Solidity
ZombitContract
contract ZombitContract is ERC721Enumerable, Ownable { using SafeMath for uint256; address admin; uint256 public maxZombitPurchase = 10; uint256 public presaleMaxZombitPurchase = 5; uint256 public zombitPrice = 80000000000000000; //0.08 ETH uint256 public maxZombits = 10000; uint256 public saleStatus = 0; //0 close purchase,1 Pre-sale,2 public sale,3 close purchase mapping(address => bool) public whitelist; mapping(address => uint256) public totalAmount; // Base URI string private m_BaseURI = ""; constructor( string memory name, string memory symbol, string memory baseURI ) ERC721(name, symbol) { admin = msg.sender; m_BaseURI = baseURI; } modifier onlyAdmin() { require(msg.sender == admin, "Not admin"); _; } /** * Mint Zombits */ function mintZombits(uint256 numberOfTokens) public payable { require( numberOfTokens <= maxZombitPurchase, "Exceeds max number of Zombits in one transaction" ); require(saleStatus == 1 || saleStatus == 2, "Purchase not open"); require( totalSupply().add(numberOfTokens) <= maxZombits, "Purchase would exceed max supply of Zombits" ); require( zombitPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct" ); // Pre-sale if (saleStatus == 1) { require( whitelist[_msgSender()], "No permission to participate in the pre-sale" ); require( totalAmount[_msgSender()] + numberOfTokens <= presaleMaxZombitPurchase, "Exceeded quantity limit" ); } for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); _safeMint(_msgSender(), tokenId); } totalAmount[_msgSender()] = totalAmount[_msgSender()] + numberOfTokens; } /** * Recycle Zombits */ function recycleZombits(uint256 numberOfTokens) public onlyAdmin { require( totalSupply().add(numberOfTokens) <= maxZombits, "Purchase would exceed max supply of Zombits" ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); _safeMint(_msgSender(), tokenId); } } /** * Add whitelist address */ function addWhitelist(address[] memory addr) public onlyAdmin { for (uint256 i = 0; i < addr.length; i++) { whitelist[addr[i]] = true; } } /** * Remove whitelist address */ function removeWhitelist(address[] memory addr) public onlyAdmin { for (uint256 i = 0; i < addr.length; i++) { whitelist[addr[i]] = false; } } /** * Withdraw all balance to the admin address */ function withdraw() public onlyAdmin { uint256 balance = address(this).balance; require(balance > 0); payable(_msgSender()).transfer(balance); } //Sales switch function flipSaleState() public onlyAdmin { if (saleStatus < 3) { saleStatus = saleStatus + 1; } } function setAdmin(address addr) external onlyAdmin { admin = addr; } function setMaxToken(uint256 _value) external onlyAdmin { require( _value > totalSupply() && _value <= 10_000, "Wrong value for max supply" ); maxZombits = _value; } function setPrice(uint256 _price) external onlyAdmin { zombitPrice = _price; } function setMaxPurchase(uint256 _value) external onlyAdmin { require(_value > 0, "Invalid value"); maxZombitPurchase = _value; } function setPresaleMaxZombitPurchase(uint256 _value) external onlyAdmin { require(_value > 0, "Invalid value"); presaleMaxZombitPurchase = _value; } // setBaseURI // - Metadata lives here function setBaseURI(string memory baseURI) external onlyAdmin { m_BaseURI = baseURI; } // _baseURI function _baseURI() internal view override returns (string memory) { return m_BaseURI; } //All tokens under this address function tokensOfOwner(address _owner) external view returns (uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { uint256 index = tokenOfOwnerByIndex(_owner, i); result[i] = index; } return result; } } }
addWhitelist
function addWhitelist(address[] memory addr) public onlyAdmin { for (uint256 i = 0; i < addr.length; i++) { whitelist[addr[i]] = true; } }
/** * Add whitelist address */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://676673b2541ab5708a84328d036883491ae88042640f01de48e51374de125b10
{ "func_code_index": [ 2611, 2790 ] }
9,305
ZombitContract
contracts/zombit.sol
0xb77a17d9e61c0c46debbb7a83a5d40e7eee4dbcd
Solidity
ZombitContract
contract ZombitContract is ERC721Enumerable, Ownable { using SafeMath for uint256; address admin; uint256 public maxZombitPurchase = 10; uint256 public presaleMaxZombitPurchase = 5; uint256 public zombitPrice = 80000000000000000; //0.08 ETH uint256 public maxZombits = 10000; uint256 public saleStatus = 0; //0 close purchase,1 Pre-sale,2 public sale,3 close purchase mapping(address => bool) public whitelist; mapping(address => uint256) public totalAmount; // Base URI string private m_BaseURI = ""; constructor( string memory name, string memory symbol, string memory baseURI ) ERC721(name, symbol) { admin = msg.sender; m_BaseURI = baseURI; } modifier onlyAdmin() { require(msg.sender == admin, "Not admin"); _; } /** * Mint Zombits */ function mintZombits(uint256 numberOfTokens) public payable { require( numberOfTokens <= maxZombitPurchase, "Exceeds max number of Zombits in one transaction" ); require(saleStatus == 1 || saleStatus == 2, "Purchase not open"); require( totalSupply().add(numberOfTokens) <= maxZombits, "Purchase would exceed max supply of Zombits" ); require( zombitPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct" ); // Pre-sale if (saleStatus == 1) { require( whitelist[_msgSender()], "No permission to participate in the pre-sale" ); require( totalAmount[_msgSender()] + numberOfTokens <= presaleMaxZombitPurchase, "Exceeded quantity limit" ); } for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); _safeMint(_msgSender(), tokenId); } totalAmount[_msgSender()] = totalAmount[_msgSender()] + numberOfTokens; } /** * Recycle Zombits */ function recycleZombits(uint256 numberOfTokens) public onlyAdmin { require( totalSupply().add(numberOfTokens) <= maxZombits, "Purchase would exceed max supply of Zombits" ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); _safeMint(_msgSender(), tokenId); } } /** * Add whitelist address */ function addWhitelist(address[] memory addr) public onlyAdmin { for (uint256 i = 0; i < addr.length; i++) { whitelist[addr[i]] = true; } } /** * Remove whitelist address */ function removeWhitelist(address[] memory addr) public onlyAdmin { for (uint256 i = 0; i < addr.length; i++) { whitelist[addr[i]] = false; } } /** * Withdraw all balance to the admin address */ function withdraw() public onlyAdmin { uint256 balance = address(this).balance; require(balance > 0); payable(_msgSender()).transfer(balance); } //Sales switch function flipSaleState() public onlyAdmin { if (saleStatus < 3) { saleStatus = saleStatus + 1; } } function setAdmin(address addr) external onlyAdmin { admin = addr; } function setMaxToken(uint256 _value) external onlyAdmin { require( _value > totalSupply() && _value <= 10_000, "Wrong value for max supply" ); maxZombits = _value; } function setPrice(uint256 _price) external onlyAdmin { zombitPrice = _price; } function setMaxPurchase(uint256 _value) external onlyAdmin { require(_value > 0, "Invalid value"); maxZombitPurchase = _value; } function setPresaleMaxZombitPurchase(uint256 _value) external onlyAdmin { require(_value > 0, "Invalid value"); presaleMaxZombitPurchase = _value; } // setBaseURI // - Metadata lives here function setBaseURI(string memory baseURI) external onlyAdmin { m_BaseURI = baseURI; } // _baseURI function _baseURI() internal view override returns (string memory) { return m_BaseURI; } //All tokens under this address function tokensOfOwner(address _owner) external view returns (uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { uint256 index = tokenOfOwnerByIndex(_owner, i); result[i] = index; } return result; } } }
removeWhitelist
function removeWhitelist(address[] memory addr) public onlyAdmin { for (uint256 i = 0; i < addr.length; i++) { whitelist[addr[i]] = false; } }
/** * Remove whitelist address */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://676673b2541ab5708a84328d036883491ae88042640f01de48e51374de125b10
{ "func_code_index": [ 2844, 3027 ] }
9,306