Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
134
// address UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
return uniswapRouter.getAmountsIn(_amount, getPathForDaitoSHIB());
return uniswapRouter.getAmountsIn(_amount, getPathForDaitoSHIB());
4,026
19
// Update the end of contract obligation (user and Total)/This obligation determines the number of tokens claimable by owner at end of contract/_address The address to update
function _updateFixedObligation(address _address) private { // Use the entire rewardlifetime if rewards have not yet started uint128 newMaxObligation; uint128 effectiveTime; if (rewardStartTime == 0) { effectiveTime = 0; } else if ( uint128(block.timestamp) > rewardStartTime + rewardLifetime ) { effectiveTime = rewardStartTime + rewardLifetime; } else { effectiveTime = uint128(block.timestamp); } newMaxObligation = (((userStakes[_address].amount * fixedAPR) / 10000) * (rewardStartTime + rewardLifetime - effectiveTime)) / rewardLifetime; // Adjust the total obligation fixedObligation = fixedObligation - userStakes[_address].maxObligation + newMaxObligation; userStakes[_address].maxObligation = newMaxObligation; }
function _updateFixedObligation(address _address) private { // Use the entire rewardlifetime if rewards have not yet started uint128 newMaxObligation; uint128 effectiveTime; if (rewardStartTime == 0) { effectiveTime = 0; } else if ( uint128(block.timestamp) > rewardStartTime + rewardLifetime ) { effectiveTime = rewardStartTime + rewardLifetime; } else { effectiveTime = uint128(block.timestamp); } newMaxObligation = (((userStakes[_address].amount * fixedAPR) / 10000) * (rewardStartTime + rewardLifetime - effectiveTime)) / rewardLifetime; // Adjust the total obligation fixedObligation = fixedObligation - userStakes[_address].maxObligation + newMaxObligation; userStakes[_address].maxObligation = newMaxObligation; }
6,348
4
// Emitted when a collateral factor is changed by admin
event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
11,825
0
// Initialized flag - indicates that initialization was made once
bool internal initialized;
bool internal initialized;
46,379
8
// require(name != "", "name can't be empty");
_name = name;
_name = name;
15,780
67
// `transfer`. {sendValue} removes this limitation.IMPORTANT: because control is transferred to `recipient`, care must betaken to not create reentrancy vulnerabilities. Consider using{ReentrancyGuard} or the /
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance");
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance");
128
212
// MasterChef is the master of Hpt. He can make Hpt 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 HPT is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless.
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 sushiRewardDebt; } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HPTs to distribute per block. uint256 lastRewardBlock; // Last block number that HPTs distribution occurs. uint256 accHptPerShare; // Accumulated HPTs per share, times 1e12. See below. uint256 sushiChefPid; uint256 lpBalance; uint256 accSushiPerShare; } // The HPT TOKEN! IERC20 public hpt; // HPT tokens created per block. uint256 public hptPerBlock; // 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 HPT mining starts. uint256 public startBlock; uint256 public hptRewardBalance; uint256 public sushiRewardBalance; uint256 public hptRewardTotal; uint256 public sushiRewardTotal; address public factory; address public WETH; ISushiChef public sushiChef; uint256 public sushiProfitRate; IERC20 public sushi; uint256 one = 1e18; address public treasuryAddress; 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 ); event AmtNotEnoughSend( address indexed user, address currency, uint256 shouldAmt, uint256 actAmt ); constructor( IERC20 _hpt, uint256 _hptPerBlock, uint256 _startBlock, address _sushiFactory, address _WETH, ISushiChef _sushiChef, uint256 _sushiProfitRate, IERC20 _sushi, address _treasuryAddress ) public { hpt = _hpt; hptPerBlock = _hptPerBlock; startBlock = _startBlock; factory = _sushiFactory; WETH = _WETH; sushiChef = _sushiChef; sushiProfitRate = _sushiProfitRate; sushi = _sushi; treasuryAddress = _treasuryAddress; } function setTreasuryAddress(address _treasuryAddress) public onlyOwner { treasuryAddress = _treasuryAddress; } function setHptPerBlock(uint _hptPerBlock) public onlyOwner { massUpdatePools(); hptPerBlock = _hptPerBlock; } function sushiRewardPerBlock(uint256 _pid) external view returns(uint256) { PoolInfo storage pool = poolInfo[_pid]; uint256 sushiTotalAllocPoint = sushiChef.totalAllocPoint(); ISushiChef.SushiPoolInfo memory sushiPoolInfo = sushiChef.poolInfo(pool.sushiChefPid); uint totalAmount = sushiPoolInfo.lpToken.balanceOf(address(sushiChef)); uint256 sushiPerBlock = sushiChef.sushiPerBlock().mul(sushiPoolInfo.allocPoint).div(sushiTotalAllocPoint); sushiPerBlock = sushiPerBlock.mul(pool.lpBalance).div(totalAmount); sushiPerBlock = sushiPerBlock.mul(one.sub(sushiProfitRate)).div(one); return sushiPerBlock; } function hptRewardPerBlock(uint _pid) external view returns(uint) { PoolInfo storage pool = poolInfo[_pid]; return hptPerBlock.mul(pool.allocPoint).div(totalAllocPoint); } function setSushiProfitRate(uint _sushiProfitRate) public onlyOwner { massUpdatePools(); sushiProfitRate = _sushiProfitRate; } function poolLength() external view returns (uint256) { return poolInfo.length; } function revoke() public onlyOwner { hpt.transfer(msg.sender, hpt.balanceOf(address(this))); //sushi.transfer(msg.sender, sushi.balanceOf(address(this))); } // 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, uint _sushiChefPid ) public onlyOwner { massUpdatePools(); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accHptPerShare: 0, sushiChefPid: _sushiChefPid, lpBalance: 0, accSushiPerShare: 0 }) ); } // Update the given pool's HPT allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, uint _sushiChefPid ) public onlyOwner { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].sushiChefPid = _sushiChefPid; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } // View function to see pending HPTs on frontend. function pendingHpt(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHptPerShare = pool.accHptPerShare; uint256 lpSupply = pool.lpBalance; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 hptReward = multiplier.mul(hptPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accHptPerShare = accHptPerShare.add( hptReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accHptPerShare).div(1e12).sub(user.rewardDebt); } // View function to see pending HPTs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = pool.lpBalance; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 sushiReward = sushiChef.pendingSushi(pool.sushiChefPid, address(this)); accSushiPerShare = accSushiPerShare.add( sushiReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accSushiPerShare).div(1e12).sub(user.sushiRewardDebt); } // 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); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpBalance; if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 hptReward = multiplier.mul(hptPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); hptRewardBalance = hptRewardBalance.add(hptReward); hptRewardTotal = hptRewardTotal.add(hptReward); pool.accHptPerShare = pool.accHptPerShare.add( hptReward.mul(1e12).div(lpSupply) ); //claim reward uint256 sushiBalancePrior = sushi.balanceOf(address(this)); sushiChef.withdraw(pool.sushiChefPid, 0); uint256 sushiBalanceNew = sushi.balanceOf(address(this)); if (sushiBalanceNew > sushiBalancePrior) { uint256 delta = sushiBalanceNew.sub(sushiBalancePrior); //keep profit to owner by sushiProfitRate uint256 sushiProfit = delta.mul(sushiProfitRate).div(one); sushi.transfer(treasuryAddress, sushiProfit); uint256 sushiReward = delta.sub(sushiProfit); sushiRewardBalance = sushiRewardBalance.add(sushiReward); sushiRewardTotal = sushiRewardTotal.add(sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add( sushiReward.mul(1e12).div(lpSupply) ); } pool.lastRewardBlock = block.number; } function depositTokens(uint256 _pid, address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin) public { uint _amount; address pair = getPair(tokenA, tokenB); PoolInfo storage pool = poolInfo[_pid]; require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); if (amountADesired != 0) { (, , _amount) = addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, address(this)); pool.lpToken.approve(address(sushiChef), _amount); sushiChef.deposit(pool.sushiChefPid, _amount); } deposit(_pid, _amount); } function depositETH(uint256 _pid, address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin) public payable { uint _amount; address pair = getPair(token, WETH); PoolInfo storage pool = poolInfo[_pid]; require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); if (amountTokenDesired != 0) { (, , _amount) = addLiquidityETH(token, amountTokenDesired, amountTokenMin, amountETHMin, address(this)); pool.lpToken.approve(address(sushiChef), _amount); sushiChef.deposit(pool.sushiChefPid, _amount); } deposit(_pid, _amount); } // Deposit LP tokens to MasterChef for HPT allocation. function deposit(uint256 _pid, uint256 _amount) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.amount > 0) { // reward hpt uint256 hptPending = user.amount.mul(pool.accHptPerShare).div(1e12).sub( user.rewardDebt ); safeHptTransfer(msg.sender, hptPending); // reward sushi uint256 sushiPending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub( user.sushiRewardDebt ); safeSushiTransfer(msg.sender, sushiPending); } pool.lpBalance = pool.lpBalance.add(_amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accHptPerShare).div(1e12); user.sushiRewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function withdrawTokens(uint256 _pid, address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin) public { address pair = getPair(tokenA, tokenB); PoolInfo storage pool = poolInfo[_pid]; require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); withdraw(_pid, liquidity); if (liquidity != 0) { sushiChef.withdraw(pool.sushiChefPid, liquidity); removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, msg.sender); } } function withdrawETH(uint256 _pid, address token, uint liquidity, uint amountTokenMin, uint amountETHMin) public { address pair = getPair(token, WETH); PoolInfo storage pool = poolInfo[_pid]; require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); withdraw(_pid, liquidity); if (liquidity != 0) { sushiChef.withdraw(pool.sushiChefPid, liquidity); uint amountToken; uint amountETH; (amountToken, amountETH) = removeLiquidity(token, WETH, liquidity, amountTokenMin, amountETHMin, address(this)); TransferHelper.safeTransfer(token, msg.sender, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(msg.sender, amountETH); } } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); // reward hpt uint256 pending = user.amount.mul(pool.accHptPerShare).div(1e12).sub( user.rewardDebt ); safeHptTransfer(msg.sender, pending); // reward sushi uint256 sushiPending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub( user.sushiRewardDebt ); safeSushiTransfer(msg.sender, sushiPending); pool.lpBalance = pool.lpBalance.sub(_amount); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accHptPerShare).div(1e12); user.sushiRewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdrawTokens(uint256 _pid, address tokenA, address tokenB, uint amountAMin, uint amountBMin) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; address pair = getPair(tokenA, tokenB); require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); sushiChef.withdraw(pool.sushiChefPid, user.amount); removeLiquidity(tokenA, tokenB, user.amount, amountAMin, amountBMin, msg.sender); emit EmergencyWithdraw(msg.sender, _pid, user.amount); pool.lpBalance = pool.lpBalance.sub(user.amount); user.amount = 0; user.rewardDebt = 0; user.sushiRewardDebt = 0; } function emergencyWithdrawETH(uint256 _pid, address token, uint amountTokenMin, uint amountETHMin) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; address pair = getPair(token, WETH); require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); sushiChef.withdraw(pool.sushiChefPid, user.amount); uint amountToken; uint amountETH; (amountToken, amountETH) = removeLiquidity(token, WETH, user.amount, amountTokenMin, amountETHMin, address(this)); TransferHelper.safeTransfer(token, msg.sender, amountToken); IWETH(WETH).withdraw(amountETH); emit EmergencyWithdraw(msg.sender, _pid, user.amount); pool.lpBalance = pool.lpBalance.sub(user.amount); user.amount = 0; user.rewardDebt = 0; user.sushiRewardDebt = 0; TransferHelper.safeTransferETH(msg.sender, amountETH); } function safeHptTransfer(address _to, uint256 _amount) internal { hptRewardBalance = hptRewardBalance.sub(_amount); uint256 hptBal = hpt.balanceOf(address(this)); if (_amount > hptBal) { hpt.transfer(_to, hptBal); emit AmtNotEnoughSend(_to, address(hpt), _amount, hptBal); } else { hpt.transfer(_to, _amount); } } function safeSushiTransfer(address _to, uint256 _amount) internal { sushiRewardBalance = sushiRewardBalance.sub(_amount); uint256 sushiBal = sushi.balanceOf(address(this)); if (_amount > sushiBal) { sushi.transfer(_to, sushiBal); emit AmtNotEnoughSend(_to, address(sushi), _amount, sushiBal); } else { sushi.transfer(_to, _amount); } } function getPair(address tokenA, address tokenB) internal view returns (address pair){ pair = ISushiFactory(factory).getPair(tokenA, tokenB); } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal view returns (uint amountA, uint amountB) { (uint reserveA, uint reserveB) = SushiSwapLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = SushiSwapLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = SushiSwapLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to ) internal returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = getPair(tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = ISushiPair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to ) internal returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = getPair(token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value : amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = ISushiPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to ) internal returns (uint amountA, uint amountB) { address pair = getPair(tokenA, tokenB); ISushiPair(pair).transfer(pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = ISushiPair(pair).burn(to); (address token0,) = SushiSwapLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'Router: INSUFFICIENT_B_AMOUNT'); } fallback() external {} receive() payable external {} }
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 sushiRewardDebt; } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HPTs to distribute per block. uint256 lastRewardBlock; // Last block number that HPTs distribution occurs. uint256 accHptPerShare; // Accumulated HPTs per share, times 1e12. See below. uint256 sushiChefPid; uint256 lpBalance; uint256 accSushiPerShare; } // The HPT TOKEN! IERC20 public hpt; // HPT tokens created per block. uint256 public hptPerBlock; // 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 HPT mining starts. uint256 public startBlock; uint256 public hptRewardBalance; uint256 public sushiRewardBalance; uint256 public hptRewardTotal; uint256 public sushiRewardTotal; address public factory; address public WETH; ISushiChef public sushiChef; uint256 public sushiProfitRate; IERC20 public sushi; uint256 one = 1e18; address public treasuryAddress; 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 ); event AmtNotEnoughSend( address indexed user, address currency, uint256 shouldAmt, uint256 actAmt ); constructor( IERC20 _hpt, uint256 _hptPerBlock, uint256 _startBlock, address _sushiFactory, address _WETH, ISushiChef _sushiChef, uint256 _sushiProfitRate, IERC20 _sushi, address _treasuryAddress ) public { hpt = _hpt; hptPerBlock = _hptPerBlock; startBlock = _startBlock; factory = _sushiFactory; WETH = _WETH; sushiChef = _sushiChef; sushiProfitRate = _sushiProfitRate; sushi = _sushi; treasuryAddress = _treasuryAddress; } function setTreasuryAddress(address _treasuryAddress) public onlyOwner { treasuryAddress = _treasuryAddress; } function setHptPerBlock(uint _hptPerBlock) public onlyOwner { massUpdatePools(); hptPerBlock = _hptPerBlock; } function sushiRewardPerBlock(uint256 _pid) external view returns(uint256) { PoolInfo storage pool = poolInfo[_pid]; uint256 sushiTotalAllocPoint = sushiChef.totalAllocPoint(); ISushiChef.SushiPoolInfo memory sushiPoolInfo = sushiChef.poolInfo(pool.sushiChefPid); uint totalAmount = sushiPoolInfo.lpToken.balanceOf(address(sushiChef)); uint256 sushiPerBlock = sushiChef.sushiPerBlock().mul(sushiPoolInfo.allocPoint).div(sushiTotalAllocPoint); sushiPerBlock = sushiPerBlock.mul(pool.lpBalance).div(totalAmount); sushiPerBlock = sushiPerBlock.mul(one.sub(sushiProfitRate)).div(one); return sushiPerBlock; } function hptRewardPerBlock(uint _pid) external view returns(uint) { PoolInfo storage pool = poolInfo[_pid]; return hptPerBlock.mul(pool.allocPoint).div(totalAllocPoint); } function setSushiProfitRate(uint _sushiProfitRate) public onlyOwner { massUpdatePools(); sushiProfitRate = _sushiProfitRate; } function poolLength() external view returns (uint256) { return poolInfo.length; } function revoke() public onlyOwner { hpt.transfer(msg.sender, hpt.balanceOf(address(this))); //sushi.transfer(msg.sender, sushi.balanceOf(address(this))); } // 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, uint _sushiChefPid ) public onlyOwner { massUpdatePools(); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accHptPerShare: 0, sushiChefPid: _sushiChefPid, lpBalance: 0, accSushiPerShare: 0 }) ); } // Update the given pool's HPT allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, uint _sushiChefPid ) public onlyOwner { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].sushiChefPid = _sushiChefPid; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } // View function to see pending HPTs on frontend. function pendingHpt(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHptPerShare = pool.accHptPerShare; uint256 lpSupply = pool.lpBalance; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 hptReward = multiplier.mul(hptPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accHptPerShare = accHptPerShare.add( hptReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accHptPerShare).div(1e12).sub(user.rewardDebt); } // View function to see pending HPTs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = pool.lpBalance; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 sushiReward = sushiChef.pendingSushi(pool.sushiChefPid, address(this)); accSushiPerShare = accSushiPerShare.add( sushiReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accSushiPerShare).div(1e12).sub(user.sushiRewardDebt); } // 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); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpBalance; if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 hptReward = multiplier.mul(hptPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); hptRewardBalance = hptRewardBalance.add(hptReward); hptRewardTotal = hptRewardTotal.add(hptReward); pool.accHptPerShare = pool.accHptPerShare.add( hptReward.mul(1e12).div(lpSupply) ); //claim reward uint256 sushiBalancePrior = sushi.balanceOf(address(this)); sushiChef.withdraw(pool.sushiChefPid, 0); uint256 sushiBalanceNew = sushi.balanceOf(address(this)); if (sushiBalanceNew > sushiBalancePrior) { uint256 delta = sushiBalanceNew.sub(sushiBalancePrior); //keep profit to owner by sushiProfitRate uint256 sushiProfit = delta.mul(sushiProfitRate).div(one); sushi.transfer(treasuryAddress, sushiProfit); uint256 sushiReward = delta.sub(sushiProfit); sushiRewardBalance = sushiRewardBalance.add(sushiReward); sushiRewardTotal = sushiRewardTotal.add(sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add( sushiReward.mul(1e12).div(lpSupply) ); } pool.lastRewardBlock = block.number; } function depositTokens(uint256 _pid, address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin) public { uint _amount; address pair = getPair(tokenA, tokenB); PoolInfo storage pool = poolInfo[_pid]; require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); if (amountADesired != 0) { (, , _amount) = addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, address(this)); pool.lpToken.approve(address(sushiChef), _amount); sushiChef.deposit(pool.sushiChefPid, _amount); } deposit(_pid, _amount); } function depositETH(uint256 _pid, address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin) public payable { uint _amount; address pair = getPair(token, WETH); PoolInfo storage pool = poolInfo[_pid]; require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); if (amountTokenDesired != 0) { (, , _amount) = addLiquidityETH(token, amountTokenDesired, amountTokenMin, amountETHMin, address(this)); pool.lpToken.approve(address(sushiChef), _amount); sushiChef.deposit(pool.sushiChefPid, _amount); } deposit(_pid, _amount); } // Deposit LP tokens to MasterChef for HPT allocation. function deposit(uint256 _pid, uint256 _amount) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.amount > 0) { // reward hpt uint256 hptPending = user.amount.mul(pool.accHptPerShare).div(1e12).sub( user.rewardDebt ); safeHptTransfer(msg.sender, hptPending); // reward sushi uint256 sushiPending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub( user.sushiRewardDebt ); safeSushiTransfer(msg.sender, sushiPending); } pool.lpBalance = pool.lpBalance.add(_amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accHptPerShare).div(1e12); user.sushiRewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function withdrawTokens(uint256 _pid, address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin) public { address pair = getPair(tokenA, tokenB); PoolInfo storage pool = poolInfo[_pid]; require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); withdraw(_pid, liquidity); if (liquidity != 0) { sushiChef.withdraw(pool.sushiChefPid, liquidity); removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, msg.sender); } } function withdrawETH(uint256 _pid, address token, uint liquidity, uint amountTokenMin, uint amountETHMin) public { address pair = getPair(token, WETH); PoolInfo storage pool = poolInfo[_pid]; require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); withdraw(_pid, liquidity); if (liquidity != 0) { sushiChef.withdraw(pool.sushiChefPid, liquidity); uint amountToken; uint amountETH; (amountToken, amountETH) = removeLiquidity(token, WETH, liquidity, amountTokenMin, amountETHMin, address(this)); TransferHelper.safeTransfer(token, msg.sender, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(msg.sender, amountETH); } } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); // reward hpt uint256 pending = user.amount.mul(pool.accHptPerShare).div(1e12).sub( user.rewardDebt ); safeHptTransfer(msg.sender, pending); // reward sushi uint256 sushiPending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub( user.sushiRewardDebt ); safeSushiTransfer(msg.sender, sushiPending); pool.lpBalance = pool.lpBalance.sub(_amount); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accHptPerShare).div(1e12); user.sushiRewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdrawTokens(uint256 _pid, address tokenA, address tokenB, uint amountAMin, uint amountBMin) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; address pair = getPair(tokenA, tokenB); require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); sushiChef.withdraw(pool.sushiChefPid, user.amount); removeLiquidity(tokenA, tokenB, user.amount, amountAMin, amountBMin, msg.sender); emit EmergencyWithdraw(msg.sender, _pid, user.amount); pool.lpBalance = pool.lpBalance.sub(user.amount); user.amount = 0; user.rewardDebt = 0; user.sushiRewardDebt = 0; } function emergencyWithdrawETH(uint256 _pid, address token, uint amountTokenMin, uint amountETHMin) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; address pair = getPair(token, WETH); require(pair == address(pool.lpToken), "wrong pid"); updatePool(_pid); sushiChef.withdraw(pool.sushiChefPid, user.amount); uint amountToken; uint amountETH; (amountToken, amountETH) = removeLiquidity(token, WETH, user.amount, amountTokenMin, amountETHMin, address(this)); TransferHelper.safeTransfer(token, msg.sender, amountToken); IWETH(WETH).withdraw(amountETH); emit EmergencyWithdraw(msg.sender, _pid, user.amount); pool.lpBalance = pool.lpBalance.sub(user.amount); user.amount = 0; user.rewardDebt = 0; user.sushiRewardDebt = 0; TransferHelper.safeTransferETH(msg.sender, amountETH); } function safeHptTransfer(address _to, uint256 _amount) internal { hptRewardBalance = hptRewardBalance.sub(_amount); uint256 hptBal = hpt.balanceOf(address(this)); if (_amount > hptBal) { hpt.transfer(_to, hptBal); emit AmtNotEnoughSend(_to, address(hpt), _amount, hptBal); } else { hpt.transfer(_to, _amount); } } function safeSushiTransfer(address _to, uint256 _amount) internal { sushiRewardBalance = sushiRewardBalance.sub(_amount); uint256 sushiBal = sushi.balanceOf(address(this)); if (_amount > sushiBal) { sushi.transfer(_to, sushiBal); emit AmtNotEnoughSend(_to, address(sushi), _amount, sushiBal); } else { sushi.transfer(_to, _amount); } } function getPair(address tokenA, address tokenB) internal view returns (address pair){ pair = ISushiFactory(factory).getPair(tokenA, tokenB); } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal view returns (uint amountA, uint amountB) { (uint reserveA, uint reserveB) = SushiSwapLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = SushiSwapLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = SushiSwapLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to ) internal returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = getPair(tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = ISushiPair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to ) internal returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = getPair(token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value : amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = ISushiPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to ) internal returns (uint amountA, uint amountB) { address pair = getPair(tokenA, tokenB); ISushiPair(pair).transfer(pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = ISushiPair(pair).burn(to); (address token0,) = SushiSwapLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'Router: INSUFFICIENT_B_AMOUNT'); } fallback() external {} receive() payable external {} }
23,362
69
// assume 360 ethereum blocks per hourwe want miners to spend 10 minutes to mine each 'block', about 60 ethereum blocks = one BitcoinSoV epoch
uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 60; //should be 60 times slower than ethereum
uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 60; //should be 60 times slower than ethereum
33,170
285
// Mapping of CKToken to user deposit in a round, key is hashed by keccak256(user_address, round number)
mapping(ICKToken => mapping(bytes32 => uint256)) public userDeposits;
mapping(ICKToken => mapping(bytes32 => uint256)) public userDeposits;
18,301
14
// for now, fix wager to 1 USDC
require( _wager == 1 * (10 ** betTokenDecimal), "Wager must be 1 USDC for now" );
require( _wager == 1 * (10 ** betTokenDecimal), "Wager must be 1 USDC for now" );
20,271
51
// @custom:security-contact hello@metareset.org
contract MetaReset is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = true; bool public swapEnabled = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("MetaReset", "RESET") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 3; uint256 _sellMarketingFee = 3; uint256 _sellLiquidityFee = 3; uint256 _sellDevFee = 3; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn maxWallet = 20_000_000 * 1e18; // 2% from total supply maxWallet swapTokensAtAmount = (totalSupply * 10) / 10000; // 0.1% swap wallet which is 1 million buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x0D95b9b08108d2CA203EC18eeaF096686D9a11Dd); // set as marketing wallet devWallet = address(0x320cA0f9F3ea3Cb361B63e213f67cc86A443a72D); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading(bool enabled) external onlyOwner { if(enabled){ tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } } // remove limits after token is stable function vanishLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function adjustSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function adjustLimits(uint256 newNumTx, uint256 newNumWallet) external onlyOwner { require( newNumTx >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNumTx * (10**18); require( newNumWallet >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNumWallet * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function adjustFees(uint256 _buyMarketingFee, uint256 _buyLiquidityFee, uint256 _buyDevFee, uint256 _sellMarketingFee, uint256 _sellLiquidityFee, uint256 _sellDevFee) external onlyOwner{ buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 10, "Must keep fees at 10% or less"); sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(buyTotalFees <= 10, "Must keep fees at 10% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; // This condition fails in buy flow if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } // This condition fails in buy flow. This will be executed in a sell flow. if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
contract MetaReset is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = true; bool public swapEnabled = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("MetaReset", "RESET") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 3; uint256 _sellMarketingFee = 3; uint256 _sellLiquidityFee = 3; uint256 _sellDevFee = 3; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn maxWallet = 20_000_000 * 1e18; // 2% from total supply maxWallet swapTokensAtAmount = (totalSupply * 10) / 10000; // 0.1% swap wallet which is 1 million buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x0D95b9b08108d2CA203EC18eeaF096686D9a11Dd); // set as marketing wallet devWallet = address(0x320cA0f9F3ea3Cb361B63e213f67cc86A443a72D); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading(bool enabled) external onlyOwner { if(enabled){ tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } } // remove limits after token is stable function vanishLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function adjustSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function adjustLimits(uint256 newNumTx, uint256 newNumWallet) external onlyOwner { require( newNumTx >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNumTx * (10**18); require( newNumWallet >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNumWallet * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function adjustFees(uint256 _buyMarketingFee, uint256 _buyLiquidityFee, uint256 _buyDevFee, uint256 _sellMarketingFee, uint256 _sellLiquidityFee, uint256 _sellDevFee) external onlyOwner{ buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 10, "Must keep fees at 10% or less"); sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(buyTotalFees <= 10, "Must keep fees at 10% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; // This condition fails in buy flow if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } // This condition fails in buy flow. This will be executed in a sell flow. if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
10,036
3
// The constructor sets the original `owner` of the contract to the sender account. /
constructor()
constructor()
1,257
31
// Success, send the transaction
(bool success, ) = toAddress.call{ value: value }(data);
(bool success, ) = toAddress.call{ value: value }(data);
85,361
106
// Mints a token to an address._to address of the future owner of the token/
function mintTo(address _to) public onlyOwner { require(_to != address(0), "cannot mint to address 0"); _mint(_to); }
function mintTo(address _to) public onlyOwner { require(_to != address(0), "cannot mint to address 0"); _mint(_to); }
11,812
1
// Lets an authorised module add a guardian to a vault. _vault - The target vault. _guardian - The guardian to add. /
function addGuardian(address _vault, address _guardian) external;
function addGuardian(address _vault, address _guardian) external;
35,717
152
// function that checks whether the token is LinkToken or not /
function isLinkToken (address contractAddress) public view returns (bool) { return _isLinkToken[contractAddress]; }
function isLinkToken (address contractAddress) public view returns (bool) { return _isLinkToken[contractAddress]; }
20,242
27
// create a lists of all auctions
mapping(uint256 => auctions) private Auctions;
mapping(uint256 => auctions) private Auctions;
31,874
18
// ------------------------------------------------------------------------ Balances for each account ------------------------------------------------------------------------
mapping(address => uint) balances;
mapping(address => uint) balances;
37,455
2
// Counts number of set bits (1's) in 32-bit unsigned integer
function bit_count_32(uint32 n) internal pure returns (uint32) { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return (((n + (n >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; }
function bit_count_32(uint32 n) internal pure returns (uint32) { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return (((n + (n >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; }
14,151
157
// deploy virtual funds (RP vStable)/ deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
7,506
9
// Token locked block length
uint256 public halvedBlock; uint256 public halvedBlockLength = 2_000_000;
uint256 public halvedBlock; uint256 public halvedBlockLength = 2_000_000;
42,021
3
// Cancel a pending grantee reassignment request./ Can only be called by the grantee.
function cancelReassignmentRequest() public onlyGrantee withRequestedReassignment
function cancelReassignmentRequest() public onlyGrantee withRequestedReassignment
25,153
46
// Updates the protocol fee on the bridging bridgeProtocolFee The part of the premium sent to the protocol treasury /
function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;
function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;
25,489
325
// check strike prices are increasing
for (uint256 i = 0; i < _strikePrices.length - 1; i++) { require(_strikePrices[i] < _strikePrices[i + 1], "Strike prices must be increasing"); }
for (uint256 i = 0; i < _strikePrices.length - 1; i++) { require(_strikePrices[i] < _strikePrices[i + 1], "Strike prices must be increasing"); }
26,608
250
// constructor deploys a new proxyFactory.
constructor(ParameterizerFactory _parameterizerFactory) public { parameterizerFactory = _parameterizerFactory; proxyFactory = parameterizerFactory.proxyFactory(); canonizedRegistry = new Registry(); }
constructor(ParameterizerFactory _parameterizerFactory) public { parameterizerFactory = _parameterizerFactory; proxyFactory = parameterizerFactory.proxyFactory(); canonizedRegistry = new Registry(); }
5,339
31
// Uniswap V3 NonfungiblePositionManager interface. Interface for any contract that wants to support UNI-V3-POS fee collection. /
interface INonfungiblePositionManager { function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); }
interface INonfungiblePositionManager { function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); }
25,580
3
// id of cammpiagn
function donateToCampaign(uint256 _id) public payable { uint256 amount = msg.value; Campaign storage campaign = campaigns[_id]; campaign.donators.push(msg.sender); campaign.donations.push(amount); (bool sent, ) = payable(campaign.owner).call{value: amount}(""); if (sent) { campaign.amountCollected = campaign.amountCollected + amount; } }
function donateToCampaign(uint256 _id) public payable { uint256 amount = msg.value; Campaign storage campaign = campaigns[_id]; campaign.donators.push(msg.sender); campaign.donations.push(amount); (bool sent, ) = payable(campaign.owner).call{value: amount}(""); if (sent) { campaign.amountCollected = campaign.amountCollected + amount; } }
29,756
1
// check for deadline
require(campaign.deadline < block.timestamp, "The deadline show be a date in the future."); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image;
require(campaign.deadline < block.timestamp, "The deadline show be a date in the future."); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image;
28,429
6
// transfer ownership of token to bridge
newChildToken = TokenUpgradeable(address(transparentUpgradeableProxy)); newChildToken.transferOwnership(bridgeUpgradeable);
newChildToken = TokenUpgradeable(address(transparentUpgradeableProxy)); newChildToken.transferOwnership(bridgeUpgradeable);
10,297
27
// Constructor.
function Gabicoin() EIP20(0, "Gabicoin", 2, "GCO") public
function Gabicoin() EIP20(0, "Gabicoin", 2, "GCO") public
2,403
16
// 1e32 adjustment is removed during claim
uint _ratio = (toFees * _FEE_PRECISION) / totalSupply; if (_ratio > 0) { index0 += _ratio; }
uint _ratio = (toFees * _FEE_PRECISION) / totalSupply; if (_ratio > 0) { index0 += _ratio; }
28,418
193
// View function to see pending SOMMAI on frontend.
function pendingSommai(uint256 _pid, address _user) external override view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSommaiPerShare = pool.accSommaiPerShare; uint256 lpSupply = IERC20(pool.stakeToken).balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sommaiReward = multiplier.mul(sommaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSommaiPerShare = accSommaiPerShare.add(sommaiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSommaiPerShare).div(1e12).sub(user.rewardDebt); }
function pendingSommai(uint256 _pid, address _user) external override view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSommaiPerShare = pool.accSommaiPerShare; uint256 lpSupply = IERC20(pool.stakeToken).balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sommaiReward = multiplier.mul(sommaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSommaiPerShare = accSommaiPerShare.add(sommaiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSommaiPerShare).div(1e12).sub(user.rewardDebt); }
23,356
75
// Make sure this is in sync with what create() does.
_mint(_owners[i], _tokenIdStart + i);
_mint(_owners[i], _tokenIdStart + i);
52,357
231
// Derived balance of the connector
uint256 inConnector;
uint256 inConnector;
49,699
60
// Claim refund, which will transfer refunded Wei amount back to buyer._token Deployed ERC20 token address /
function claimRefund( address _token ) public nonZeroAddress(_token) inState(_token, States.Refunding)
function claimRefund( address _token ) public nonZeroAddress(_token) inState(_token, States.Refunding)
34,244
5
// Exits liquidity tokens from a Balancer V2 pool.
function exitPool( bytes32 poolId, address sender, address recipient, ExitPoolRequest calldata request ) external;
function exitPool( bytes32 poolId, address sender, address recipient, ExitPoolRequest calldata request ) external;
18,961
9
// mint(): Mint a new Gen0 Beats.These are the tokens that other Beats will be "cloned from"./_to Address to mint to./_priceFinney Price of the Beats in Finney./_numEditionsAllowed Maximum number of times this Beats is allowed to be cloned./_tokenURI A URL to the JSON file containing the metadata for the Beats.See metadata.json for an example./ return tokenId the tokenId of the Beats that has been minted.Note that in a transaction only the tx_hash is returned.
function mint(address _to, uint256 _priceFinney, uint256 _numEditionsAllowed, string memory _tokenURI, bool _remixable) public mintable returns (uint256 tokenId) { Beat memory _beat = Beat({ priceFinney: _priceFinney, numEditionsAllowed: _numEditionsAllowed, numEditionsInWild: 0, madeFromId: 0, remixable: _remixable }); // The new beat is pushed onto the array and minted // Note that Solidity uses 0 as a default value when an item is not found in a mapping. tokenId = beats.length; beats.push(_beat); beats[tokenId].madeFromId = tokenId; _mint(_to, tokenId); _setTokenURI(tokenId, _tokenURI); emit TokenMinted(tokenId); }
function mint(address _to, uint256 _priceFinney, uint256 _numEditionsAllowed, string memory _tokenURI, bool _remixable) public mintable returns (uint256 tokenId) { Beat memory _beat = Beat({ priceFinney: _priceFinney, numEditionsAllowed: _numEditionsAllowed, numEditionsInWild: 0, madeFromId: 0, remixable: _remixable }); // The new beat is pushed onto the array and minted // Note that Solidity uses 0 as a default value when an item is not found in a mapping. tokenId = beats.length; beats.push(_beat); beats[tokenId].madeFromId = tokenId; _mint(_to, tokenId); _setTokenURI(tokenId, _tokenURI); emit TokenMinted(tokenId); }
32,163
18
// force reserves to match balances --/
function sync() external lock { _update( IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1 ); }
function sync() external lock { _update( IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1 ); }
26,017
23
// If the upgrade hasn't been registered, register with the current time.
if (registrationTime == 0) { timeLockedUpgrades[upgradeHash] = block.timestamp; emit UpgradeRegistered( upgradeHash, block.timestamp ); return; }
if (registrationTime == 0) { timeLockedUpgrades[upgradeHash] = block.timestamp; emit UpgradeRegistered( upgradeHash, block.timestamp ); return; }
20,971
42
// Returns list of transaction IDs in defined range./from Index start position of transaction array./to Index end position of transaction array./pending Include pending transactions./executed Include executed transactions./ return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds)
function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds)
14,645
251
// Skip the O(length) loop when source == dest.
if (source == dest) { return; }
if (source == dest) { return; }
42,178
98
// Emitted when the operator address permission has been changed. operator Address of the operator. previousPermission Whether the operator was authorized. newPermission Whether the operator will be authorized. /
event SetOperator(address indexed operator, bool indexed previousPermission, bool indexed newPermission);
event SetOperator(address indexed operator, bool indexed previousPermission, bool indexed newPermission);
35,734
7
// Index of most recent order.
uint256 internal _orderIndex;
uint256 internal _orderIndex;
46,743
11
// Save this for an assertion in the future.
uint previousBalances = balanceOf[_from] + balanceOf[_to];
uint previousBalances = balanceOf[_from] + balanceOf[_to];
9,953
2
// an Entry represents a single entry purchase for a raffle
struct Entry { address player; }
struct Entry { address player; }
3,469
0
// only the owner is allowed to burn tokens
function burn(uint256 _value) public onlyOwner { _burn(msg.sender, _value); }
function burn(uint256 _value) public onlyOwner { _burn(msg.sender, _value); }
44,858
2
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
function revokeOverride(bytes32 role, address account) external;
16,924
18
// As described in https:eips.ethereum.org/EIPS/eip-20
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function name() external view returns (string memory); // optional method - see eip spec function symbol() external view returns (string memory); // optional method - see eip spec function decimals() external view returns (uint8); // optional method - see eip spec function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); }
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function name() external view returns (string memory); // optional method - see eip spec function symbol() external view returns (string memory); // optional method - see eip spec function decimals() external view returns (uint8); // optional method - see eip spec function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); }
6,282
6
// Transfers value amount of an _id from the _from address to the _to addresses specified. Each parameter array should be the same length, with each index correlating. MUST emit Transfer event on success.Caller must have sufficient allowance by _from for the _id/_value pair, or isApprovedForAll must be true.Throws if `_to` is the zero address.Throws if `_id` is not a valid token ID.When transfer is complete, this function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC1155Received` on `_to` and throws if the return value is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`. _fromsource addresses _totarget addresses _idID of
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
41,336
63
// set approval for custom OFT bridge contract
LibAsset.maxApproveERC20( IERC20(_bridgeData.sendingAssetId), _oftWrapperData.customCode_approveTo, _bridgeData.minAmount );
LibAsset.maxApproveERC20( IERC20(_bridgeData.sendingAssetId), _oftWrapperData.customCode_approveTo, _bridgeData.minAmount );
20,290
56
// Third Owner saved reward withdraw
uint256 endRewardAmount = rewardToken.balanceOf(address(this)); if(endRewardAmount > 0){ rewardToken.transfer(owner, endRewardAmount); }
uint256 endRewardAmount = rewardToken.balanceOf(address(this)); if(endRewardAmount > 0){ rewardToken.transfer(owner, endRewardAmount); }
41,921
77
// Liquidity pool token interface
IUniswapV2Pair public pair;
IUniswapV2Pair public pair;
28,065
16
// Contract module which provides a basic access control mechanism, wherethere is an account (an owner) that can be granted exclusive access tospecific functions. This module is used through inheritance. It will make available the modifier`onlyOwner`, which can be applied to your functions to restrict their use tothe owner. /
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
8,363
305
// returns the address to which the interest is redirected_user address of the user return 0 if there is no redirection, an address otherwise/
function getInterestRedirectionAddress(address _user) external view returns(address) { return interestRedirectionAddresses[_user]; }
function getInterestRedirectionAddress(address _user) external view returns(address) { return interestRedirectionAddresses[_user]; }
16,216
17
// Returns true if the caller is the admin role /
function isAdmin() public view returns (bool) { return hasRole(msg.sender, 0); }
function isAdmin() public view returns (bool) { return hasRole(msg.sender, 0); }
26,167
115
// rateConfidence = currentTotalLotteryHours / (avgLotteryHours + currentTotalLotteryHours);But since we need to account for decimal pointsrateConfidence = (currentTotalLotteryHoursTWO_DECIMALS) / (avgLotteryHours + currentTotalLotteryHours);rateConfidence needs to be divided by TWO_DECIMALS later on /
rateConfidence = currentTotalLotteryHours.mul(TWO_DECIMALS).div(avgLotteryHours.add(currentTotalLotteryHours));
rateConfidence = currentTotalLotteryHours.mul(TWO_DECIMALS).div(avgLotteryHours.add(currentTotalLotteryHours));
10,222
99
// do we need to remember previous reward? IDK!add here if needed (not needed??)
rewardPerBlockPriorFibonaccening = rewardPerBlock; //remember new reward as current ?? IDK
rewardPerBlockPriorFibonaccening = rewardPerBlock; //remember new reward as current ?? IDK
35,398
10
// An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
25,320
27
// Get the current mint fee floor price. Returns the lowest price for a token minting. /
function mintFeeFloor() public view returns (uint) { return _mintFeeFloor; }
function mintFeeFloor() public view returns (uint) { return _mintFeeFloor; }
80,470
21
// Claim a refund for a bid where the vote was not cast
function claimRefund(uint256) external;
function claimRefund(uint256) external;
10,164
237
// an optional (to be choosen by contract owner) fee on each option. A % of the bet money is sent as a fee. see devFundBetFee
if (devFundBetFee > 0) { uint256 fee = msg.value.div(devFundBetFee).div(100); require(devFund.send(fee), "devFund fee transfer failed"); depositValue = msg.value.sub(fee); } else {
if (devFundBetFee > 0) { uint256 fee = msg.value.div(devFundBetFee).div(100); require(devFund.send(fee), "devFund fee transfer failed"); depositValue = msg.value.sub(fee); } else {
27,193
38
// string marketID;
string storageTimeStamp; string storageDetail; //storageDescription, storageTableName, storageUser and storageQuantity which includes storage UoM uint256 BlockNumber; //block number of storage submission. previously hash uint IsSet; // integer indication of whether storage Submission exists i.e. default is zero so if > 0 it exists
string storageTimeStamp; string storageDetail; //storageDescription, storageTableName, storageUser and storageQuantity which includes storage UoM uint256 BlockNumber; //block number of storage submission. previously hash uint IsSet; // integer indication of whether storage Submission exists i.e. default is zero so if > 0 it exists
25,081
168
// Collects opium tokens
IStakingRewards(rewards).getReward(); uint256 _opium = IERC20_2(opium).balanceOf(address(this)); if (_opium > 0) {
IStakingRewards(rewards).getReward(); uint256 _opium = IERC20_2(opium).balanceOf(address(this)); if (_opium > 0) {
31,631
50
// Calculates the ETH gain earned by the deposit since its last snapshots were taken.Given by the formula:E = d0(S - S(0))/P(0)where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively.d0 is the last recorded deposit value. /
function getDepositorETHGain(address _depositor) public view override returns (uint256) { uint256 initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint256 ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; }
function getDepositorETHGain(address _depositor) public view override returns (uint256) { uint256 initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint256 ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; }
43,297
9
// Unassigned Integer variable ~ tokenPrice ~ is equal to 1 ether
uint tokenPrice = 1 ether;
uint tokenPrice = 1 ether;
9,116
165
// Designed to manage delegation to staking contract /
contract DelegateManager is InitializableV2 { using SafeMath for uint256; string private constant ERROR_ONLY_GOVERNANCE = ( "DelegateManager: Only callable by Governance contract" ); string private constant ERROR_MINIMUM_DELEGATION = ( "DelegateManager: Minimum delegation amount required" ); string private constant ERROR_ONLY_SP_GOVERNANCE = ( "DelegateManager: Only callable by target SP or governance" ); string private constant ERROR_DELEGATOR_STAKE = ( "DelegateManager: Delegator must be staked for SP" ); address private governanceAddress; address private stakingAddress; address private serviceProviderFactoryAddress; address private claimsManagerAddress; /** * Period in blocks an undelegate operation is delayed. * The undelegate operation speed bump is to prevent a delegator from * attempting to remove their delegation in anticipation of a slash. * @notice Must be greater than governance votingPeriod + executionDelay */ uint256 private undelegateLockupDuration; /// @notice Maximum number of delegators a single account can handle uint256 private maxDelegators; /// @notice Minimum amount of delegation allowed uint256 private minDelegationAmount; /** * Lockup duration for a remove delegator request. * The remove delegator speed bump is to prevent a service provider from maliciously * removing a delegator prior to the evaluation of a proposal. * @notice Must be greater than governance votingPeriod + executionDelay */ uint256 private removeDelegatorLockupDuration; /** * Evaluation period for a remove delegator request * @notice added to expiry block calculated for removeDelegatorLockupDuration */ uint256 private removeDelegatorEvalDuration; // Staking contract ref ERC20Mintable private audiusToken; // Struct representing total delegated to SP and list of delegators struct ServiceProviderDelegateInfo { uint256 totalDelegatedStake; uint256 totalLockedUpStake; address[] delegators; } // Data structures for lockup during withdrawal struct UndelegateStakeRequest { address serviceProvider; uint256 amount; uint256 lockupExpiryBlock; } // Service provider address -> ServiceProviderDelegateInfo mapping (address => ServiceProviderDelegateInfo) private spDelegateInfo; // Delegator stake by address delegated to // delegator -> (service provider -> delegatedStake) mapping (address => mapping(address => uint256)) private delegateInfo; // Delegator stake total by address // delegator -> (totalDelegated) // Note - delegator properties are maintained in a mapping instead of struct // in order to facilitate extensibility in the future. mapping (address => uint256) private delegatorTotalStake; // Requester to pending undelegate request mapping (address => UndelegateStakeRequest) private undelegateRequests; // Pending remove delegator requests // service provider -> (delegator -> lockupExpiryBlock) mapping (address => mapping (address => uint256)) private removeDelegatorRequests; event IncreaseDelegatedStake( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _increaseAmount ); event UndelegateStakeRequested( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount, uint256 _lockupExpiryBlock ); event UndelegateStakeRequestCancelled( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount ); event UndelegateStakeRequestEvaluated( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount ); event Claim( address indexed _claimer, uint256 indexed _rewards, uint256 indexed _newTotal ); event Slash( address indexed _target, uint256 indexed _amount, uint256 indexed _newTotal ); event RemoveDelegatorRequested( address indexed _serviceProvider, address indexed _delegator, uint256 indexed _lockupExpiryBlock ); event RemoveDelegatorRequestCancelled( address indexed _serviceProvider, address indexed _delegator ); event RemoveDelegatorRequestEvaluated( address indexed _serviceProvider, address indexed _delegator, uint256 indexed _unstakedAmount ); event MaxDelegatorsUpdated(uint256 indexed _maxDelegators); event MinDelegationUpdated(uint256 indexed _minDelegationAmount); event UndelegateLockupDurationUpdated(uint256 indexed _undelegateLockupDuration); event GovernanceAddressUpdated(address indexed _newGovernanceAddress); event StakingAddressUpdated(address indexed _newStakingAddress); event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress); event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress); event RemoveDelegatorLockupDurationUpdated(uint256 indexed _removeDelegatorLockupDuration); event RemoveDelegatorEvalDurationUpdated(uint256 indexed _removeDelegatorEvalDuration); /** * @notice Function to initialize the contract * @dev stakingAddress must be initialized separately after Staking contract is deployed * @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed * @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed * @param _tokenAddress - address of ERC20 token that will be claimed * @param _governanceAddress - Governance proxy address */ function initialize ( address _tokenAddress, address _governanceAddress, uint256 _undelegateLockupDuration ) public initializer { _updateGovernanceAddress(_governanceAddress); audiusToken = ERC20Mintable(_tokenAddress); maxDelegators = 175; // Default minimum delegation amount set to 100AUD minDelegationAmount = 100 * 10**uint256(18); InitializableV2.initialize(); _updateUndelegateLockupDuration(_undelegateLockupDuration); // 1 week = 168hrs * 60 min/hr * 60 sec/min / ~13 sec/block = 46523 blocks _updateRemoveDelegatorLockupDuration(46523); // 24hr * 60min/hr * 60sec/min / ~13 sec/block = 6646 blocks removeDelegatorEvalDuration = 6646; } /** * @notice Allow a delegator to delegate stake to a service provider * @param _targetSP - address of service provider to delegate to * @param _amount - amount in wei to delegate * @return Updated total amount delegated to the service provider by delegator */ function delegateStake( address _targetSP, uint256 _amount ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); require( !_claimPending(_targetSP), "DelegateManager: Delegation not permitted for SP pending claim" ); address delegator = msg.sender; Staking stakingContract = Staking(stakingAddress); // Stake on behalf of target service provider stakingContract.delegateStakeFor( _targetSP, delegator, _amount ); // Update list of delegators to SP if necessary if (!_delegatorExistsForSP(delegator, _targetSP)) { // If not found, update list of delegates spDelegateInfo[_targetSP].delegators.push(delegator); require( spDelegateInfo[_targetSP].delegators.length <= maxDelegators, "DelegateManager: Maximum delegators exceeded" ); } // Update following values in storage through helper // totalServiceProviderDelegatedStake = current sp total + new amount, // totalStakedForSpFromDelegator = current delegator total for sp + new amount, // totalDelegatorStake = current delegator total + new amount _updateDelegatorStake( delegator, _targetSP, spDelegateInfo[_targetSP].totalDelegatedStake.add(_amount), delegateInfo[delegator][_targetSP].add(_amount), delegatorTotalStake[delegator].add(_amount) ); require( delegateInfo[delegator][_targetSP] >= minDelegationAmount, ERROR_MINIMUM_DELEGATION ); // Validate balance ServiceProviderFactory( serviceProviderFactoryAddress ).validateAccountStakeBalance(_targetSP); emit IncreaseDelegatedStake( delegator, _targetSP, _amount ); // Return new total return delegateInfo[delegator][_targetSP]; } /** * @notice Submit request for undelegation * @param _target - address of service provider to undelegate stake from * @param _amount - amount in wei to undelegate * @return Updated total amount delegated to the service provider by delegator */ function requestUndelegateStake( address _target, uint256 _amount ) external returns (uint256) { _requireIsInitialized(); _requireClaimsManagerAddressIsSet(); require( _amount > 0, "DelegateManager: Requested undelegate stake amount must be greater than zero" ); require( !_claimPending(_target), "DelegateManager: Undelegate request not permitted for SP pending claim" ); address delegator = msg.sender; require( _delegatorExistsForSP(delegator, _target), ERROR_DELEGATOR_STAKE ); // Confirm no pending delegation request require( !_undelegateRequestIsPending(delegator), "DelegateManager: No pending lockup expected" ); // Ensure valid bounds uint256 currentlyDelegatedToSP = delegateInfo[delegator][_target]; require( _amount <= currentlyDelegatedToSP, "DelegateManager: Cannot decrease greater than currently staked for this ServiceProvider" ); // Submit updated request for sender, with target sp, undelegate amount, target expiry block uint256 lockupExpiryBlock = block.number.add(undelegateLockupDuration); _updateUndelegateStakeRequest( delegator, _target, _amount, lockupExpiryBlock ); // Update total locked for this service provider, increasing by unstake amount _updateServiceProviderLockupAmount( _target, spDelegateInfo[_target].totalLockedUpStake.add(_amount) ); emit UndelegateStakeRequested(delegator, _target, _amount, lockupExpiryBlock); return delegateInfo[delegator][_target].sub(_amount); } /** * @notice Cancel undelegation request */ function cancelUndelegateStakeRequest() external { _requireIsInitialized(); address delegator = msg.sender; // Confirm pending delegation request require( _undelegateRequestIsPending(delegator), "DelegateManager: Pending lockup expected" ); uint256 unstakeAmount = undelegateRequests[delegator].amount; address unlockFundsSP = undelegateRequests[delegator].serviceProvider; // Update total locked for this service provider, decreasing by unstake amount _updateServiceProviderLockupAmount( unlockFundsSP, spDelegateInfo[unlockFundsSP].totalLockedUpStake.sub(unstakeAmount) ); // Remove pending request _resetUndelegateStakeRequest(delegator); emit UndelegateStakeRequestCancelled(delegator, unlockFundsSP, unstakeAmount); } /** * @notice Finalize undelegation request and withdraw stake * @return New total amount currently staked after stake has been undelegated */ function undelegateStake() external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); address delegator = msg.sender; // Confirm pending delegation request require( _undelegateRequestIsPending(delegator), "DelegateManager: Pending lockup expected" ); // Confirm lockup expiry has expired require( undelegateRequests[delegator].lockupExpiryBlock <= block.number, "DelegateManager: Lockup must be expired" ); // Confirm no pending claim for this service provider require( !_claimPending(undelegateRequests[delegator].serviceProvider), "DelegateManager: Undelegate not permitted for SP pending claim" ); address serviceProvider = undelegateRequests[delegator].serviceProvider; uint256 unstakeAmount = undelegateRequests[delegator].amount; // Unstake on behalf of target service provider Staking(stakingAddress).undelegateStakeFor( serviceProvider, delegator, unstakeAmount ); // Update total delegated for SP // totalServiceProviderDelegatedStake - total amount delegated to service provider // totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider _updateDelegatorStake( delegator, serviceProvider, spDelegateInfo[serviceProvider].totalDelegatedStake.sub(unstakeAmount), delegateInfo[delegator][serviceProvider].sub(unstakeAmount), delegatorTotalStake[delegator].sub(unstakeAmount) ); require( (delegateInfo[delegator][serviceProvider] >= minDelegationAmount || delegateInfo[delegator][serviceProvider] == 0), ERROR_MINIMUM_DELEGATION ); // Remove from delegators list if no delegated stake remaining if (delegateInfo[delegator][serviceProvider] == 0) { _removeFromDelegatorsList(serviceProvider, delegator); } // Update total locked for this service provider, decreasing by unstake amount _updateServiceProviderLockupAmount( serviceProvider, spDelegateInfo[serviceProvider].totalLockedUpStake.sub(unstakeAmount) ); // Reset undelegate request _resetUndelegateStakeRequest(delegator); emit UndelegateStakeRequestEvaluated( delegator, serviceProvider, unstakeAmount ); // Return new total return delegateInfo[delegator][serviceProvider]; } /** * @notice Claim and distribute rewards to delegators and service provider as necessary * @param _serviceProvider - Provider for which rewards are being distributed * @dev Factors in service provider rewards from delegator and transfers deployer cut */ function claimRewards(address _serviceProvider) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress); // Total rewards = (balance in staking) - ((balance in sp factory) + (balance in delegate manager)) ( uint256 totalBalanceInStaking, uint256 totalBalanceInSPFactory, uint256 totalActiveFunds, uint256 totalRewards, uint256 deployerCut ) = _validateClaimRewards(spFactory, _serviceProvider); // No-op if balance is already equivalent // This case can occur if no rewards due to bound violation or all stake is locked if (totalRewards == 0) { return; } uint256 totalDelegatedStakeIncrease = _distributeDelegateRewards( _serviceProvider, totalActiveFunds, totalRewards, deployerCut, spFactory.getServiceProviderDeployerCutBase() ); // Update total delegated to this SP spDelegateInfo[_serviceProvider].totalDelegatedStake = ( spDelegateInfo[_serviceProvider].totalDelegatedStake.add(totalDelegatedStakeIncrease) ); // spRewardShare represents rewards directly allocated to service provider for their stake // Value is computed as the remainder of total minted rewards after distribution to // delegators, eliminating any potential for precision loss. uint256 spRewardShare = totalRewards.sub(totalDelegatedStakeIncrease); // Adding the newly calculated reward share to current balance uint256 newSPFactoryBalance = totalBalanceInSPFactory.add(spRewardShare); require( totalBalanceInStaking == newSPFactoryBalance.add(spDelegateInfo[_serviceProvider].totalDelegatedStake), "DelegateManager: claimRewards amount mismatch" ); spFactory.updateServiceProviderStake( _serviceProvider, newSPFactoryBalance ); } /** * @notice Reduce current stake amount * @dev Only callable by governance. Slashes service provider and delegators equally * @param _amount - amount in wei to slash * @param _slashAddress - address of service provider to slash */ function slash(uint256 _amount, address _slashAddress) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); Staking stakingContract = Staking(stakingAddress); ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress); // Amount stored in staking contract for owner uint256 totalBalanceInStakingPreSlash = stakingContract.totalStakedFor(_slashAddress); require( (totalBalanceInStakingPreSlash >= _amount), "DelegateManager: Cannot slash more than total currently staked" ); // Cancel any withdrawal request for this service provider (uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_slashAddress); if (spLockedStake > 0) { spFactory.cancelDecreaseStakeRequest(_slashAddress); } // Amount in sp factory for slash target (uint256 totalBalanceInSPFactory,,,,,) = ( spFactory.getServiceProviderDetails(_slashAddress) ); require( totalBalanceInSPFactory > 0, "DelegateManager: Service Provider stake required" ); // Decrease value in Staking contract // A value of zero slash will fail in staking, reverting this transaction stakingContract.slash(_amount, _slashAddress); uint256 totalBalanceInStakingAfterSlash = stakingContract.totalStakedFor(_slashAddress); // Emit slash event emit Slash(_slashAddress, _amount, totalBalanceInStakingAfterSlash); uint256 totalDelegatedStakeDecrease = 0; // For each delegator and deployer, recalculate new value // newStakeAmount = newStakeAmount * (oldStakeAmount / totalBalancePreSlash) for (uint256 i = 0; i < spDelegateInfo[_slashAddress].delegators.length; i++) { address delegator = spDelegateInfo[_slashAddress].delegators[i]; uint256 preSlashDelegateStake = delegateInfo[delegator][_slashAddress]; uint256 newDelegateStake = ( totalBalanceInStakingAfterSlash.mul(preSlashDelegateStake) ).div(totalBalanceInStakingPreSlash); // slashAmountForDelegator = preSlashDelegateStake - newDelegateStake; delegateInfo[delegator][_slashAddress] = ( delegateInfo[delegator][_slashAddress].sub(preSlashDelegateStake.sub(newDelegateStake)) ); // Update total stake for delegator _updateDelegatorTotalStake( delegator, delegatorTotalStake[delegator].sub(preSlashDelegateStake.sub(newDelegateStake)) ); // Update total decrease amount totalDelegatedStakeDecrease = ( totalDelegatedStakeDecrease.add(preSlashDelegateStake.sub(newDelegateStake)) ); // Check for any locked up funds for this slashed delegator // Slash overrides any pending withdrawal requests if (undelegateRequests[delegator].amount != 0) { address unstakeSP = undelegateRequests[delegator].serviceProvider; uint256 unstakeAmount = undelegateRequests[delegator].amount; // Remove pending request _updateServiceProviderLockupAmount( unstakeSP, spDelegateInfo[unstakeSP].totalLockedUpStake.sub(unstakeAmount) ); _resetUndelegateStakeRequest(delegator); } } // Update total delegated to this SP spDelegateInfo[_slashAddress].totalDelegatedStake = ( spDelegateInfo[_slashAddress].totalDelegatedStake.sub(totalDelegatedStakeDecrease) ); // Remaining decrease applied to service provider uint256 totalStakeDecrease = ( totalBalanceInStakingPreSlash.sub(totalBalanceInStakingAfterSlash) ); uint256 totalSPFactoryBalanceDecrease = ( totalStakeDecrease.sub(totalDelegatedStakeDecrease) ); spFactory.updateServiceProviderStake( _slashAddress, totalBalanceInSPFactory.sub(totalSPFactoryBalanceDecrease) ); } /** * @notice Initiate forcible removal of a delegator * @param _serviceProvider - address of service provider * @param _delegator - address of delegator */ function requestRemoveDelegator(address _serviceProvider, address _delegator) external { _requireIsInitialized(); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] == 0, "DelegateManager: Pending remove delegator request" ); require( _delegatorExistsForSP(_delegator, _serviceProvider), ERROR_DELEGATOR_STAKE ); // Update lockup removeDelegatorRequests[_serviceProvider][_delegator] = ( block.number + removeDelegatorLockupDuration ); emit RemoveDelegatorRequested( _serviceProvider, _delegator, removeDelegatorRequests[_serviceProvider][_delegator] ); } /** * @notice Cancel pending removeDelegator request * @param _serviceProvider - address of service provider * @param _delegator - address of delegator */ function cancelRemoveDelegatorRequest(address _serviceProvider, address _delegator) external { require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] != 0, "DelegateManager: No pending request" ); // Reset lockup expiry removeDelegatorRequests[_serviceProvider][_delegator] = 0; emit RemoveDelegatorRequestCancelled(_serviceProvider, _delegator); } /** * @notice Evaluate removeDelegator request * @param _serviceProvider - address of service provider * @param _delegator - address of delegator * @return Updated total amount delegated to the service provider by delegator */ function removeDelegator(address _serviceProvider, address _delegator) external { _requireIsInitialized(); _requireStakingAddressIsSet(); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] != 0, "DelegateManager: No pending request" ); // Enforce lockup expiry block require( block.number >= removeDelegatorRequests[_serviceProvider][_delegator], "DelegateManager: Lockup must be expired" ); // Enforce evaluation window for request require( block.number < removeDelegatorRequests[_serviceProvider][_delegator] + removeDelegatorEvalDuration, "DelegateManager: RemoveDelegator evaluation window expired" ); uint256 unstakeAmount = delegateInfo[_delegator][_serviceProvider]; // Unstake on behalf of target service provider Staking(stakingAddress).undelegateStakeFor( _serviceProvider, _delegator, unstakeAmount ); // Update total delegated for SP // totalServiceProviderDelegatedStake - total amount delegated to service provider // totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider _updateDelegatorStake( _delegator, _serviceProvider, spDelegateInfo[_serviceProvider].totalDelegatedStake.sub(unstakeAmount), delegateInfo[_delegator][_serviceProvider].sub(unstakeAmount), delegatorTotalStake[_delegator].sub(unstakeAmount) ); if ( _undelegateRequestIsPending(_delegator) && undelegateRequests[_delegator].serviceProvider == _serviceProvider ) { // Remove pending request information _updateServiceProviderLockupAmount( _serviceProvider, spDelegateInfo[_serviceProvider].totalLockedUpStake.sub(undelegateRequests[_delegator].amount) ); _resetUndelegateStakeRequest(_delegator); } // Remove from list of delegators _removeFromDelegatorsList(_serviceProvider, _delegator); // Reset lockup expiry removeDelegatorRequests[_serviceProvider][_delegator] = 0; emit RemoveDelegatorRequestEvaluated(_serviceProvider, _delegator, unstakeAmount); } /** * @notice Update duration for undelegate request lockup * @param _duration - new lockup duration */ function updateUndelegateLockupDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateUndelegateLockupDuration(_duration); emit UndelegateLockupDurationUpdated(_duration); } /** * @notice Update maximum delegators allowed * @param _maxDelegators - new max delegators */ function updateMaxDelegators(uint256 _maxDelegators) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); maxDelegators = _maxDelegators; emit MaxDelegatorsUpdated(_maxDelegators); } /** * @notice Update minimum delegation amount * @param _minDelegationAmount - min new min delegation amount */ function updateMinDelegationAmount(uint256 _minDelegationAmount) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); minDelegationAmount = _minDelegationAmount; emit MinDelegationUpdated(_minDelegationAmount); } /** * @notice Update remove delegator lockup duration * @param _duration - new lockup duration */ function updateRemoveDelegatorLockupDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateRemoveDelegatorLockupDuration(_duration); emit RemoveDelegatorLockupDurationUpdated(_duration); } /** * @notice Update remove delegator evaluation window duration * @param _duration - new window duration */ function updateRemoveDelegatorEvalDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); removeDelegatorEvalDuration = _duration; emit RemoveDelegatorEvalDurationUpdated(_duration); } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); governanceAddress = _governanceAddress; emit GovernanceAddressUpdated(_governanceAddress); } /** * @notice Set the Staking address * @dev Only callable by Governance address * @param _stakingAddress - address for new Staking contract */ function setStakingAddress(address _stakingAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); stakingAddress = _stakingAddress; emit StakingAddressUpdated(_stakingAddress); } /** * @notice Set the ServiceProviderFactory address * @dev Only callable by Governance address * @param _spFactory - address for new ServiceProviderFactory contract */ function setServiceProviderFactoryAddress(address _spFactory) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); serviceProviderFactoryAddress = _spFactory; emit ServiceProviderFactoryAddressUpdated(_spFactory); } /** * @notice Set the ClaimsManager address * @dev Only callable by Governance address * @param _claimsManagerAddress - address for new ClaimsManager contract */ function setClaimsManagerAddress(address _claimsManagerAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); claimsManagerAddress = _claimsManagerAddress; emit ClaimsManagerAddressUpdated(_claimsManagerAddress); } // ========================================= View Functions ========================================= /** * @notice Get list of delegators for a given service provider * @param _sp - service provider address */ function getDelegatorsList(address _sp) external view returns (address[] memory) { _requireIsInitialized(); return spDelegateInfo[_sp].delegators; } /** * @notice Get total delegation from a given address * @param _delegator - delegator address */ function getTotalDelegatorStake(address _delegator) external view returns (uint256) { _requireIsInitialized(); return delegatorTotalStake[_delegator]; } /// @notice Get total amount delegated to a service provider function getTotalDelegatedToServiceProvider(address _sp) external view returns (uint256) { _requireIsInitialized(); return spDelegateInfo[_sp].totalDelegatedStake; } /// @notice Get total delegated stake locked up for a service provider function getTotalLockedDelegationForServiceProvider(address _sp) external view returns (uint256) { _requireIsInitialized(); return spDelegateInfo[_sp].totalLockedUpStake; } /// @notice Get total currently staked for a delegator, for a given service provider function getDelegatorStakeForServiceProvider(address _delegator, address _serviceProvider) external view returns (uint256) { _requireIsInitialized(); return delegateInfo[_delegator][_serviceProvider]; } /** * @notice Get status of pending undelegate request for a given address * @param _delegator - address of the delegator */ function getPendingUndelegateRequest(address _delegator) external view returns (address target, uint256 amount, uint256 lockupExpiryBlock) { _requireIsInitialized(); UndelegateStakeRequest memory req = undelegateRequests[_delegator]; return (req.serviceProvider, req.amount, req.lockupExpiryBlock); } /** * @notice Get status of pending remove delegator request for a given address * @param _serviceProvider - address of the service provider * @param _delegator - address of the delegator * @return - current lockup expiry block for remove delegator request */ function getPendingRemoveDelegatorRequest( address _serviceProvider, address _delegator ) external view returns (uint256) { _requireIsInitialized(); return removeDelegatorRequests[_serviceProvider][_delegator]; } /// @notice Get current undelegate lockup duration function getUndelegateLockupDuration() external view returns (uint256) { _requireIsInitialized(); return undelegateLockupDuration; } /// @notice Current maximum delegators function getMaxDelegators() external view returns (uint256) { _requireIsInitialized(); return maxDelegators; } /// @notice Get minimum delegation amount function getMinDelegationAmount() external view returns (uint256) { _requireIsInitialized(); return minDelegationAmount; } /// @notice Get the duration for remove delegator request lockup function getRemoveDelegatorLockupDuration() external view returns (uint256) { _requireIsInitialized(); return removeDelegatorLockupDuration; } /// @notice Get the duration for evaluation of remove delegator operations function getRemoveDelegatorEvalDuration() external view returns (uint256) { _requireIsInitialized(); return removeDelegatorEvalDuration; } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the ServiceProviderFactory address function getServiceProviderFactoryAddress() external view returns (address) { _requireIsInitialized(); return serviceProviderFactoryAddress; } /// @notice Get the ClaimsManager address function getClaimsManagerAddress() external view returns (address) { _requireIsInitialized(); return claimsManagerAddress; } /// @notice Get the Staking address function getStakingAddress() external view returns (address) { _requireIsInitialized(); return stakingAddress; } // ========================================= Internal functions ========================================= /** * @notice Helper function for claimRewards to get balances from Staking contract and do validation * @param spFactory - reference to ServiceProviderFactory contract * @param _serviceProvider - address for which rewards are being claimed * @return (totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, spLockedStake, totalRewards, deployerCut) */ function _validateClaimRewards(ServiceProviderFactory spFactory, address _serviceProvider) internal returns ( uint256 totalBalanceInStaking, uint256 totalBalanceInSPFactory, uint256 totalActiveFunds, uint256 totalRewards, uint256 deployerCut ) { // Account for any pending locked up stake for the service provider (uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_serviceProvider); uint256 totalLockedUpStake = ( spDelegateInfo[_serviceProvider].totalLockedUpStake.add(spLockedStake) ); // Process claim for msg.sender // Total locked parameter is equal to delegate locked up stake + service provider locked up stake uint256 mintedRewards = ClaimsManager(claimsManagerAddress).processClaim( _serviceProvider, totalLockedUpStake ); // Amount stored in staking contract for owner totalBalanceInStaking = Staking(stakingAddress).totalStakedFor(_serviceProvider); // Amount in sp factory for claimer ( totalBalanceInSPFactory, deployerCut, ,,, ) = spFactory.getServiceProviderDetails(_serviceProvider); // Require active stake to claim any rewards // Amount in delegate manager staked to service provider uint256 totalBalanceOutsideStaking = ( totalBalanceInSPFactory.add(spDelegateInfo[_serviceProvider].totalDelegatedStake) ); totalActiveFunds = totalBalanceOutsideStaking.sub(totalLockedUpStake); require( mintedRewards == totalBalanceInStaking.sub(totalBalanceOutsideStaking), "DelegateManager: Reward amount mismatch" ); // Emit claim event emit Claim(_serviceProvider, totalRewards, totalBalanceInStaking); return ( totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, mintedRewards, deployerCut ); } /** * @notice Perform state updates when a delegate stake has changed * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @param _totalServiceProviderDelegatedStake - total delegated to this service provider * @param _totalStakedForSpFromDelegator - total delegated to this service provider by delegator * @param _totalDelegatorStake - total delegated from this delegator address */ function _updateDelegatorStake( address _delegator, address _serviceProvider, uint256 _totalServiceProviderDelegatedStake, uint256 _totalStakedForSpFromDelegator, uint256 _totalDelegatorStake ) internal { // Update total delegated for SP spDelegateInfo[_serviceProvider].totalDelegatedStake = _totalServiceProviderDelegatedStake; // Update amount staked from this delegator to targeted service provider delegateInfo[_delegator][_serviceProvider] = _totalStakedForSpFromDelegator; // Update total delegated from this delegator _updateDelegatorTotalStake(_delegator, _totalDelegatorStake); } /** * @notice Reset pending undelegate stake request * @param _delegator - address of delegator */ function _resetUndelegateStakeRequest(address _delegator) internal { _updateUndelegateStakeRequest(_delegator, address(0), 0, 0); } /** * @notice Perform updates when undelegate request state has changed * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @param _amount - amount being undelegated * @param _lockupExpiryBlock - block at which stake can be undelegated */ function _updateUndelegateStakeRequest( address _delegator, address _serviceProvider, uint256 _amount, uint256 _lockupExpiryBlock ) internal { // Update lockup information undelegateRequests[_delegator] = UndelegateStakeRequest({ lockupExpiryBlock: _lockupExpiryBlock, amount: _amount, serviceProvider: _serviceProvider }); } /** * @notice Update total amount delegated from an address * @param _delegator - address of service provider * @param _amount - updated delegator total */ function _updateDelegatorTotalStake(address _delegator, uint256 _amount) internal { delegatorTotalStake[_delegator] = _amount; } /** * @notice Update amount currently locked up for this service provider * @param _serviceProvider - address of service provider * @param _updatedLockupAmount - updated lock up amount */ function _updateServiceProviderLockupAmount( address _serviceProvider, uint256 _updatedLockupAmount ) internal { spDelegateInfo[_serviceProvider].totalLockedUpStake = _updatedLockupAmount; } function _removeFromDelegatorsList(address _serviceProvider, address _delegator) internal { for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) { if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) { // Overwrite and shrink delegators list spDelegateInfo[_serviceProvider].delegators[i] = spDelegateInfo[_serviceProvider].delegators[spDelegateInfo[_serviceProvider].delegators.length - 1]; spDelegateInfo[_serviceProvider].delegators.length--; break; } } } /** * @notice Helper function to distribute rewards to any delegators * @param _sp - service provider account tracked in staking * @param _totalActiveFunds - total funds minus any locked stake * @param _totalRewards - total rewaards generated in this round * @param _deployerCut - service provider cut of delegate rewards, defined as deployerCut / deployerCutBase * @param _deployerCutBase - denominator value for calculating service provider cut as a % * @return (totalBalanceInStaking, totalBalanceInSPFactory, totalBalanceOutsideStaking) */ function _distributeDelegateRewards( address _sp, uint256 _totalActiveFunds, uint256 _totalRewards, uint256 _deployerCut, uint256 _deployerCutBase ) internal returns (uint256 totalDelegatedStakeIncrease) { // Traverse all delegates and calculate their rewards // As each delegate reward is calculated, increment SP cut reward accordingly for (uint256 i = 0; i < spDelegateInfo[_sp].delegators.length; i++) { address delegator = spDelegateInfo[_sp].delegators[i]; uint256 delegateStakeToSP = delegateInfo[delegator][_sp]; // Subtract any locked up stake if (undelegateRequests[delegator].serviceProvider == _sp) { delegateStakeToSP = delegateStakeToSP.sub(undelegateRequests[delegator].amount); } // Calculate rewards by ((delegateStakeToSP / totalActiveFunds) * totalRewards) uint256 rewardsPriorToSPCut = ( delegateStakeToSP.mul(_totalRewards) ).div(_totalActiveFunds); // Multiply by deployer cut fraction to calculate reward for SP // Operation constructed to perform all multiplication prior to division // uint256 spDeployerCut = (rewardsPriorToSPCut * deployerCut ) / (deployerCutBase); // = ((delegateStakeToSP * totalRewards) / totalActiveFunds) * deployerCut ) / (deployerCutBase); // = ((delegateStakeToSP * totalRewards * deployerCut) / totalActiveFunds ) / (deployerCutBase); // = (delegateStakeToSP * totalRewards * deployerCut) / (deployerCutBase * totalActiveFunds); uint256 spDeployerCut = ( (delegateStakeToSP.mul(_totalRewards)).mul(_deployerCut) ).div( _totalActiveFunds.mul(_deployerCutBase) ); // Increase total delegate reward in DelegateManager // Subtract SP reward from rewards to calculate delegate reward // delegateReward = rewardsPriorToSPCut - spDeployerCut; delegateInfo[delegator][_sp] = ( delegateInfo[delegator][_sp].add(rewardsPriorToSPCut.sub(spDeployerCut)) ); // Update total for this delegator _updateDelegatorTotalStake( delegator, delegatorTotalStake[delegator].add(rewardsPriorToSPCut.sub(spDeployerCut)) ); totalDelegatedStakeIncrease = ( totalDelegatedStakeIncrease.add(rewardsPriorToSPCut.sub(spDeployerCut)) ); } return (totalDelegatedStakeIncrease); } /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "DelegateManager: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } /** * @notice Set the remove delegator lockup duration after validating against governance * @param _duration - Incoming remove delegator duration value */ function _updateRemoveDelegatorLockupDuration(uint256 _duration) internal { Governance governance = Governance(governanceAddress); require( _duration > governance.getVotingPeriod() + governance.getExecutionDelay(), "DelegateManager: removeDelegatorLockupDuration duration must be greater than governance votingPeriod + executionDelay" ); removeDelegatorLockupDuration = _duration; } /** * @notice Set the undelegate lockup duration after validating against governance * @param _duration - Incoming undelegate lockup duration value */ function _updateUndelegateLockupDuration(uint256 _duration) internal { Governance governance = Governance(governanceAddress); require( _duration > governance.getVotingPeriod() + governance.getExecutionDelay(), "DelegateManager: undelegateLockupDuration duration must be greater than governance votingPeriod + executionDelay" ); undelegateLockupDuration = _duration; } /** * @notice Returns if delegator has delegated to a service provider * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @return boolean indicating whether delegator exists for service provider */ function _delegatorExistsForSP( address _delegator, address _serviceProvider ) internal view returns (bool) { for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) { if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) { return true; } } // Not found return false; } /** * @notice Determine if a claim is pending for this service provider * @param _sp - address of service provider * @return boolean indicating whether a claim is pending */ function _claimPending(address _sp) internal view returns (bool) { ClaimsManager claimsManager = ClaimsManager(claimsManagerAddress); return claimsManager.claimPending(_sp); } /** * @notice Determine if a decrease request has been initiated * @param _delegator - address of delegator * @return boolean indicating whether a decrease request is pending */ function _undelegateRequestIsPending(address _delegator) internal view returns (bool) { return ( (undelegateRequests[_delegator].lockupExpiryBlock != 0) && (undelegateRequests[_delegator].amount != 0) && (undelegateRequests[_delegator].serviceProvider != address(0)) ); } // ========================================= Private Functions ========================================= function _requireStakingAddressIsSet() private view { require( stakingAddress != address(0x00), "DelegateManager: stakingAddress is not set" ); } function _requireServiceProviderFactoryAddressIsSet() private view { require( serviceProviderFactoryAddress != address(0x00), "DelegateManager: serviceProviderFactoryAddress is not set" ); } function _requireClaimsManagerAddressIsSet() private view { require( claimsManagerAddress != address(0x00), "DelegateManager: claimsManagerAddress is not set" ); } }
contract DelegateManager is InitializableV2 { using SafeMath for uint256; string private constant ERROR_ONLY_GOVERNANCE = ( "DelegateManager: Only callable by Governance contract" ); string private constant ERROR_MINIMUM_DELEGATION = ( "DelegateManager: Minimum delegation amount required" ); string private constant ERROR_ONLY_SP_GOVERNANCE = ( "DelegateManager: Only callable by target SP or governance" ); string private constant ERROR_DELEGATOR_STAKE = ( "DelegateManager: Delegator must be staked for SP" ); address private governanceAddress; address private stakingAddress; address private serviceProviderFactoryAddress; address private claimsManagerAddress; /** * Period in blocks an undelegate operation is delayed. * The undelegate operation speed bump is to prevent a delegator from * attempting to remove their delegation in anticipation of a slash. * @notice Must be greater than governance votingPeriod + executionDelay */ uint256 private undelegateLockupDuration; /// @notice Maximum number of delegators a single account can handle uint256 private maxDelegators; /// @notice Minimum amount of delegation allowed uint256 private minDelegationAmount; /** * Lockup duration for a remove delegator request. * The remove delegator speed bump is to prevent a service provider from maliciously * removing a delegator prior to the evaluation of a proposal. * @notice Must be greater than governance votingPeriod + executionDelay */ uint256 private removeDelegatorLockupDuration; /** * Evaluation period for a remove delegator request * @notice added to expiry block calculated for removeDelegatorLockupDuration */ uint256 private removeDelegatorEvalDuration; // Staking contract ref ERC20Mintable private audiusToken; // Struct representing total delegated to SP and list of delegators struct ServiceProviderDelegateInfo { uint256 totalDelegatedStake; uint256 totalLockedUpStake; address[] delegators; } // Data structures for lockup during withdrawal struct UndelegateStakeRequest { address serviceProvider; uint256 amount; uint256 lockupExpiryBlock; } // Service provider address -> ServiceProviderDelegateInfo mapping (address => ServiceProviderDelegateInfo) private spDelegateInfo; // Delegator stake by address delegated to // delegator -> (service provider -> delegatedStake) mapping (address => mapping(address => uint256)) private delegateInfo; // Delegator stake total by address // delegator -> (totalDelegated) // Note - delegator properties are maintained in a mapping instead of struct // in order to facilitate extensibility in the future. mapping (address => uint256) private delegatorTotalStake; // Requester to pending undelegate request mapping (address => UndelegateStakeRequest) private undelegateRequests; // Pending remove delegator requests // service provider -> (delegator -> lockupExpiryBlock) mapping (address => mapping (address => uint256)) private removeDelegatorRequests; event IncreaseDelegatedStake( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _increaseAmount ); event UndelegateStakeRequested( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount, uint256 _lockupExpiryBlock ); event UndelegateStakeRequestCancelled( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount ); event UndelegateStakeRequestEvaluated( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount ); event Claim( address indexed _claimer, uint256 indexed _rewards, uint256 indexed _newTotal ); event Slash( address indexed _target, uint256 indexed _amount, uint256 indexed _newTotal ); event RemoveDelegatorRequested( address indexed _serviceProvider, address indexed _delegator, uint256 indexed _lockupExpiryBlock ); event RemoveDelegatorRequestCancelled( address indexed _serviceProvider, address indexed _delegator ); event RemoveDelegatorRequestEvaluated( address indexed _serviceProvider, address indexed _delegator, uint256 indexed _unstakedAmount ); event MaxDelegatorsUpdated(uint256 indexed _maxDelegators); event MinDelegationUpdated(uint256 indexed _minDelegationAmount); event UndelegateLockupDurationUpdated(uint256 indexed _undelegateLockupDuration); event GovernanceAddressUpdated(address indexed _newGovernanceAddress); event StakingAddressUpdated(address indexed _newStakingAddress); event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress); event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress); event RemoveDelegatorLockupDurationUpdated(uint256 indexed _removeDelegatorLockupDuration); event RemoveDelegatorEvalDurationUpdated(uint256 indexed _removeDelegatorEvalDuration); /** * @notice Function to initialize the contract * @dev stakingAddress must be initialized separately after Staking contract is deployed * @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed * @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed * @param _tokenAddress - address of ERC20 token that will be claimed * @param _governanceAddress - Governance proxy address */ function initialize ( address _tokenAddress, address _governanceAddress, uint256 _undelegateLockupDuration ) public initializer { _updateGovernanceAddress(_governanceAddress); audiusToken = ERC20Mintable(_tokenAddress); maxDelegators = 175; // Default minimum delegation amount set to 100AUD minDelegationAmount = 100 * 10**uint256(18); InitializableV2.initialize(); _updateUndelegateLockupDuration(_undelegateLockupDuration); // 1 week = 168hrs * 60 min/hr * 60 sec/min / ~13 sec/block = 46523 blocks _updateRemoveDelegatorLockupDuration(46523); // 24hr * 60min/hr * 60sec/min / ~13 sec/block = 6646 blocks removeDelegatorEvalDuration = 6646; } /** * @notice Allow a delegator to delegate stake to a service provider * @param _targetSP - address of service provider to delegate to * @param _amount - amount in wei to delegate * @return Updated total amount delegated to the service provider by delegator */ function delegateStake( address _targetSP, uint256 _amount ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); require( !_claimPending(_targetSP), "DelegateManager: Delegation not permitted for SP pending claim" ); address delegator = msg.sender; Staking stakingContract = Staking(stakingAddress); // Stake on behalf of target service provider stakingContract.delegateStakeFor( _targetSP, delegator, _amount ); // Update list of delegators to SP if necessary if (!_delegatorExistsForSP(delegator, _targetSP)) { // If not found, update list of delegates spDelegateInfo[_targetSP].delegators.push(delegator); require( spDelegateInfo[_targetSP].delegators.length <= maxDelegators, "DelegateManager: Maximum delegators exceeded" ); } // Update following values in storage through helper // totalServiceProviderDelegatedStake = current sp total + new amount, // totalStakedForSpFromDelegator = current delegator total for sp + new amount, // totalDelegatorStake = current delegator total + new amount _updateDelegatorStake( delegator, _targetSP, spDelegateInfo[_targetSP].totalDelegatedStake.add(_amount), delegateInfo[delegator][_targetSP].add(_amount), delegatorTotalStake[delegator].add(_amount) ); require( delegateInfo[delegator][_targetSP] >= minDelegationAmount, ERROR_MINIMUM_DELEGATION ); // Validate balance ServiceProviderFactory( serviceProviderFactoryAddress ).validateAccountStakeBalance(_targetSP); emit IncreaseDelegatedStake( delegator, _targetSP, _amount ); // Return new total return delegateInfo[delegator][_targetSP]; } /** * @notice Submit request for undelegation * @param _target - address of service provider to undelegate stake from * @param _amount - amount in wei to undelegate * @return Updated total amount delegated to the service provider by delegator */ function requestUndelegateStake( address _target, uint256 _amount ) external returns (uint256) { _requireIsInitialized(); _requireClaimsManagerAddressIsSet(); require( _amount > 0, "DelegateManager: Requested undelegate stake amount must be greater than zero" ); require( !_claimPending(_target), "DelegateManager: Undelegate request not permitted for SP pending claim" ); address delegator = msg.sender; require( _delegatorExistsForSP(delegator, _target), ERROR_DELEGATOR_STAKE ); // Confirm no pending delegation request require( !_undelegateRequestIsPending(delegator), "DelegateManager: No pending lockup expected" ); // Ensure valid bounds uint256 currentlyDelegatedToSP = delegateInfo[delegator][_target]; require( _amount <= currentlyDelegatedToSP, "DelegateManager: Cannot decrease greater than currently staked for this ServiceProvider" ); // Submit updated request for sender, with target sp, undelegate amount, target expiry block uint256 lockupExpiryBlock = block.number.add(undelegateLockupDuration); _updateUndelegateStakeRequest( delegator, _target, _amount, lockupExpiryBlock ); // Update total locked for this service provider, increasing by unstake amount _updateServiceProviderLockupAmount( _target, spDelegateInfo[_target].totalLockedUpStake.add(_amount) ); emit UndelegateStakeRequested(delegator, _target, _amount, lockupExpiryBlock); return delegateInfo[delegator][_target].sub(_amount); } /** * @notice Cancel undelegation request */ function cancelUndelegateStakeRequest() external { _requireIsInitialized(); address delegator = msg.sender; // Confirm pending delegation request require( _undelegateRequestIsPending(delegator), "DelegateManager: Pending lockup expected" ); uint256 unstakeAmount = undelegateRequests[delegator].amount; address unlockFundsSP = undelegateRequests[delegator].serviceProvider; // Update total locked for this service provider, decreasing by unstake amount _updateServiceProviderLockupAmount( unlockFundsSP, spDelegateInfo[unlockFundsSP].totalLockedUpStake.sub(unstakeAmount) ); // Remove pending request _resetUndelegateStakeRequest(delegator); emit UndelegateStakeRequestCancelled(delegator, unlockFundsSP, unstakeAmount); } /** * @notice Finalize undelegation request and withdraw stake * @return New total amount currently staked after stake has been undelegated */ function undelegateStake() external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); address delegator = msg.sender; // Confirm pending delegation request require( _undelegateRequestIsPending(delegator), "DelegateManager: Pending lockup expected" ); // Confirm lockup expiry has expired require( undelegateRequests[delegator].lockupExpiryBlock <= block.number, "DelegateManager: Lockup must be expired" ); // Confirm no pending claim for this service provider require( !_claimPending(undelegateRequests[delegator].serviceProvider), "DelegateManager: Undelegate not permitted for SP pending claim" ); address serviceProvider = undelegateRequests[delegator].serviceProvider; uint256 unstakeAmount = undelegateRequests[delegator].amount; // Unstake on behalf of target service provider Staking(stakingAddress).undelegateStakeFor( serviceProvider, delegator, unstakeAmount ); // Update total delegated for SP // totalServiceProviderDelegatedStake - total amount delegated to service provider // totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider _updateDelegatorStake( delegator, serviceProvider, spDelegateInfo[serviceProvider].totalDelegatedStake.sub(unstakeAmount), delegateInfo[delegator][serviceProvider].sub(unstakeAmount), delegatorTotalStake[delegator].sub(unstakeAmount) ); require( (delegateInfo[delegator][serviceProvider] >= minDelegationAmount || delegateInfo[delegator][serviceProvider] == 0), ERROR_MINIMUM_DELEGATION ); // Remove from delegators list if no delegated stake remaining if (delegateInfo[delegator][serviceProvider] == 0) { _removeFromDelegatorsList(serviceProvider, delegator); } // Update total locked for this service provider, decreasing by unstake amount _updateServiceProviderLockupAmount( serviceProvider, spDelegateInfo[serviceProvider].totalLockedUpStake.sub(unstakeAmount) ); // Reset undelegate request _resetUndelegateStakeRequest(delegator); emit UndelegateStakeRequestEvaluated( delegator, serviceProvider, unstakeAmount ); // Return new total return delegateInfo[delegator][serviceProvider]; } /** * @notice Claim and distribute rewards to delegators and service provider as necessary * @param _serviceProvider - Provider for which rewards are being distributed * @dev Factors in service provider rewards from delegator and transfers deployer cut */ function claimRewards(address _serviceProvider) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress); // Total rewards = (balance in staking) - ((balance in sp factory) + (balance in delegate manager)) ( uint256 totalBalanceInStaking, uint256 totalBalanceInSPFactory, uint256 totalActiveFunds, uint256 totalRewards, uint256 deployerCut ) = _validateClaimRewards(spFactory, _serviceProvider); // No-op if balance is already equivalent // This case can occur if no rewards due to bound violation or all stake is locked if (totalRewards == 0) { return; } uint256 totalDelegatedStakeIncrease = _distributeDelegateRewards( _serviceProvider, totalActiveFunds, totalRewards, deployerCut, spFactory.getServiceProviderDeployerCutBase() ); // Update total delegated to this SP spDelegateInfo[_serviceProvider].totalDelegatedStake = ( spDelegateInfo[_serviceProvider].totalDelegatedStake.add(totalDelegatedStakeIncrease) ); // spRewardShare represents rewards directly allocated to service provider for their stake // Value is computed as the remainder of total minted rewards after distribution to // delegators, eliminating any potential for precision loss. uint256 spRewardShare = totalRewards.sub(totalDelegatedStakeIncrease); // Adding the newly calculated reward share to current balance uint256 newSPFactoryBalance = totalBalanceInSPFactory.add(spRewardShare); require( totalBalanceInStaking == newSPFactoryBalance.add(spDelegateInfo[_serviceProvider].totalDelegatedStake), "DelegateManager: claimRewards amount mismatch" ); spFactory.updateServiceProviderStake( _serviceProvider, newSPFactoryBalance ); } /** * @notice Reduce current stake amount * @dev Only callable by governance. Slashes service provider and delegators equally * @param _amount - amount in wei to slash * @param _slashAddress - address of service provider to slash */ function slash(uint256 _amount, address _slashAddress) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); Staking stakingContract = Staking(stakingAddress); ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress); // Amount stored in staking contract for owner uint256 totalBalanceInStakingPreSlash = stakingContract.totalStakedFor(_slashAddress); require( (totalBalanceInStakingPreSlash >= _amount), "DelegateManager: Cannot slash more than total currently staked" ); // Cancel any withdrawal request for this service provider (uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_slashAddress); if (spLockedStake > 0) { spFactory.cancelDecreaseStakeRequest(_slashAddress); } // Amount in sp factory for slash target (uint256 totalBalanceInSPFactory,,,,,) = ( spFactory.getServiceProviderDetails(_slashAddress) ); require( totalBalanceInSPFactory > 0, "DelegateManager: Service Provider stake required" ); // Decrease value in Staking contract // A value of zero slash will fail in staking, reverting this transaction stakingContract.slash(_amount, _slashAddress); uint256 totalBalanceInStakingAfterSlash = stakingContract.totalStakedFor(_slashAddress); // Emit slash event emit Slash(_slashAddress, _amount, totalBalanceInStakingAfterSlash); uint256 totalDelegatedStakeDecrease = 0; // For each delegator and deployer, recalculate new value // newStakeAmount = newStakeAmount * (oldStakeAmount / totalBalancePreSlash) for (uint256 i = 0; i < spDelegateInfo[_slashAddress].delegators.length; i++) { address delegator = spDelegateInfo[_slashAddress].delegators[i]; uint256 preSlashDelegateStake = delegateInfo[delegator][_slashAddress]; uint256 newDelegateStake = ( totalBalanceInStakingAfterSlash.mul(preSlashDelegateStake) ).div(totalBalanceInStakingPreSlash); // slashAmountForDelegator = preSlashDelegateStake - newDelegateStake; delegateInfo[delegator][_slashAddress] = ( delegateInfo[delegator][_slashAddress].sub(preSlashDelegateStake.sub(newDelegateStake)) ); // Update total stake for delegator _updateDelegatorTotalStake( delegator, delegatorTotalStake[delegator].sub(preSlashDelegateStake.sub(newDelegateStake)) ); // Update total decrease amount totalDelegatedStakeDecrease = ( totalDelegatedStakeDecrease.add(preSlashDelegateStake.sub(newDelegateStake)) ); // Check for any locked up funds for this slashed delegator // Slash overrides any pending withdrawal requests if (undelegateRequests[delegator].amount != 0) { address unstakeSP = undelegateRequests[delegator].serviceProvider; uint256 unstakeAmount = undelegateRequests[delegator].amount; // Remove pending request _updateServiceProviderLockupAmount( unstakeSP, spDelegateInfo[unstakeSP].totalLockedUpStake.sub(unstakeAmount) ); _resetUndelegateStakeRequest(delegator); } } // Update total delegated to this SP spDelegateInfo[_slashAddress].totalDelegatedStake = ( spDelegateInfo[_slashAddress].totalDelegatedStake.sub(totalDelegatedStakeDecrease) ); // Remaining decrease applied to service provider uint256 totalStakeDecrease = ( totalBalanceInStakingPreSlash.sub(totalBalanceInStakingAfterSlash) ); uint256 totalSPFactoryBalanceDecrease = ( totalStakeDecrease.sub(totalDelegatedStakeDecrease) ); spFactory.updateServiceProviderStake( _slashAddress, totalBalanceInSPFactory.sub(totalSPFactoryBalanceDecrease) ); } /** * @notice Initiate forcible removal of a delegator * @param _serviceProvider - address of service provider * @param _delegator - address of delegator */ function requestRemoveDelegator(address _serviceProvider, address _delegator) external { _requireIsInitialized(); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] == 0, "DelegateManager: Pending remove delegator request" ); require( _delegatorExistsForSP(_delegator, _serviceProvider), ERROR_DELEGATOR_STAKE ); // Update lockup removeDelegatorRequests[_serviceProvider][_delegator] = ( block.number + removeDelegatorLockupDuration ); emit RemoveDelegatorRequested( _serviceProvider, _delegator, removeDelegatorRequests[_serviceProvider][_delegator] ); } /** * @notice Cancel pending removeDelegator request * @param _serviceProvider - address of service provider * @param _delegator - address of delegator */ function cancelRemoveDelegatorRequest(address _serviceProvider, address _delegator) external { require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] != 0, "DelegateManager: No pending request" ); // Reset lockup expiry removeDelegatorRequests[_serviceProvider][_delegator] = 0; emit RemoveDelegatorRequestCancelled(_serviceProvider, _delegator); } /** * @notice Evaluate removeDelegator request * @param _serviceProvider - address of service provider * @param _delegator - address of delegator * @return Updated total amount delegated to the service provider by delegator */ function removeDelegator(address _serviceProvider, address _delegator) external { _requireIsInitialized(); _requireStakingAddressIsSet(); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] != 0, "DelegateManager: No pending request" ); // Enforce lockup expiry block require( block.number >= removeDelegatorRequests[_serviceProvider][_delegator], "DelegateManager: Lockup must be expired" ); // Enforce evaluation window for request require( block.number < removeDelegatorRequests[_serviceProvider][_delegator] + removeDelegatorEvalDuration, "DelegateManager: RemoveDelegator evaluation window expired" ); uint256 unstakeAmount = delegateInfo[_delegator][_serviceProvider]; // Unstake on behalf of target service provider Staking(stakingAddress).undelegateStakeFor( _serviceProvider, _delegator, unstakeAmount ); // Update total delegated for SP // totalServiceProviderDelegatedStake - total amount delegated to service provider // totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider _updateDelegatorStake( _delegator, _serviceProvider, spDelegateInfo[_serviceProvider].totalDelegatedStake.sub(unstakeAmount), delegateInfo[_delegator][_serviceProvider].sub(unstakeAmount), delegatorTotalStake[_delegator].sub(unstakeAmount) ); if ( _undelegateRequestIsPending(_delegator) && undelegateRequests[_delegator].serviceProvider == _serviceProvider ) { // Remove pending request information _updateServiceProviderLockupAmount( _serviceProvider, spDelegateInfo[_serviceProvider].totalLockedUpStake.sub(undelegateRequests[_delegator].amount) ); _resetUndelegateStakeRequest(_delegator); } // Remove from list of delegators _removeFromDelegatorsList(_serviceProvider, _delegator); // Reset lockup expiry removeDelegatorRequests[_serviceProvider][_delegator] = 0; emit RemoveDelegatorRequestEvaluated(_serviceProvider, _delegator, unstakeAmount); } /** * @notice Update duration for undelegate request lockup * @param _duration - new lockup duration */ function updateUndelegateLockupDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateUndelegateLockupDuration(_duration); emit UndelegateLockupDurationUpdated(_duration); } /** * @notice Update maximum delegators allowed * @param _maxDelegators - new max delegators */ function updateMaxDelegators(uint256 _maxDelegators) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); maxDelegators = _maxDelegators; emit MaxDelegatorsUpdated(_maxDelegators); } /** * @notice Update minimum delegation amount * @param _minDelegationAmount - min new min delegation amount */ function updateMinDelegationAmount(uint256 _minDelegationAmount) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); minDelegationAmount = _minDelegationAmount; emit MinDelegationUpdated(_minDelegationAmount); } /** * @notice Update remove delegator lockup duration * @param _duration - new lockup duration */ function updateRemoveDelegatorLockupDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateRemoveDelegatorLockupDuration(_duration); emit RemoveDelegatorLockupDurationUpdated(_duration); } /** * @notice Update remove delegator evaluation window duration * @param _duration - new window duration */ function updateRemoveDelegatorEvalDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); removeDelegatorEvalDuration = _duration; emit RemoveDelegatorEvalDurationUpdated(_duration); } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); governanceAddress = _governanceAddress; emit GovernanceAddressUpdated(_governanceAddress); } /** * @notice Set the Staking address * @dev Only callable by Governance address * @param _stakingAddress - address for new Staking contract */ function setStakingAddress(address _stakingAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); stakingAddress = _stakingAddress; emit StakingAddressUpdated(_stakingAddress); } /** * @notice Set the ServiceProviderFactory address * @dev Only callable by Governance address * @param _spFactory - address for new ServiceProviderFactory contract */ function setServiceProviderFactoryAddress(address _spFactory) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); serviceProviderFactoryAddress = _spFactory; emit ServiceProviderFactoryAddressUpdated(_spFactory); } /** * @notice Set the ClaimsManager address * @dev Only callable by Governance address * @param _claimsManagerAddress - address for new ClaimsManager contract */ function setClaimsManagerAddress(address _claimsManagerAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); claimsManagerAddress = _claimsManagerAddress; emit ClaimsManagerAddressUpdated(_claimsManagerAddress); } // ========================================= View Functions ========================================= /** * @notice Get list of delegators for a given service provider * @param _sp - service provider address */ function getDelegatorsList(address _sp) external view returns (address[] memory) { _requireIsInitialized(); return spDelegateInfo[_sp].delegators; } /** * @notice Get total delegation from a given address * @param _delegator - delegator address */ function getTotalDelegatorStake(address _delegator) external view returns (uint256) { _requireIsInitialized(); return delegatorTotalStake[_delegator]; } /// @notice Get total amount delegated to a service provider function getTotalDelegatedToServiceProvider(address _sp) external view returns (uint256) { _requireIsInitialized(); return spDelegateInfo[_sp].totalDelegatedStake; } /// @notice Get total delegated stake locked up for a service provider function getTotalLockedDelegationForServiceProvider(address _sp) external view returns (uint256) { _requireIsInitialized(); return spDelegateInfo[_sp].totalLockedUpStake; } /// @notice Get total currently staked for a delegator, for a given service provider function getDelegatorStakeForServiceProvider(address _delegator, address _serviceProvider) external view returns (uint256) { _requireIsInitialized(); return delegateInfo[_delegator][_serviceProvider]; } /** * @notice Get status of pending undelegate request for a given address * @param _delegator - address of the delegator */ function getPendingUndelegateRequest(address _delegator) external view returns (address target, uint256 amount, uint256 lockupExpiryBlock) { _requireIsInitialized(); UndelegateStakeRequest memory req = undelegateRequests[_delegator]; return (req.serviceProvider, req.amount, req.lockupExpiryBlock); } /** * @notice Get status of pending remove delegator request for a given address * @param _serviceProvider - address of the service provider * @param _delegator - address of the delegator * @return - current lockup expiry block for remove delegator request */ function getPendingRemoveDelegatorRequest( address _serviceProvider, address _delegator ) external view returns (uint256) { _requireIsInitialized(); return removeDelegatorRequests[_serviceProvider][_delegator]; } /// @notice Get current undelegate lockup duration function getUndelegateLockupDuration() external view returns (uint256) { _requireIsInitialized(); return undelegateLockupDuration; } /// @notice Current maximum delegators function getMaxDelegators() external view returns (uint256) { _requireIsInitialized(); return maxDelegators; } /// @notice Get minimum delegation amount function getMinDelegationAmount() external view returns (uint256) { _requireIsInitialized(); return minDelegationAmount; } /// @notice Get the duration for remove delegator request lockup function getRemoveDelegatorLockupDuration() external view returns (uint256) { _requireIsInitialized(); return removeDelegatorLockupDuration; } /// @notice Get the duration for evaluation of remove delegator operations function getRemoveDelegatorEvalDuration() external view returns (uint256) { _requireIsInitialized(); return removeDelegatorEvalDuration; } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the ServiceProviderFactory address function getServiceProviderFactoryAddress() external view returns (address) { _requireIsInitialized(); return serviceProviderFactoryAddress; } /// @notice Get the ClaimsManager address function getClaimsManagerAddress() external view returns (address) { _requireIsInitialized(); return claimsManagerAddress; } /// @notice Get the Staking address function getStakingAddress() external view returns (address) { _requireIsInitialized(); return stakingAddress; } // ========================================= Internal functions ========================================= /** * @notice Helper function for claimRewards to get balances from Staking contract and do validation * @param spFactory - reference to ServiceProviderFactory contract * @param _serviceProvider - address for which rewards are being claimed * @return (totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, spLockedStake, totalRewards, deployerCut) */ function _validateClaimRewards(ServiceProviderFactory spFactory, address _serviceProvider) internal returns ( uint256 totalBalanceInStaking, uint256 totalBalanceInSPFactory, uint256 totalActiveFunds, uint256 totalRewards, uint256 deployerCut ) { // Account for any pending locked up stake for the service provider (uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_serviceProvider); uint256 totalLockedUpStake = ( spDelegateInfo[_serviceProvider].totalLockedUpStake.add(spLockedStake) ); // Process claim for msg.sender // Total locked parameter is equal to delegate locked up stake + service provider locked up stake uint256 mintedRewards = ClaimsManager(claimsManagerAddress).processClaim( _serviceProvider, totalLockedUpStake ); // Amount stored in staking contract for owner totalBalanceInStaking = Staking(stakingAddress).totalStakedFor(_serviceProvider); // Amount in sp factory for claimer ( totalBalanceInSPFactory, deployerCut, ,,, ) = spFactory.getServiceProviderDetails(_serviceProvider); // Require active stake to claim any rewards // Amount in delegate manager staked to service provider uint256 totalBalanceOutsideStaking = ( totalBalanceInSPFactory.add(spDelegateInfo[_serviceProvider].totalDelegatedStake) ); totalActiveFunds = totalBalanceOutsideStaking.sub(totalLockedUpStake); require( mintedRewards == totalBalanceInStaking.sub(totalBalanceOutsideStaking), "DelegateManager: Reward amount mismatch" ); // Emit claim event emit Claim(_serviceProvider, totalRewards, totalBalanceInStaking); return ( totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, mintedRewards, deployerCut ); } /** * @notice Perform state updates when a delegate stake has changed * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @param _totalServiceProviderDelegatedStake - total delegated to this service provider * @param _totalStakedForSpFromDelegator - total delegated to this service provider by delegator * @param _totalDelegatorStake - total delegated from this delegator address */ function _updateDelegatorStake( address _delegator, address _serviceProvider, uint256 _totalServiceProviderDelegatedStake, uint256 _totalStakedForSpFromDelegator, uint256 _totalDelegatorStake ) internal { // Update total delegated for SP spDelegateInfo[_serviceProvider].totalDelegatedStake = _totalServiceProviderDelegatedStake; // Update amount staked from this delegator to targeted service provider delegateInfo[_delegator][_serviceProvider] = _totalStakedForSpFromDelegator; // Update total delegated from this delegator _updateDelegatorTotalStake(_delegator, _totalDelegatorStake); } /** * @notice Reset pending undelegate stake request * @param _delegator - address of delegator */ function _resetUndelegateStakeRequest(address _delegator) internal { _updateUndelegateStakeRequest(_delegator, address(0), 0, 0); } /** * @notice Perform updates when undelegate request state has changed * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @param _amount - amount being undelegated * @param _lockupExpiryBlock - block at which stake can be undelegated */ function _updateUndelegateStakeRequest( address _delegator, address _serviceProvider, uint256 _amount, uint256 _lockupExpiryBlock ) internal { // Update lockup information undelegateRequests[_delegator] = UndelegateStakeRequest({ lockupExpiryBlock: _lockupExpiryBlock, amount: _amount, serviceProvider: _serviceProvider }); } /** * @notice Update total amount delegated from an address * @param _delegator - address of service provider * @param _amount - updated delegator total */ function _updateDelegatorTotalStake(address _delegator, uint256 _amount) internal { delegatorTotalStake[_delegator] = _amount; } /** * @notice Update amount currently locked up for this service provider * @param _serviceProvider - address of service provider * @param _updatedLockupAmount - updated lock up amount */ function _updateServiceProviderLockupAmount( address _serviceProvider, uint256 _updatedLockupAmount ) internal { spDelegateInfo[_serviceProvider].totalLockedUpStake = _updatedLockupAmount; } function _removeFromDelegatorsList(address _serviceProvider, address _delegator) internal { for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) { if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) { // Overwrite and shrink delegators list spDelegateInfo[_serviceProvider].delegators[i] = spDelegateInfo[_serviceProvider].delegators[spDelegateInfo[_serviceProvider].delegators.length - 1]; spDelegateInfo[_serviceProvider].delegators.length--; break; } } } /** * @notice Helper function to distribute rewards to any delegators * @param _sp - service provider account tracked in staking * @param _totalActiveFunds - total funds minus any locked stake * @param _totalRewards - total rewaards generated in this round * @param _deployerCut - service provider cut of delegate rewards, defined as deployerCut / deployerCutBase * @param _deployerCutBase - denominator value for calculating service provider cut as a % * @return (totalBalanceInStaking, totalBalanceInSPFactory, totalBalanceOutsideStaking) */ function _distributeDelegateRewards( address _sp, uint256 _totalActiveFunds, uint256 _totalRewards, uint256 _deployerCut, uint256 _deployerCutBase ) internal returns (uint256 totalDelegatedStakeIncrease) { // Traverse all delegates and calculate their rewards // As each delegate reward is calculated, increment SP cut reward accordingly for (uint256 i = 0; i < spDelegateInfo[_sp].delegators.length; i++) { address delegator = spDelegateInfo[_sp].delegators[i]; uint256 delegateStakeToSP = delegateInfo[delegator][_sp]; // Subtract any locked up stake if (undelegateRequests[delegator].serviceProvider == _sp) { delegateStakeToSP = delegateStakeToSP.sub(undelegateRequests[delegator].amount); } // Calculate rewards by ((delegateStakeToSP / totalActiveFunds) * totalRewards) uint256 rewardsPriorToSPCut = ( delegateStakeToSP.mul(_totalRewards) ).div(_totalActiveFunds); // Multiply by deployer cut fraction to calculate reward for SP // Operation constructed to perform all multiplication prior to division // uint256 spDeployerCut = (rewardsPriorToSPCut * deployerCut ) / (deployerCutBase); // = ((delegateStakeToSP * totalRewards) / totalActiveFunds) * deployerCut ) / (deployerCutBase); // = ((delegateStakeToSP * totalRewards * deployerCut) / totalActiveFunds ) / (deployerCutBase); // = (delegateStakeToSP * totalRewards * deployerCut) / (deployerCutBase * totalActiveFunds); uint256 spDeployerCut = ( (delegateStakeToSP.mul(_totalRewards)).mul(_deployerCut) ).div( _totalActiveFunds.mul(_deployerCutBase) ); // Increase total delegate reward in DelegateManager // Subtract SP reward from rewards to calculate delegate reward // delegateReward = rewardsPriorToSPCut - spDeployerCut; delegateInfo[delegator][_sp] = ( delegateInfo[delegator][_sp].add(rewardsPriorToSPCut.sub(spDeployerCut)) ); // Update total for this delegator _updateDelegatorTotalStake( delegator, delegatorTotalStake[delegator].add(rewardsPriorToSPCut.sub(spDeployerCut)) ); totalDelegatedStakeIncrease = ( totalDelegatedStakeIncrease.add(rewardsPriorToSPCut.sub(spDeployerCut)) ); } return (totalDelegatedStakeIncrease); } /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "DelegateManager: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } /** * @notice Set the remove delegator lockup duration after validating against governance * @param _duration - Incoming remove delegator duration value */ function _updateRemoveDelegatorLockupDuration(uint256 _duration) internal { Governance governance = Governance(governanceAddress); require( _duration > governance.getVotingPeriod() + governance.getExecutionDelay(), "DelegateManager: removeDelegatorLockupDuration duration must be greater than governance votingPeriod + executionDelay" ); removeDelegatorLockupDuration = _duration; } /** * @notice Set the undelegate lockup duration after validating against governance * @param _duration - Incoming undelegate lockup duration value */ function _updateUndelegateLockupDuration(uint256 _duration) internal { Governance governance = Governance(governanceAddress); require( _duration > governance.getVotingPeriod() + governance.getExecutionDelay(), "DelegateManager: undelegateLockupDuration duration must be greater than governance votingPeriod + executionDelay" ); undelegateLockupDuration = _duration; } /** * @notice Returns if delegator has delegated to a service provider * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @return boolean indicating whether delegator exists for service provider */ function _delegatorExistsForSP( address _delegator, address _serviceProvider ) internal view returns (bool) { for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) { if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) { return true; } } // Not found return false; } /** * @notice Determine if a claim is pending for this service provider * @param _sp - address of service provider * @return boolean indicating whether a claim is pending */ function _claimPending(address _sp) internal view returns (bool) { ClaimsManager claimsManager = ClaimsManager(claimsManagerAddress); return claimsManager.claimPending(_sp); } /** * @notice Determine if a decrease request has been initiated * @param _delegator - address of delegator * @return boolean indicating whether a decrease request is pending */ function _undelegateRequestIsPending(address _delegator) internal view returns (bool) { return ( (undelegateRequests[_delegator].lockupExpiryBlock != 0) && (undelegateRequests[_delegator].amount != 0) && (undelegateRequests[_delegator].serviceProvider != address(0)) ); } // ========================================= Private Functions ========================================= function _requireStakingAddressIsSet() private view { require( stakingAddress != address(0x00), "DelegateManager: stakingAddress is not set" ); } function _requireServiceProviderFactoryAddressIsSet() private view { require( serviceProviderFactoryAddress != address(0x00), "DelegateManager: serviceProviderFactoryAddress is not set" ); } function _requireClaimsManagerAddressIsSet() private view { require( claimsManagerAddress != address(0x00), "DelegateManager: claimsManagerAddress is not set" ); } }
17,958
26
// placeholder
_balancesArray.push(address(0));
_balancesArray.push(address(0));
31,015
3
// Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. /
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); }
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); }
65,338
62
// _proposalID Id of the new curator proposal/ return _newDAO Address of the new DAO
function getNewDAOAddress(uint _proposalID) public virtual view returns (address _newDAO);
function getNewDAOAddress(uint _proposalID) public virtual view returns (address _newDAO);
22,145
464
// register supported interfaces for ERC165
_registerInterface(0x80ac58cd); // ERC721 _registerInterface(0x5b5e139f); // ERC721Metadata _registerInterface(0x7f5828d0); // ERC173 (ownership)
_registerInterface(0x80ac58cd); // ERC721 _registerInterface(0x5b5e139f); // ERC721Metadata _registerInterface(0x7f5828d0); // ERC173 (ownership)
52,025
77
// Withdraw crvLPToken from yearn amount_ The amount of crvLPToken which we deposit yearnVault_ The yearn Vault in which we deposit /
function _withdrawFromYearn(uint256 amount_, YearnVault yearnVault_) internal
function _withdrawFromYearn(uint256 amount_, YearnVault yearnVault_) internal
12,267
34
// Contains all logic for processing an unstake operation. For the given deposit, does share accounting and burns shares, returns staking tokens to the original owner, updates global deposit and share trackers, and claims rewards for the given deposit.depositId The specified deposit to unstake from. /
function _unstake(uint256 depositId) internal returns (uint256 reward) { // Fetch stake and make sure it is withdrawable UserStake storage s = stakes[msg.sender][depositId]; uint256 depositAmount = s.amount; if (depositAmount == 0) revert USR_NoDeposit(depositId); if (s.unbondTimestamp == 0 || block.timestamp < s.unbondTimestamp) revert USR_StakeLocked(depositId); _updateRewardForStake(msg.sender, depositId); // Start unstaking uint256 amountWithBoost = s.amountWithBoost; reward = s.rewards; s.amount = 0; s.amountWithBoost = 0; s.rewards = 0; // Update global state totalDeposits -= depositAmount; totalDepositsWithBoost -= amountWithBoost; // Distribute stake stakingToken.safeTransfer(msg.sender, depositAmount); // Distribute reward distributionToken.safeTransfer(msg.sender, reward); emit Unstake(msg.sender, depositId, depositAmount, reward); }
function _unstake(uint256 depositId) internal returns (uint256 reward) { // Fetch stake and make sure it is withdrawable UserStake storage s = stakes[msg.sender][depositId]; uint256 depositAmount = s.amount; if (depositAmount == 0) revert USR_NoDeposit(depositId); if (s.unbondTimestamp == 0 || block.timestamp < s.unbondTimestamp) revert USR_StakeLocked(depositId); _updateRewardForStake(msg.sender, depositId); // Start unstaking uint256 amountWithBoost = s.amountWithBoost; reward = s.rewards; s.amount = 0; s.amountWithBoost = 0; s.rewards = 0; // Update global state totalDeposits -= depositAmount; totalDepositsWithBoost -= amountWithBoost; // Distribute stake stakingToken.safeTransfer(msg.sender, depositAmount); // Distribute reward distributionToken.safeTransfer(msg.sender, reward); emit Unstake(msg.sender, depositId, depositAmount, reward); }
72,086
308
// EIP-712 contract's domain separator, /
bytes32 public immutable DOMAIN_SEPARATOR;
bytes32 public immutable DOMAIN_SEPARATOR;
8,770
1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator);
interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator);
70,051
49
// Vault distributing incoming elastic token rewards equally amongst staked pools
contract Vault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // elastic, in token underlying units // // We do some fancy math here. Basically, any point in time, the amount of reward tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardPerShare` (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 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Reward tokens to distribute per block. uint256 accRewardPerShare; // Accumulated token underlying units per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // A reward token IXAUToken public rewardToken; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes 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; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; // elastic, in token underlying units uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; // elastic, in token underlying units uint256 public rewardsInThisEpoch; // elastic, in token underlying units uint public epoch; // Dev address. address public devFeeReceiver; uint16 public devFeePercentX100; uint256 public pendingDevRewards; // elastic, in token underlying units // Returns average rewards generated since start of this contract function averageRewardPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge reward in this epoch function averageRewardPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; // Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event NewDevFeeReceiver(address oldDevFeeReceiver, address newDevFeeReceiver); event NewDevFeePercentX100(uint256 oldDevFeePercentX100, uint256 newDevFeePercentX100); 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, address indexed to); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event MigrationWithdraw( address indexed user, address indexed newVault, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( IXAUToken _rewardToken, address _devFeeReceiver, uint16 _devFeePercentX100 ) public initializer { OwnableUpgradeSafe.__Ownable_init(); devFeePercentX100 = _devFeePercentX100; rewardToken = _rewardToken; devFeeReceiver = _devFeeReceiver; contractStartBlock = block.number; epochCalculationStartBlock = block.number; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing reward token governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token, "Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accRewardPerShare: 0, withdrawable: _withdrawable }) ); } // Update the given pool's reward tokens allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing reward token governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing reward token governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // Note contract owner is meant to be a governance contract allowing reward token governance consensus function setDevFeePercentX100(uint16 _devFeePercentX100) public onlyOwner { require(_devFeePercentX100 <= 1000, 'Dev fee clamped at 10%'); uint256 oldDevFeePercentX100 = devFeePercentX100; devFeePercentX100 = _devFeePercentX100; emit NewDevFeePercentX100(oldDevFeePercentX100, _devFeePercentX100); } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing reward token governance token holders to do this functions. function setDevFeeReceiver(address _devFeeReceiver) public onlyOwner { address oldDevFeeReceiver = devFeeReceiver; devFeeReceiver = _devFeeReceiver; emit NewDevFeeReceiver(oldDevFeeReceiver, _devFeeReceiver); } // View function to see pending reward tokens on frontend. function pendingToken(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; return rewardToken.fromUnderlying(user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt)); } // View function to see pending reward tokens on frontend. function pendingTokenActual(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } uint256 rewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 rewardFee = rewardWhole.mul(devFeePercentX100).div(10000); uint256 rewardToDistribute = rewardWhole.sub(rewardFee); uint256 accRewardPerShare = pool.accRewardPerShare.add(rewardToDistribute.mul(1e12).div(tokenSupply)); return rewardToken.fromUnderlying(user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt)); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // Function that adds pending rewards, called by the reward token. uint256 private rewardTokenBalance; function addPendingRewards(uint256 /* _ */) public { uint256 newRewards = rewardToken.balanceOfUnderlying(address(this)).sub(rewardTokenBalance); // elastic if (newRewards > 0) { rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); // If there is no change the balance didn't change // elastic pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 rewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } rewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 rewardFee = rewardWhole.mul(devFeePercentX100).div(10000); uint256 rewardToDistribute = rewardWhole.sub(rewardFee); pendingDevRewards = pendingDevRewards.add(rewardFee); pool.accRewardPerShare = pool.accRewardPerShare.add( rewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit user tokens to vault for reward token allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); // https://kovan.etherscan.io/tx/0xbd6a42d7ca389be178a2e825b7a242d60189abcfbea3e4276598c0bb28c143c9 // TODO: INVESTIGATE // Transfer in the amounts from user // save gas if (_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address _depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, _depositFor); // Update the balances of person that amount is being deposited for if (_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); /// This is deposited for address emit Deposit(_depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw user tokens from vault function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming rewards farmed if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingToken(_pid, from); if (pending > 0) { safeRewardTokenTransfer(from, pending); } } // Function that lets owner/governance contract approve // allowance for any 3rd party token inside this contract. // This means all future UNI like airdrops are covered. // And at the same time allows us to give allowance to strategy contracts. function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlyOwner { require(isContract(contractAddress), "Recipent is not a smart contract"); require(tokenAddress != address(rewardToken), "Reward token allowance not allowed"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; pid++) { require(tokenAddress != address(poolInfo[pid].token), "Pool token allowance not allowed"); } IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } function migrateTokensToNewVault(address _newVault) public virtual onlyOwner { require(_newVault != address(0), "Vault: new vault is the zero address"); uint256 rewardTokenBalErc = rewardToken.balanceOf(address(this)); // elastic safeRewardTokenTransfer(_newVault, rewardTokenBalErc); emit MigrationWithdraw(msg.sender, _newVault, rewardTokenBalErc); rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid, address _to) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; // Note: transfer can fail or succeed if `amount` is zero. if (amount > 0) { pool.token.safeTransfer(_to, amount); user.amount = 0; user.rewardDebt = 0; } emit EmergencyWithdraw(msg.sender, _pid, amount, _to); } // Safe reward token transfer function, just in case if rounding error causes pool to not have enough reward tokens. function safeRewardTokenTransfer(address _to, uint256 _amount) internal { uint256 rewardTokenBalErc = rewardToken.balanceOf(address(this)); // elastic if (_amount > rewardTokenBalErc) { rewardToken.transfer(_to, rewardTokenBalErc); // elastic rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); // elastic } else { rewardToken.transfer(_to, _amount); // elastic rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); // elastic } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if (pendingDevRewards == 0) return; uint256 pendingDevRewardsErc = rewardToken.fromUnderlying(pendingDevRewards); uint256 rewardTokenBalErc = rewardToken.balanceOf(address(this)); // elastic if (pendingDevRewardsErc > rewardTokenBalErc) { rewardToken.transfer(devFeeReceiver, rewardTokenBalErc); // elastic rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); // elastic } else { rewardToken.transfer(devFeeReceiver, pendingDevRewardsErc); // elastic rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); // elastic } pendingDevRewards = 0; } }
contract Vault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // elastic, in token underlying units // // We do some fancy math here. Basically, any point in time, the amount of reward tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardPerShare` (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 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Reward tokens to distribute per block. uint256 accRewardPerShare; // Accumulated token underlying units per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // A reward token IXAUToken public rewardToken; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes 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; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; // elastic, in token underlying units uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; // elastic, in token underlying units uint256 public rewardsInThisEpoch; // elastic, in token underlying units uint public epoch; // Dev address. address public devFeeReceiver; uint16 public devFeePercentX100; uint256 public pendingDevRewards; // elastic, in token underlying units // Returns average rewards generated since start of this contract function averageRewardPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge reward in this epoch function averageRewardPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; // Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event NewDevFeeReceiver(address oldDevFeeReceiver, address newDevFeeReceiver); event NewDevFeePercentX100(uint256 oldDevFeePercentX100, uint256 newDevFeePercentX100); 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, address indexed to); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event MigrationWithdraw( address indexed user, address indexed newVault, uint256 amount ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( IXAUToken _rewardToken, address _devFeeReceiver, uint16 _devFeePercentX100 ) public initializer { OwnableUpgradeSafe.__Ownable_init(); devFeePercentX100 = _devFeePercentX100; rewardToken = _rewardToken; devFeeReceiver = _devFeeReceiver; contractStartBlock = block.number; epochCalculationStartBlock = block.number; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing reward token governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token, "Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accRewardPerShare: 0, withdrawable: _withdrawable }) ); } // Update the given pool's reward tokens allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing reward token governance consensus function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing reward token governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // Note contract owner is meant to be a governance contract allowing reward token governance consensus function setDevFeePercentX100(uint16 _devFeePercentX100) public onlyOwner { require(_devFeePercentX100 <= 1000, 'Dev fee clamped at 10%'); uint256 oldDevFeePercentX100 = devFeePercentX100; devFeePercentX100 = _devFeePercentX100; emit NewDevFeePercentX100(oldDevFeePercentX100, _devFeePercentX100); } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing reward token governance token holders to do this functions. function setDevFeeReceiver(address _devFeeReceiver) public onlyOwner { address oldDevFeeReceiver = devFeeReceiver; devFeeReceiver = _devFeeReceiver; emit NewDevFeeReceiver(oldDevFeeReceiver, _devFeeReceiver); } // View function to see pending reward tokens on frontend. function pendingToken(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; return rewardToken.fromUnderlying(user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt)); } // View function to see pending reward tokens on frontend. function pendingTokenActual(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } uint256 rewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 rewardFee = rewardWhole.mul(devFeePercentX100).div(10000); uint256 rewardToDistribute = rewardWhole.sub(rewardFee); uint256 accRewardPerShare = pool.accRewardPerShare.add(rewardToDistribute.mul(1e12).div(tokenSupply)); return rewardToken.fromUnderlying(user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt)); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // Function that adds pending rewards, called by the reward token. uint256 private rewardTokenBalance; function addPendingRewards(uint256 /* _ */) public { uint256 newRewards = rewardToken.balanceOfUnderlying(address(this)).sub(rewardTokenBalance); // elastic if (newRewards > 0) { rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); // If there is no change the balance didn't change // elastic pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 rewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } rewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 rewardFee = rewardWhole.mul(devFeePercentX100).div(10000); uint256 rewardToDistribute = rewardWhole.sub(rewardFee); pendingDevRewards = pendingDevRewards.add(rewardFee); pool.accRewardPerShare = pool.accRewardPerShare.add( rewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit user tokens to vault for reward token allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, msg.sender); // https://kovan.etherscan.io/tx/0xbd6a42d7ca389be178a2e825b7a242d60189abcfbea3e4276598c0bb28c143c9 // TODO: INVESTIGATE // Transfer in the amounts from user // save gas if (_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address _depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, _depositFor); // Update the balances of person that amount is being deposited for if (_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); /// This is deposited for address emit Deposit(_depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw user tokens from vault function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming rewards farmed if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingToken(_pid, from); if (pending > 0) { safeRewardTokenTransfer(from, pending); } } // Function that lets owner/governance contract approve // allowance for any 3rd party token inside this contract. // This means all future UNI like airdrops are covered. // And at the same time allows us to give allowance to strategy contracts. function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlyOwner { require(isContract(contractAddress), "Recipent is not a smart contract"); require(tokenAddress != address(rewardToken), "Reward token allowance not allowed"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; pid++) { require(tokenAddress != address(poolInfo[pid].token), "Pool token allowance not allowed"); } IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } function migrateTokensToNewVault(address _newVault) public virtual onlyOwner { require(_newVault != address(0), "Vault: new vault is the zero address"); uint256 rewardTokenBalErc = rewardToken.balanceOf(address(this)); // elastic safeRewardTokenTransfer(_newVault, rewardTokenBalErc); emit MigrationWithdraw(msg.sender, _newVault, rewardTokenBalErc); rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid, address _to) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; // Note: transfer can fail or succeed if `amount` is zero. if (amount > 0) { pool.token.safeTransfer(_to, amount); user.amount = 0; user.rewardDebt = 0; } emit EmergencyWithdraw(msg.sender, _pid, amount, _to); } // Safe reward token transfer function, just in case if rounding error causes pool to not have enough reward tokens. function safeRewardTokenTransfer(address _to, uint256 _amount) internal { uint256 rewardTokenBalErc = rewardToken.balanceOf(address(this)); // elastic if (_amount > rewardTokenBalErc) { rewardToken.transfer(_to, rewardTokenBalErc); // elastic rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); // elastic } else { rewardToken.transfer(_to, _amount); // elastic rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); // elastic } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if (pendingDevRewards == 0) return; uint256 pendingDevRewardsErc = rewardToken.fromUnderlying(pendingDevRewards); uint256 rewardTokenBalErc = rewardToken.balanceOf(address(this)); // elastic if (pendingDevRewardsErc > rewardTokenBalErc) { rewardToken.transfer(devFeeReceiver, rewardTokenBalErc); // elastic rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); // elastic } else { rewardToken.transfer(devFeeReceiver, pendingDevRewardsErc); // elastic rewardTokenBalance = rewardToken.balanceOfUnderlying(address(this)); // elastic } pendingDevRewards = 0; } }
8,827
8
// time contract was deployed
uint public createdAt;
uint public createdAt;
85,692
8
// `requestProofIssuance` - An authorized issuer requests proof issuance after a consensus is reached.This runs the automatic data verification and the certificate minting process. request - An IssuanceRequest struct containing the data needed to issue a certificate. /
function requestProofIssuance(IssuanceRequest memory request) external;
function requestProofIssuance(IssuanceRequest memory request) external;
30,437
1
// max count of latest blocks that _actionFlag can store actions
uint constant actionMaxBlocks = 14;
uint constant actionMaxBlocks = 14;
2,022
293
// Reduces reserves by transferring to admin Requires fresh interest accrual reduceAmount Amount of reduction to reservesreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is Reserve Guardian or admin if (msg.sender != comptroller.reserveGuardian() && msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } // Make sure reserve guardian was set to avoid transferring reserves to the zero address if (comptroller.reserveGuardian() == address(0)) { return fail(Error.INVALID_GUARDIAN, FailureInfo.REDUCE_RESERVES_GUARDIAN_NOT_SET); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(comptroller.reserveGuardian(), reduceAmount); emit ReservesReduced(comptroller.reserveGuardian(), reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); }
function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is Reserve Guardian or admin if (msg.sender != comptroller.reserveGuardian() && msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } // Make sure reserve guardian was set to avoid transferring reserves to the zero address if (comptroller.reserveGuardian() == address(0)) { return fail(Error.INVALID_GUARDIAN, FailureInfo.REDUCE_RESERVES_GUARDIAN_NOT_SET); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(comptroller.reserveGuardian(), reduceAmount); emit ReservesReduced(comptroller.reserveGuardian(), reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); }
65,991
9
// Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network.return the maximum gas limit value. /
function maxGasPerTx() internal view returns (uint256) { return bridgeContract().maxGasPerTx(); }
function maxGasPerTx() internal view returns (uint256) { return bridgeContract().maxGasPerTx(); }
4,630
107
// Compute percentage of a value with the percentage represented by a fraction over PERC_DIVISOR _amount Amount to take the percentage of _fracNum Numerator of fraction representing the percentage with PERC_DIVISOR as the denominator /
function percOf(uint256 _amount, uint256 _fracNum) internal pure returns (uint256) { return _amount.mul(_fracNum).div(PERC_DIVISOR); }
function percOf(uint256 _amount, uint256 _fracNum) internal pure returns (uint256) { return _amount.mul(_fracNum).div(PERC_DIVISOR); }
23,603
85
// how much fee is being paid in
uint256 feeAmount;
uint256 feeAmount;
27,604
16
// Pay ether to fond
_fondContract.invest.value(toFond)(msg.sender);
_fondContract.invest.value(toFond)(msg.sender);
45,784
127
// This is an alternative to {approve} that can be used as a mitigation forproblems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address.- `spender` must have allowance for the caller of at least`subtractedValue`. /
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; }
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; }
4,873
2
// Returns the platform fee recipient and bps.
function getPlatformFeeInfo() public view override returns (address, uint16) { return (platformFeeRecipient, uint16(platformFeeBps)); }
function getPlatformFeeInfo() public view override returns (address, uint16) { return (platformFeeRecipient, uint16(platformFeeBps)); }
13,607
4
// Emitted when an existing router is removed router - The address of the removed router caller - The account that called the function /
event RouterRemoved(address indexed router, address caller);
event RouterRemoved(address indexed router, address caller);
23,777
4
// Variables to store the start and end time of the election
uint public electionStartTime; uint public electionEndTime;
uint public electionStartTime; uint public electionEndTime;
11,232
114
// Sets the frozen state of the reserve self The reserve configuration frozen The frozen state /
function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); }
function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); }
46,796
75
// assign the end block
endBlock = _endBlock;
endBlock = _endBlock;
6,847
0
// track all members of the DAO with their roles
mapping(address => mapping(bytes32 => bool)) private _members;
mapping(address => mapping(bytes32 => bool)) private _members;
23,915
121
// Internal function to set the token URI for a given token. Reverts if the token ID does not exist.tokenId uint256 ID of the token to set its URIuri string URI to assign/
function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; }
function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; }
68,567
500
// keccak256("decodeAndHashBoosterMessage(address,bytes)")
abi.encodeWithSelector( 0xaf6eec54, msg.sender, /* msg.sender becomes the target booster */ boosterMessage ) ); if (!success) { continue; }
abi.encodeWithSelector( 0xaf6eec54, msg.sender, /* msg.sender becomes the target booster */ boosterMessage ) ); if (!success) { continue; }
5,378
3
// asset that is held as collateral against short/written options
address public collateralAsset;
address public collateralAsset;
43,266
80
// CAUTION: do not input _from == _to s.t. this function will always fail
function _transfer( IERC20Upgradeable _token, address _to, Decimal.decimal memory _value
function _transfer( IERC20Upgradeable _token, address _to, Decimal.decimal memory _value
8,601
264
// Closes the specified stream. Pays out pending amounts, clears out the stream, and emits a StreamClosed event. streamId The id of the stream to close. /
function closeStream(uint256 streamId) public canManageStreams
function closeStream(uint256 streamId) public canManageStreams
87,513
121
// B. If rewards at this bracket are > 0, calculate, else, report the numberAddresses from previous bracket
if (_lotteries[_lotteryId].rewardsBreakdown[j] != 0) { _lotteries[_lotteryId].dexTokenPerBracket[j] = ((_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) / (_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket)) / 10000;
if (_lotteries[_lotteryId].rewardsBreakdown[j] != 0) { _lotteries[_lotteryId].dexTokenPerBracket[j] = ((_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) / (_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket)) / 10000;
33,948
62
// Closes user position id Position id /
function closePosition(bytes32 id) external { _closePosition(_msgSender(), id, block.timestamp); }
function closePosition(bytes32 id) external { _closePosition(_msgSender(), id, block.timestamp); }
1,614
11
// Changes the current state to `to`, and fires `StateChanged`. /
function setState(State to) internal { State from = state; state = to; StateChanged(from, to); }
function setState(State to) internal { State from = state; state = to; StateChanged(from, to); }
4,961
24
// Mark fill fraction as zero as the order will not be used.
advancedOrder.numerator = 0;
advancedOrder.numerator = 0;
16,828
25
// For methods only callable with withdraws enabled (all withdrawal operations). /
modifier onlyWithdrawEnabled() { if (!withdrawEnabled) revert AV_WithdrawsDisabled(); _; }
modifier onlyWithdrawEnabled() { if (!withdrawEnabled) revert AV_WithdrawsDisabled(); _; }
36,254