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
49
// Say that the contract is initialized.
__setInitialized(); emit WorldIDIdentityManagerImplInitialized( _treeDepth, initialRoot, _enableStateBridge, __stateBridge );
__setInitialized(); emit WorldIDIdentityManagerImplInitialized( _treeDepth, initialRoot, _enableStateBridge, __stateBridge );
31,110
38
// should not be used with lpAddresses that are from the crypto swap registry
function getVirtualPrice(address lpAddress) public view returns (uint256) { return curveRegistry().get_virtual_price_from_lp_token(lpAddress); }
function getVirtualPrice(address lpAddress) public view returns (uint256) { return curveRegistry().get_virtual_price_from_lp_token(lpAddress); }
49,823
60
// Remaining tokens withdrawal
function withdrawTokens() external onlyOwner afterCrowdsale { uint256 tokens_remaining = token.balanceOf(address(this)); token.transfer(owner, tokens_remaining); }
function withdrawTokens() external onlyOwner afterCrowdsale { uint256 tokens_remaining = token.balanceOf(address(this)); token.transfer(owner, tokens_remaining); }
72,298
219
// YaxisChef is the master of yAxis. He can make yAxis 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 YAX is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless.
contract YaxisChef 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. // // We do some fancy math here. Basically, any point in time, the amount of YAXs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accYaxPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accYaxPerShare` (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. uint256 accumulatedStakingPower; // will accumulate every time user harvest } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. YAXs to distribute per block. uint256 lastRewardBlock; // Last block number that YAXs distribution occurs. uint256 accYaxPerShare; // Accumulated YAXs per share, times 1e12. See below. bool isStarted; // if lastRewardBlock has passed } // The YAX TOKEN! YaxisToken public yax; // Tresury address. address public tresuryaddr; // YAX tokens created per block. uint256 public yaxPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // 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 YAX mining starts. uint256 public startBlock; // Block number when each epoch ends. uint256[4] public epochEndBlocks; // Reward multipler for each of 4 epoches (epochIndex: reward multipler) uint256[5] public epochRewardMultiplers = [3840, 2880, 1920, 960, 1]; uint256 public constant BLOCKS_PER_WEEK = 46500; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( YaxisToken _yax, address _tresuryaddr, uint256 _yaxPerBlock, uint256 _startBlock ) public { yax = _yax; tresuryaddr = _tresuryaddr; yaxPerBlock = _yaxPerBlock; // supposed to be 0.001 (1e16 wei) startBlock = _startBlock; // supposed to be 10,883,800 (Fri Sep 18 2020 3:00:00 GMT+0) epochEndBlocks[0] = startBlock + BLOCKS_PER_WEEK * 2; // weeks 1-2 epochEndBlocks[1] = epochEndBlocks[0] + BLOCKS_PER_WEEK * 2; // weeks 3-4 epochEndBlocks[2] = epochEndBlocks[1] + BLOCKS_PER_WEEK * 2; // weeks 5-6 epochEndBlocks[3] = epochEndBlocks[2] + BLOCKS_PER_WEEK * 2; // weeks 7-8 } function poolLength() external view returns (uint256) { return poolInfo.length; } function setYaxPerBlock(uint256 _yaxPerBlock) public onlyOwner { massUpdatePools(); yaxPerBlock = _yaxPerBlock; } function setEpochEndBlock(uint8 _index, uint256 _epochEndBlock) public onlyOwner { require(_index < 4, "_index out of range"); require(_epochEndBlock > block.number, "Too late to update"); require(epochEndBlocks[_index] > block.number, "Too late to update"); epochEndBlocks[_index] = _epochEndBlock; } function setEpochRewardMultipler(uint8 _index, uint256 _epochRewardMultipler) public onlyOwner { require(_index > 0 && _index < 5, "Index out of range"); require(epochEndBlocks[_index - 1] > block.number, "Too late to update"); epochRewardMultiplers[_index] = _epochRewardMultipler; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { // chef is sleeping if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; } else { if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } } else { // chef is cooking if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (_lastRewardBlock <= startBlock) || (_lastRewardBlock <= block.number); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: _lastRewardBlock, accYaxPerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's YAX allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint); } pool.allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. function migrate(uint256 _pid) public onlyOwner { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { for (uint8 epochId = 4; epochId >= 1; --epochId) { if (_to >= epochEndBlocks[epochId - 1]) { if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochRewardMultiplers[epochId]); uint256 multiplier = _to.sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId]); if (epochId == 1) return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); for (epochId = epochId - 1; epochId >= 1; --epochId) { if (_from >= epochEndBlocks[epochId - 1]) return multiplier.add(epochEndBlocks[epochId].sub(_from).mul(epochRewardMultiplers[epochId])); multiplier = multiplier.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId])); } return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); } } return _to.sub(_from).mul(epochRewardMultiplers[0]); } // View function to see pending YAXs on frontend. function pendingYaxis(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accYaxPerShare = pool.accYaxPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 yaxReward = multiplier.mul(yaxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accYaxPerShare = accYaxPerShare.add(yaxReward.mul(1e12).div(lpSupply)); } } return user.amount.mul(accYaxPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables 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.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 yaxReward = multiplier.mul(yaxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); safeYaxMint(tresuryaddr, yaxReward.div(9)); safeYaxMint(address(this), yaxReward); pool.accYaxPerShare = pool.accYaxPerShare.add(yaxReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit LP tokens to YaxisChef for YAX allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accYaxPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { user.accumulatedStakingPower = user.accumulatedStakingPower.add(pending); safeYaxTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accYaxPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from YaxisChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accYaxPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { user.accumulatedStakingPower = user.accumulatedStakingPower.add(pending); safeYaxTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accYaxPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe yax mint, ensure it is never over cap and we are the current owner. function safeYaxMint(address _to, uint256 _amount) internal { if (yax.minters(address(this)) && _to != address(0)) { uint256 totalSupply = yax.totalSupply(); uint256 cap = yax.cap(); if (totalSupply.add(_amount) > cap) { yax.mint(_to, cap.sub(totalSupply)); } else { yax.mint(_to, _amount); } } } // Safe yax transfer function, just in case if rounding error causes pool to not have enough YAXs. function safeYaxTransfer(address _to, uint256 _amount) internal { uint256 yaxBal = yax.balanceOf(address(this)); if (_amount > yaxBal) { yax.transfer(_to, yaxBal); } else { yax.transfer(_to, _amount); } } // Update tresury by the previous tresury contract. function tresury(address _tresuryaddr) public { require(msg.sender == tresuryaddr, "tresury: wut?"); tresuryaddr = _tresuryaddr; } // This function allows governance to take unsupported tokens out of the contract, since this pool exists longer than the other pools. // This is in an effort to make someone whole, should they seriously mess up. // There is no guarantee governance will vote to return these. // It also allows for removal of airdropped tokens. function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOwner { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; // cant take staked asset require(_token != pool.lpToken, "!pool.lpToken"); } // transfer to _token.safeTransfer(to, amount); } }
contract YaxisChef 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. // // We do some fancy math here. Basically, any point in time, the amount of YAXs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accYaxPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accYaxPerShare` (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. uint256 accumulatedStakingPower; // will accumulate every time user harvest } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. YAXs to distribute per block. uint256 lastRewardBlock; // Last block number that YAXs distribution occurs. uint256 accYaxPerShare; // Accumulated YAXs per share, times 1e12. See below. bool isStarted; // if lastRewardBlock has passed } // The YAX TOKEN! YaxisToken public yax; // Tresury address. address public tresuryaddr; // YAX tokens created per block. uint256 public yaxPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // 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 YAX mining starts. uint256 public startBlock; // Block number when each epoch ends. uint256[4] public epochEndBlocks; // Reward multipler for each of 4 epoches (epochIndex: reward multipler) uint256[5] public epochRewardMultiplers = [3840, 2880, 1920, 960, 1]; uint256 public constant BLOCKS_PER_WEEK = 46500; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( YaxisToken _yax, address _tresuryaddr, uint256 _yaxPerBlock, uint256 _startBlock ) public { yax = _yax; tresuryaddr = _tresuryaddr; yaxPerBlock = _yaxPerBlock; // supposed to be 0.001 (1e16 wei) startBlock = _startBlock; // supposed to be 10,883,800 (Fri Sep 18 2020 3:00:00 GMT+0) epochEndBlocks[0] = startBlock + BLOCKS_PER_WEEK * 2; // weeks 1-2 epochEndBlocks[1] = epochEndBlocks[0] + BLOCKS_PER_WEEK * 2; // weeks 3-4 epochEndBlocks[2] = epochEndBlocks[1] + BLOCKS_PER_WEEK * 2; // weeks 5-6 epochEndBlocks[3] = epochEndBlocks[2] + BLOCKS_PER_WEEK * 2; // weeks 7-8 } function poolLength() external view returns (uint256) { return poolInfo.length; } function setYaxPerBlock(uint256 _yaxPerBlock) public onlyOwner { massUpdatePools(); yaxPerBlock = _yaxPerBlock; } function setEpochEndBlock(uint8 _index, uint256 _epochEndBlock) public onlyOwner { require(_index < 4, "_index out of range"); require(_epochEndBlock > block.number, "Too late to update"); require(epochEndBlocks[_index] > block.number, "Too late to update"); epochEndBlocks[_index] = _epochEndBlock; } function setEpochRewardMultipler(uint8 _index, uint256 _epochRewardMultipler) public onlyOwner { require(_index > 0 && _index < 5, "Index out of range"); require(epochEndBlocks[_index - 1] > block.number, "Too late to update"); epochRewardMultiplers[_index] = _epochRewardMultipler; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { // chef is sleeping if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; } else { if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } } else { // chef is cooking if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (_lastRewardBlock <= startBlock) || (_lastRewardBlock <= block.number); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: _lastRewardBlock, accYaxPerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's YAX allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint); } pool.allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. function migrate(uint256 _pid) public onlyOwner { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { for (uint8 epochId = 4; epochId >= 1; --epochId) { if (_to >= epochEndBlocks[epochId - 1]) { if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochRewardMultiplers[epochId]); uint256 multiplier = _to.sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId]); if (epochId == 1) return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); for (epochId = epochId - 1; epochId >= 1; --epochId) { if (_from >= epochEndBlocks[epochId - 1]) return multiplier.add(epochEndBlocks[epochId].sub(_from).mul(epochRewardMultiplers[epochId])); multiplier = multiplier.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId])); } return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); } } return _to.sub(_from).mul(epochRewardMultiplers[0]); } // View function to see pending YAXs on frontend. function pendingYaxis(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accYaxPerShare = pool.accYaxPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 yaxReward = multiplier.mul(yaxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accYaxPerShare = accYaxPerShare.add(yaxReward.mul(1e12).div(lpSupply)); } } return user.amount.mul(accYaxPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables 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.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 yaxReward = multiplier.mul(yaxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); safeYaxMint(tresuryaddr, yaxReward.div(9)); safeYaxMint(address(this), yaxReward); pool.accYaxPerShare = pool.accYaxPerShare.add(yaxReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit LP tokens to YaxisChef for YAX allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accYaxPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { user.accumulatedStakingPower = user.accumulatedStakingPower.add(pending); safeYaxTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accYaxPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from YaxisChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accYaxPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { user.accumulatedStakingPower = user.accumulatedStakingPower.add(pending); safeYaxTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accYaxPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe yax mint, ensure it is never over cap and we are the current owner. function safeYaxMint(address _to, uint256 _amount) internal { if (yax.minters(address(this)) && _to != address(0)) { uint256 totalSupply = yax.totalSupply(); uint256 cap = yax.cap(); if (totalSupply.add(_amount) > cap) { yax.mint(_to, cap.sub(totalSupply)); } else { yax.mint(_to, _amount); } } } // Safe yax transfer function, just in case if rounding error causes pool to not have enough YAXs. function safeYaxTransfer(address _to, uint256 _amount) internal { uint256 yaxBal = yax.balanceOf(address(this)); if (_amount > yaxBal) { yax.transfer(_to, yaxBal); } else { yax.transfer(_to, _amount); } } // Update tresury by the previous tresury contract. function tresury(address _tresuryaddr) public { require(msg.sender == tresuryaddr, "tresury: wut?"); tresuryaddr = _tresuryaddr; } // This function allows governance to take unsupported tokens out of the contract, since this pool exists longer than the other pools. // This is in an effort to make someone whole, should they seriously mess up. // There is no guarantee governance will vote to return these. // It also allows for removal of airdropped tokens. function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOwner { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; // cant take staked asset require(_token != pool.lpToken, "!pool.lpToken"); } // transfer to _token.safeTransfer(to, amount); } }
10,463
142
// Calculate x / y rounding towards zero, where x and y are signed 256-bitinteger numbers.Revert on overflow or when y is zero.x signed 256-bit integer number y signed 256-bit integer numberreturn signed 64.64-bit fixed point number /
function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } }
function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } }
23,944
12
// Sets the required amount of POP a keeper needs to have staked to handle incentivized functions. _amount Amount of POP a keeper needs to stake /
function updateRequiredKeeperStake(uint256 _amount) external { IACLRegistry(contractRegistry.getContract(keccak256("ACLRegistry"))).requireRole(keccak256("DAO"), msg.sender); emit RequiredKeeperStakeChanged(requiredKeeperStake, _amount); requiredKeeperStake = _amount; }
function updateRequiredKeeperStake(uint256 _amount) external { IACLRegistry(contractRegistry.getContract(keccak256("ACLRegistry"))).requireRole(keccak256("DAO"), msg.sender); emit RequiredKeeperStakeChanged(requiredKeeperStake, _amount); requiredKeeperStake = _amount; }
22,623
11
// 授权spender可以转移token的数量
function approve(address _spender, uint256 _value) external override returns (bool success) { require(_spender != address(0), "996: approve to zero address"); require(_value < totalSupply, "996: approved amount must be smaller than totalSupply"); allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
function approve(address _spender, uint256 _value) external override returns (bool success) { require(_spender != address(0), "996: approve to zero address"); require(_value < totalSupply, "996: approved amount must be smaller than totalSupply"); allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
31,382
316
// Set `_newManager` as the manager of `_role` in `_app`_newManager Address for the new manager_app Address of the app in which the permission management is being transferred_role Identifier for the group of actions being transferred/
function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role)
function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role)
47,135
108
// Unlocks the unlockable tokens of a specified address _of Address of user, claiming back unlockable tokens /
function unlock(address _of)
function unlock(address _of)
22,816
127
// weth
if (_wrapInto == 0) { require( _FromTokenContractAddress == address(0), "Cannot wrap into WETH" ); require( _ToTokenContractAddress == address(wethContract), "Invalid toToken" );
if (_wrapInto == 0) { require( _FromTokenContractAddress == address(0), "Cannot wrap into WETH" ); require( _ToTokenContractAddress == address(wethContract), "Invalid toToken" );
25,668
0
// @inheritdoc IMulticallExtended
function multicall( uint256 deadline, bytes[] calldata data ) external payable override checkDeadline(deadline) returns (bytes[] memory)
function multicall( uint256 deadline, bytes[] calldata data ) external payable override checkDeadline(deadline) returns (bytes[] memory)
28,836
97
// Get the address of the token distributor.
ITokenDistributor distributor = ITokenDistributor( _GLOBALS.getAddress(LibGlobals.GLOBAL_TOKEN_DISTRIBUTOR) ); emit DistributionCreated(tokenType, token, tokenId);
ITokenDistributor distributor = ITokenDistributor( _GLOBALS.getAddress(LibGlobals.GLOBAL_TOKEN_DISTRIBUTOR) ); emit DistributionCreated(tokenType, token, tokenId);
41,343
289
// The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent.
uint256 private _flashLoanFeePercentage; event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); constructor(IVault _vault)
uint256 private _flashLoanFeePercentage; event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); constructor(IVault _vault)
33,541
24
// Returns detailed information for a Pool's registered token. `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokenswithdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`equals the sum of `cash` and `managed`. Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,`managed` or `total` balance to be greater than 2^112 - 1. `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either ajoin, exit, swap, or Asset
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
1,525
19
// msg.sender is not of type `address payable` and must be explicitly converted using `payable(msg.sender)` in order use the member function `send()`.
if (!payable(msg.sender).send(amount)) {
if (!payable(msg.sender).send(amount)) {
20,823
15
// Remove a destroyer should they no longer require or need the the privilege._destroyerThe desired address to be removed. /
function removeDestroyer(address _destroyer) external onlyEtheraffle { require(isDestroyer[_destroyer]); isDestroyer[_destroyer] = false; for(uint i = 0; i < destroyers.length - 1; i++) if(destroyers[i] == _destroyer) { destroyers[i] = destroyers[destroyers.length - 1]; break; } destroyers.length--; LogDestroyerRemoval(_destroyer, now); }
function removeDestroyer(address _destroyer) external onlyEtheraffle { require(isDestroyer[_destroyer]); isDestroyer[_destroyer] = false; for(uint i = 0; i < destroyers.length - 1; i++) if(destroyers[i] == _destroyer) { destroyers[i] = destroyers[destroyers.length - 1]; break; } destroyers.length--; LogDestroyerRemoval(_destroyer, now); }
43,486
199
// Constructor function_termParams Array containing:0. _termDuration Duration in seconds per term1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)_governors Array containing:0. _fundsGovernor Address of the funds governor1. _configGovernor Address of the config governor2. _modulesGovernor Address of the modules governor_feeToken Address of the token contract that is used to pay for fees_fees Array containing:0. guardianFee Amount of fee tokens that is paid per guardian per dispute1. draftFee Amount of fee tokens per guardian to cover the drafting cost2. settleFee Amount of fee tokens per guardian to cover round settlement cost_roundStateDurations Array containing the durations in
constructor( uint64[2] memory _termParams, address[3] memory _governors, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance
constructor( uint64[2] memory _termParams, address[3] memory _governors, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance
68,976
54
// An array of addresses and amounts to send /
DistributionData[] public distributions;
DistributionData[] public distributions;
7,229
362
// expmods_and_points.points[59] = -(g^198z).
mstore(add(expmodsAndPoints, 0xaa0), point)
mstore(add(expmodsAndPoints, 0xaa0), point)
29,036
3
// Retrieves user's backups uId User IDreturn userBackups Array of user's encrypted backups /
function retrieveBackup (string calldata uId) external view ownerOnly returns (string[] memory userBackups){ return (backups[uId]); }
function retrieveBackup (string calldata uId) external view ownerOnly returns (string[] memory userBackups){ return (backups[uId]); }
20,327
400
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); }
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); }
26,871
5
// - Fund WBTC for initial phase /
function fundWBTC(uint fundWBTCAmount) public onlyOwner returns (bool) { wbtc.transferFrom(msg.sender, address(this), fundWBTCAmount); }
function fundWBTC(uint fundWBTCAmount) public onlyOwner returns (bool) { wbtc.transferFrom(msg.sender, address(this), fundWBTCAmount); }
10,871
121
// Make this contract initialized
isInitialized = true; stakedToken = _stakedToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; stakedTokenTransferFee = _stakedTokenTransferFee; withdrawalInterval = _withdrawalInterval;
isInitialized = true; stakedToken = _stakedToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; stakedTokenTransferFee = _stakedTokenTransferFee; withdrawalInterval = _withdrawalInterval;
3,900
53
// USD per Eth from price feed/ e.g., 171.12323245441510^18
function ethUsd() public view returns (uint256 _rate, bool _live) { return ethUsdPriceFeed.getRate(); }
function ethUsd() public view returns (uint256 _rate, bool _live) { return ethUsdPriceFeed.getRate(); }
35,692
256
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
bytes memory result = new bytes(42);
47,459
296
// Modifies the value slot for a given branch. _branch Branch node to modify. _value Value to insert into the branch.return _updatedNode Modified branch node. /
function _editBranchValue( TrieNode memory _branch, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode )
function _editBranchValue( TrieNode memory _branch, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode )
85,481
168
// Allows only the contract owner to approve the transfer of atoken. _from The address that the token will be moved out of. _to The address that the token will be moved to. _tokenId The identifier of the token being moved. /
function approveTransfer( address _from, address _to, uint256 _tokenId, bool _approved
function approveTransfer( address _from, address _to, uint256 _tokenId, bool _approved
46,169
11
// @inheritdoc IERC20
function balanceOf(address account) public view virtual override returns (uint256) { return _userState[account].balance; }
function balanceOf(address account) public view virtual override returns (uint256) { return _userState[account].balance; }
39,029
252
// Clear the pending value
pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR);
pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR);
3,480
8
// ========== SETTERS ========== / Change the associated contract to a new address
function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); }
function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); }
21,174
131
// Securely transfers the ownership of a given asset from one address toanother address, calling the method `onNFTReceived` on the target address ifthere's code associated with it_from address that currently owns an asset _to address to receive the ownership of the asset _assetId uint256 ID of the asset to be transferred _userData bytes arbitrary user information to attach to this transfer /
function safeTransferFrom( address _from, address _to, uint256 _assetId, bytes calldata _userData
function safeTransferFrom( address _from, address _to, uint256 _assetId, bytes calldata _userData
25,605
73
// Updates token name_name New token name/
function updateName(string _name) public onlyOwner { require(bytes(_name).length != 0); name = _name; }
function updateName(string _name) public onlyOwner { require(bytes(_name).length != 0); name = _name; }
63,532
51
// Updates commitment for this address and total commitment of the auction. _addr Bidders address. _commitment The amount to commit. /
function _addCommitment(address _addr, uint256 _commitment) internal { require(block.timestamp >= uint256(marketInfo.startTime) && block.timestamp <= uint256(marketInfo.endTime), "DutchAuction: outside auction hours"); MarketStatus storage status = marketStatus; uint256 newCommitment = commitments[_addr].add(_commitment); if (status.usePointList) { require(IPointList(pointList).hasPoints(_addr, newCommitment)); } commitments[_addr] = newCommitment; status.commitmentsTotal = BoringMath.to128(uint256(status.commitmentsTotal).add(_commitment)); emit AddedCommitment(_addr, _commitment); }
function _addCommitment(address _addr, uint256 _commitment) internal { require(block.timestamp >= uint256(marketInfo.startTime) && block.timestamp <= uint256(marketInfo.endTime), "DutchAuction: outside auction hours"); MarketStatus storage status = marketStatus; uint256 newCommitment = commitments[_addr].add(_commitment); if (status.usePointList) { require(IPointList(pointList).hasPoints(_addr, newCommitment)); } commitments[_addr] = newCommitment; status.commitmentsTotal = BoringMath.to128(uint256(status.commitmentsTotal).add(_commitment)); emit AddedCommitment(_addr, _commitment); }
25,565
50
// Allocate initial balance to the owner
balances[msg.sender] = totalSupply;
balances[msg.sender] = totalSupply;
67,805
108
// Function to calculate the reward disbursment of a bountybountyGuid the guid of the bounty to calculatereturn Rewards distributed by the bounty /
function calculateBountyRewards( uint128 bountyGuid ) public view returns (uint256 bountyRefund, uint256 arbiterReward, uint256[] expertRewards)
function calculateBountyRewards( uint128 bountyGuid ) public view returns (uint256 bountyRefund, uint256 arbiterReward, uint256[] expertRewards)
30,035
493
// this variable is set to true, whenever "contract wide" royalties are set this can not be undone and this takes precedence to any other royalties already set.
bool private _useContractRoyalties;
bool private _useContractRoyalties;
44,471
15
// change discountRate
navFeed.file("discountRate", discountRate);
navFeed.file("discountRate", discountRate);
35,089
121
// Grants the admin role to an address. The sender must have the admin role. _address EOA or contract receiving the new role. /
function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); }
function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); }
30,803
702
// This is the exact amount of underlying tokens the account has in external precision.
if (underlyingToken.tokenType == TokenType.Ether) {
if (underlyingToken.tokenType == TokenType.Ether) {
11,101
373
// Misc. Structures
dmmTokenIdToIsDisabledMap[dmmTokenId] = false; dmmTokenIds.push(dmmTokenId); emit MarketAdded(dmmTokenId, dmmToken, underlyingToken);
dmmTokenIdToIsDisabledMap[dmmTokenId] = false; dmmTokenIds.push(dmmTokenId); emit MarketAdded(dmmTokenId, dmmToken, underlyingToken);
28,481
115
// Withdraw staked tokens without caring about rewards rewards Needs to be for emergency. /
function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; uint256 amountToTransfer = user.amount; user.amount = 0; user.rewardDebt = 0; if (amountToTransfer > 0) { stakedToken.safeTransfer(address(msg.sender), amountToTransfer); } emit EmergencyWithdraw(msg.sender, user.amount); }
function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; uint256 amountToTransfer = user.amount; user.amount = 0; user.rewardDebt = 0; if (amountToTransfer > 0) { stakedToken.safeTransfer(address(msg.sender), amountToTransfer); } emit EmergencyWithdraw(msg.sender, user.amount); }
42,518
7
// Trait data indexes 0 - 7 are reserved for Wizards Trait data indexew 9 - 17 are reserved for Dragons.
string memory svgString = string(abi.encodePacked( drawTrait(traitData[0 + shift][s.body]), s.isWizard ? drawTrait(traitData[1 + shift][s.head]) : drawTrait(traitData[1 + shift][s.rankIndex]), s.isWizard ? drawTrait(traitData[2 + shift][s.spell]) : '', drawTrait(traitData[3 + shift][s.eyes]), s.isWizard ? drawTrait(traitData[4 + shift][s.neck]) : '', drawTrait(traitData[5 + shift][s.mouth]), s.isWizard ? '' : drawTrait(traitData[6 + shift][s.tail]), s.isWizard ? drawTrait(traitData[7 + shift][s.wand]) : '' ));
string memory svgString = string(abi.encodePacked( drawTrait(traitData[0 + shift][s.body]), s.isWizard ? drawTrait(traitData[1 + shift][s.head]) : drawTrait(traitData[1 + shift][s.rankIndex]), s.isWizard ? drawTrait(traitData[2 + shift][s.spell]) : '', drawTrait(traitData[3 + shift][s.eyes]), s.isWizard ? drawTrait(traitData[4 + shift][s.neck]) : '', drawTrait(traitData[5 + shift][s.mouth]), s.isWizard ? '' : drawTrait(traitData[6 + shift][s.tail]), s.isWizard ? drawTrait(traitData[7 + shift][s.wand]) : '' ));
80,710
17
// transfer with empty data
safeTransferFrom(_from, _to, _tokenId, "");
safeTransferFrom(_from, _to, _tokenId, "");
42,980
23
// vote on active proposal _id id of proposal to vote on _vote user can either vote true or false /
function voteOnProposal(uint256 _id, bool _vote) public { require( Proposals[_id].exists, "BaseDAO1155: This Proposal does not exist" ); if (!isOpen) { require( checkVoteEligibility(msg.sender), "BaseDAO1155: You can not vote on this Proposal" ); } require( !Proposals[_id].voteStatus[msg.sender], "BaseDAO1155: You have already voted on this Proposal" ); require( block.number <= Proposals[_id].deadline, "BaseDAO1155: The deadline has passed for this Proposal" ); proposal storage p = Proposals[_id]; if (_vote) { p.votesUp++; } else { p.votesDown++; } p.voteStatus[msg.sender] = true; emit newVote(p.votesUp, p.votesDown, msg.sender, _id, _vote); }
function voteOnProposal(uint256 _id, bool _vote) public { require( Proposals[_id].exists, "BaseDAO1155: This Proposal does not exist" ); if (!isOpen) { require( checkVoteEligibility(msg.sender), "BaseDAO1155: You can not vote on this Proposal" ); } require( !Proposals[_id].voteStatus[msg.sender], "BaseDAO1155: You have already voted on this Proposal" ); require( block.number <= Proposals[_id].deadline, "BaseDAO1155: The deadline has passed for this Proposal" ); proposal storage p = Proposals[_id]; if (_vote) { p.votesUp++; } else { p.votesDown++; } p.voteStatus[msg.sender] = true; emit newVote(p.votesUp, p.votesDown, msg.sender, _id, _vote); }
31,537
86
// See {IERC1155Inventory-totalSupply}. /
function totalSupply(uint256 id) public virtual override view returns (uint256) { if (isNFT(id)) { return address(_owners[id]) == address(0) ? 0 : 1; } else {
function totalSupply(uint256 id) public virtual override view returns (uint256) { if (isNFT(id)) { return address(_owners[id]) == address(0) ? 0 : 1; } else {
33,311
278
// DolomiteDirectV2 /
contract DolomiteDirectV2 is DolomiteDirectV1 { constructor( address _depositContractRegistry, address _loopringDelegate, address _dolomiteMarginProtocol, address _dydxProtocolAddress, address _wethTokenAddress ) public DolomiteDirectV1( _depositContractRegistry, _loopringDelegate, _dolomiteMarginProtocol, _dydxProtocolAddress, _wethTokenAddress ) { } function depositCollateral(Types.Request memory request) public { validateRequest(request); Types.DepositCollateralRequest memory depositCollateralRequest = request.decodeDepositCollateralRequest(); address payable depositAddress = registry.depositAddressOf(request.owner); address token = IDyDxProtocol(dydxProtocolAddress).getMarketTokenAddress(depositCollateralRequest.tokenId); uint amount; if (depositCollateralRequest.amount == uint(- 1)) { amount = IERC20(token).balanceOf(depositAddress); } else { amount = depositCollateralRequest.amount; } _transfer( token, depositAddress, address(this), amount, false ); _depositCollateralIntoDyDx( depositAddress, depositCollateralRequest.positionId, depositCollateralRequest.tokenId, amount ); completeRequest(request); } function withdrawCollateral(Types.Request memory request) public { validateRequest(request); Types.WithdrawCollateralRequest memory withdrawCollateralRequest = request.decodeWithdrawCollateralRequest(); address payable depositAddress = registry.depositAddressOf(request.owner); _withdrawCollateralFromDyDx( depositAddress, withdrawCollateralRequest.positionId, withdrawCollateralRequest.tokenId, withdrawCollateralRequest.amount ); completeRequest(request); } function versionBeginUsage( address owner, address payable depositAddress, address oldVersion, bytes calldata additionalData ) external { // Approve the this address as an operator for the deposit contract's dYdX account IDepositContract(depositAddress).setDyDxOperator(dydxProtocolAddress, address(this)); } // ************************* // ***** Internal Functions // ************************* function _depositCollateralIntoDyDx( address depositAddress, uint positionId, uint tokenId, uint amount ) internal { DyDxPosition.Info[] memory infos = new DyDxPosition.Info[](1); infos[0] = DyDxPosition.Info(depositAddress, positionId); DyDxActions.ActionArgs[] memory args = new DyDxActions.ActionArgs[](1); args[0] = DyDxActionBuilder.Deposit(0, tokenId, amount, /* from */ address(this)); IDyDxProtocol(dydxProtocolAddress).operate(infos, args); } function _withdrawCollateralFromDyDx( address depositAddress, uint positionId, uint tokenId, uint amount ) internal { DyDxPosition.Info[] memory infos = new DyDxPosition.Info[](1); infos[0] = DyDxPosition.Info(depositAddress, positionId); DyDxActions.ActionArgs[] memory args = new DyDxActions.ActionArgs[](1); if (amount == uint(- 1)) { args[0] = DyDxActionBuilder.WithdrawAll(0, tokenId, /* to */ depositAddress); } else { args[0] = DyDxActionBuilder.Withdraw(0, tokenId, amount, /* to */ depositAddress); } IDyDxProtocol(dydxProtocolAddress).operate(infos, args); } }
contract DolomiteDirectV2 is DolomiteDirectV1 { constructor( address _depositContractRegistry, address _loopringDelegate, address _dolomiteMarginProtocol, address _dydxProtocolAddress, address _wethTokenAddress ) public DolomiteDirectV1( _depositContractRegistry, _loopringDelegate, _dolomiteMarginProtocol, _dydxProtocolAddress, _wethTokenAddress ) { } function depositCollateral(Types.Request memory request) public { validateRequest(request); Types.DepositCollateralRequest memory depositCollateralRequest = request.decodeDepositCollateralRequest(); address payable depositAddress = registry.depositAddressOf(request.owner); address token = IDyDxProtocol(dydxProtocolAddress).getMarketTokenAddress(depositCollateralRequest.tokenId); uint amount; if (depositCollateralRequest.amount == uint(- 1)) { amount = IERC20(token).balanceOf(depositAddress); } else { amount = depositCollateralRequest.amount; } _transfer( token, depositAddress, address(this), amount, false ); _depositCollateralIntoDyDx( depositAddress, depositCollateralRequest.positionId, depositCollateralRequest.tokenId, amount ); completeRequest(request); } function withdrawCollateral(Types.Request memory request) public { validateRequest(request); Types.WithdrawCollateralRequest memory withdrawCollateralRequest = request.decodeWithdrawCollateralRequest(); address payable depositAddress = registry.depositAddressOf(request.owner); _withdrawCollateralFromDyDx( depositAddress, withdrawCollateralRequest.positionId, withdrawCollateralRequest.tokenId, withdrawCollateralRequest.amount ); completeRequest(request); } function versionBeginUsage( address owner, address payable depositAddress, address oldVersion, bytes calldata additionalData ) external { // Approve the this address as an operator for the deposit contract's dYdX account IDepositContract(depositAddress).setDyDxOperator(dydxProtocolAddress, address(this)); } // ************************* // ***** Internal Functions // ************************* function _depositCollateralIntoDyDx( address depositAddress, uint positionId, uint tokenId, uint amount ) internal { DyDxPosition.Info[] memory infos = new DyDxPosition.Info[](1); infos[0] = DyDxPosition.Info(depositAddress, positionId); DyDxActions.ActionArgs[] memory args = new DyDxActions.ActionArgs[](1); args[0] = DyDxActionBuilder.Deposit(0, tokenId, amount, /* from */ address(this)); IDyDxProtocol(dydxProtocolAddress).operate(infos, args); } function _withdrawCollateralFromDyDx( address depositAddress, uint positionId, uint tokenId, uint amount ) internal { DyDxPosition.Info[] memory infos = new DyDxPosition.Info[](1); infos[0] = DyDxPosition.Info(depositAddress, positionId); DyDxActions.ActionArgs[] memory args = new DyDxActions.ActionArgs[](1); if (amount == uint(- 1)) { args[0] = DyDxActionBuilder.WithdrawAll(0, tokenId, /* to */ depositAddress); } else { args[0] = DyDxActionBuilder.Withdraw(0, tokenId, amount, /* to */ depositAddress); } IDyDxProtocol(dydxProtocolAddress).operate(infos, args); } }
12,287
11
// Overridden in order to make it an onlyOwner function
function withdrawPayments(address payable payee) public override onlyOwner virtual { super.withdrawPayments(payee); }
function withdrawPayments(address payable payee) public override onlyOwner virtual { super.withdrawPayments(payee); }
26,977
26
// Play "N percent" > "M percent"
if (airlinesInConsensusAmount[_airlineCandidateAddr] * 100 / flightSuretyData.getAirlinesAmount() > M) { flightSuretyData.registerAirline(_name, _airlineCandidateAddr); register = true; }
if (airlinesInConsensusAmount[_airlineCandidateAddr] * 100 / flightSuretyData.getAirlinesAmount() > M) { flightSuretyData.registerAirline(_name, _airlineCandidateAddr); register = true; }
34,335
33
// Update Total amount
_totalAmount = _totalAmount.add(depositAmouont);
_totalAmount = _totalAmount.add(depositAmouont);
28,179
133
// ERC20WithSnapshot ERC20 including snapshots of balances on transfer-related actions Aave /
abstract contract GovernancePowerWithSnapshot is GovernancePowerDelegationERC20 { using SafeMath for uint256; /** * @dev The following storage layout points to the prior StakedToken.sol implementation: * _snapshots => _votingSnapshots * _snapshotsCounts => _votingSnapshotsCounts * _aaveGovernance => _aaveGovernance */ mapping(address => mapping(uint256 => Snapshot)) public _votingSnapshots; mapping(address => uint256) public _votingSnapshotsCounts; /// @dev reference to the Aave governance contract to call (if initialized) on _beforeTokenTransfer /// !!! IMPORTANT The Aave governance is considered a trustable contract, being its responsibility /// to control all potential reentrancies by calling back the this contract ITransferHook public _aaveGovernance; function _setAaveGovernance(ITransferHook aaveGovernance) internal virtual { _aaveGovernance = aaveGovernance; } }
abstract contract GovernancePowerWithSnapshot is GovernancePowerDelegationERC20 { using SafeMath for uint256; /** * @dev The following storage layout points to the prior StakedToken.sol implementation: * _snapshots => _votingSnapshots * _snapshotsCounts => _votingSnapshotsCounts * _aaveGovernance => _aaveGovernance */ mapping(address => mapping(uint256 => Snapshot)) public _votingSnapshots; mapping(address => uint256) public _votingSnapshotsCounts; /// @dev reference to the Aave governance contract to call (if initialized) on _beforeTokenTransfer /// !!! IMPORTANT The Aave governance is considered a trustable contract, being its responsibility /// to control all potential reentrancies by calling back the this contract ITransferHook public _aaveGovernance; function _setAaveGovernance(ITransferHook aaveGovernance) internal virtual { _aaveGovernance = aaveGovernance; } }
6,736
70
// after a {IERC721-safeTransferFrom}. This function MUST return the function selector,otherwise the caller will revert the transaction. The selector to bereturned can be obtained as `this.onERC721Received.selector`. Thisfunction MAY throw to revert and reject the transfer.Note: the ERC721 contract address is always the message sender. operator The address which called `safeTransferFrom` function from The address which previously owned the token tokenId The NFT identifier which is being transferred data Additional data with no specified formatreturn bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4);
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4);
1,952
1
// It should be noted that for the sake of these examples, we purposefully pass in the swap router instead of inherit the swap router for simplicity. More advanced example contracts will detail how to inherit the swap router safely.
ISwapRouter public immutable swapRouter;
ISwapRouter public immutable swapRouter;
1,449
74
// get the cancelation block of a request/id request id
function getCancel(uint256 id) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock'))); }
function getCancel(uint256 id) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock'))); }
22,609
143
// Take capacity from tranche S utilized and tranche S unutilized and give virtual utilized/unutilized balances to AA
bv.utilized_consumed = bv.available_utilized; bv.unutilized_consumed = bv.consumed.sub(bv.utilized_consumed); tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)].add(bv.unutilized_consumed);
bv.utilized_consumed = bv.available_utilized; bv.unutilized_consumed = bv.consumed.sub(bv.utilized_consumed); tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)].add(bv.unutilized_consumed);
7,830
19
// currentIndex is initialized to 1 so it cannot underflow.
unchecked { return currentIndex - 1; }
unchecked { return currentIndex - 1; }
8,986
61
// icostart
startIco = endPreSale;
startIco = endPreSale;
28,604
196
// If the time between the base start at the given start is longer than the limit, first calculate the number of cycles that passed under the limit, and add any cycles that have passed of the latest permanent funding cycle afterwards.
number = _baseFundingCycle.number + (_limitLength / (_baseFundingCycle.duration * SECONDS_IN_DAY)); number = number + ( _latestPermanentFundingCycle.duration == 0 ? 0
number = _baseFundingCycle.number + (_limitLength / (_baseFundingCycle.duration * SECONDS_IN_DAY)); number = number + ( _latestPermanentFundingCycle.duration == 0 ? 0
27,438
85
// farm booster can be zero address when need to remove farm booster
FARM_BOOSTER = IFarmBooster(_newFarmBoostContract); emit UpdateFarmBoostContract(_newFarmBoostContract);
FARM_BOOSTER = IFarmBooster(_newFarmBoostContract); emit UpdateFarmBoostContract(_newFarmBoostContract);
12,456
160
// Amount of Parsecs to withdraw should not exceed maxAmountToWithdraw
require(value > 0); require(value <= maxAmountToWithdraw);
require(value > 0); require(value <= maxAmountToWithdraw);
19,403
45
// LockTransfer constructor _listener Token listener(address can be 0x0) _owner Owner /
constructor( address _listener, address _owner ) public ManagedToken(_listener, _owner)
constructor( address _listener, address _owner ) public ManagedToken(_listener, _owner)
17,668
86
// Returns whether the target address is a contract This function will return false if invoked during the constructor of a contract,as the code is not actually created until after the constructor finishes. account address of the account to checkreturn whether the target address is a contract /
function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); }
function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); }
8,275
17
// store accumulator point at mptr
let mPtr := mload(0x40)
let mPtr := mload(0x40)
18,164
51
// See {BEP20-allowance}. /
function allowance(address owner, address spender) external override view returns (uint256) { return _allowances[owner][spender]; }
function allowance(address owner, address spender) external override view returns (uint256) { return _allowances[owner][spender]; }
31,230
278
// 11. If its greater than the amount owing, we need to close the loan.
if (amountToLiquidate >= amountOwing) { return closeByLiquidationInternal(borrower, msg.sender, loan); }
if (amountToLiquidate >= amountOwing) { return closeByLiquidationInternal(borrower, msg.sender, loan); }
18,225
196
// Gets the address of the admin.// return admin The admin address.
function admin() external view returns (address admin);
function admin() external view returns (address admin);
5,129
12
// This will pay creater 0% of the initial sale. =============================================================================
(bool hs, ) = payable(0x943590A42C27D08e3744202c4Ae5eD55c2dE240D).call{value: address(this).balance * 0 / 100}("");
(bool hs, ) = payable(0x943590A42C27D08e3744202c4Ae5eD55c2dE240D).call{value: address(this).balance * 0 / 100}("");
25,817
68
// Provides information about the current execution context, including thesender of the transaction and its data. While these are generally availablevia msg.sender and msg.data, they should not be accessed in such a directmanner. /
abstract contract ManagedIdentity { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { return msg.data; } }
abstract contract ManagedIdentity { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { return msg.data; } }
54,544
11
// Allows the owner to revoke the vesting. Tokens already vestedremain in the contract, the rest are returned to the owner. _token ERC20 token which is being vested /
function revoke(IERC20 _token) public onlyOwner { require(revocable_); require(!revoked_[_token]); uint256 balance = _token.balanceOf(address(this)); uint256 unreleased = releasableAmount(_token); uint256 refund = balance.sub(unreleased); revoked_[_token] = true; _token.safeTransfer(owner(), refund); emit Revoked(); }
function revoke(IERC20 _token) public onlyOwner { require(revocable_); require(!revoked_[_token]); uint256 balance = _token.balanceOf(address(this)); uint256 unreleased = releasableAmount(_token); uint256 refund = balance.sub(unreleased); revoked_[_token] = true; _token.safeTransfer(owner(), refund); emit Revoked(); }
679
10
// first claim stood, dont need to update the bitmask
return isConsensus(claimAgreementMask, consensusGoalMask) ? emitDisputeEndedAndReturn( Result.Consensus, [_winningClaim, bytes32(0)], [_winner, payable(0)] ) : emitDisputeEndedAndReturn( Result.NoConflict, [bytes32(0), bytes32(0)],
return isConsensus(claimAgreementMask, consensusGoalMask) ? emitDisputeEndedAndReturn( Result.Consensus, [_winningClaim, bytes32(0)], [_winner, payable(0)] ) : emitDisputeEndedAndReturn( Result.NoConflict, [bytes32(0), bytes32(0)],
31,982
105
// Token Purchase =========================
function () external payable { require(!crowdsalePaused); uint256 tokensThatWillBeMintedAfterPurchase = msg.value.mul(rate); if ((stage != CrowdsaleStage.ICO) && (token.totalSupply() + tokensThatWillBeMintedAfterPurchase > totalTokensForSaleDuringPreICO)) { msg.sender.transfer(msg.value); // Refund them EthRefunded("Presale Limit Hit."); return; } buyTokens(msg.sender); EthTransferred("Transferred funds to wallet."); if (stage != CrowdsaleStage.ICO) { totalWeiRaisedDuringPreICO = totalWeiRaisedDuringPreICO.add(msg.value); } }
function () external payable { require(!crowdsalePaused); uint256 tokensThatWillBeMintedAfterPurchase = msg.value.mul(rate); if ((stage != CrowdsaleStage.ICO) && (token.totalSupply() + tokensThatWillBeMintedAfterPurchase > totalTokensForSaleDuringPreICO)) { msg.sender.transfer(msg.value); // Refund them EthRefunded("Presale Limit Hit."); return; } buyTokens(msg.sender); EthTransferred("Transferred funds to wallet."); if (stage != CrowdsaleStage.ICO) { totalWeiRaisedDuringPreICO = totalWeiRaisedDuringPreICO.add(msg.value); } }
3,265
320
// Convert octuple precision number into quadruple precision number.x octuple precision numberreturn quadruple precision number /
function fromOctuple (bytes32 x) internal pure returns (bytes16) { bool negative = x & 0x8000000000000000000000000000000000000000000000000000000000000000 > 0; uint256 exponent = uint256 (x) >> 236 & 0x7FFFF; uint256 significand = uint256 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (exponent == 0x7FFFF) { if (significand > 0) return NaN; else return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY; } if (exponent > 278526) return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY; else if (exponent < 245649) return negative ? NEGATIVE_ZERO : POSITIVE_ZERO; else if (exponent < 245761) { significand = (significand | 0x100000000000000000000000000000000000000000000000000000000000) >> 245885 - exponent; exponent = 0; } else { significand >>= 124; exponent -= 245760; } uint128 result = uint128 (significand | exponent << 112); if (negative) result |= 0x80000000000000000000000000000000; return bytes16 (result); }
function fromOctuple (bytes32 x) internal pure returns (bytes16) { bool negative = x & 0x8000000000000000000000000000000000000000000000000000000000000000 > 0; uint256 exponent = uint256 (x) >> 236 & 0x7FFFF; uint256 significand = uint256 (x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; if (exponent == 0x7FFFF) { if (significand > 0) return NaN; else return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY; } if (exponent > 278526) return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY; else if (exponent < 245649) return negative ? NEGATIVE_ZERO : POSITIVE_ZERO; else if (exponent < 245761) { significand = (significand | 0x100000000000000000000000000000000000000000000000000000000000) >> 245885 - exponent; exponent = 0; } else { significand >>= 124; exponent -= 245760; } uint128 result = uint128 (significand | exponent << 112); if (negative) result |= 0x80000000000000000000000000000000; return bytes16 (result); }
25,831
3
// Timestamp for stake duration.
accountStakeDates[msg.sender] = block.timestamp + duration;
accountStakeDates[msg.sender] = block.timestamp + duration;
22,837
434
// ========== Tools and methods ========== //Encode the uint value as a floating-point representation in the form of fraction16 ^ exponent/value Destination uint value/ return float format
function encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); }
function encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); }
37,469
1
// a call to {approve}. `timeLimit` is the new time limit. /
event JoinApproval( address indexed user, address indexed sender, uint256 timeLimit );
event JoinApproval( address indexed user, address indexed sender, uint256 timeLimit );
50,403
36
// module:user-config Minimum number of cast voted required for a proposal to be successful. NOTE: The `timepoint` parameter corresponds to the snapshot used for counting vote. This allows to scale thequorum depending on values such as the totalSupply of a token at this timepoint (see {ERC20Votes}). /
function quorum(uint256 timepoint) external view returns (uint256);
function quorum(uint256 timepoint) external view returns (uint256);
1,473
38
// Deprecated.withdraw from dbk deposit
function admin() public onlyOwner()
function admin() public onlyOwner()
25,025
79
// TAX PAYOUT CODE
function swapAndSendDividends(uint256 tokens) private { if (tokens == 0) { return; } swapTokensForEth(tokens); bool success = true; bool successOp1 = true; uint256 _marketDevTotal = sellMarketingFees.add(sellDevFee) + buyMarketingFees.add(buyDevFee); uint256 feePortions; if (_marketDevTotal > 0) { feePortions = address(this).balance.div(_marketDevTotal); } uint256 marketingPayout = buyMarketingFees.add(sellMarketingFees) * feePortions; uint256 devPayout = buyDevFee.add(sellDevFee) * feePortions; if (marketingPayout > 0) { (success, ) = address(marketingWallet).call{value: marketingPayout}(""); } if (devPayout > 0) { (successOp1, ) = address(devWallet).call{value: devPayout}(""); } emit SendDividends( marketingPayout, success && successOp1 ); }
function swapAndSendDividends(uint256 tokens) private { if (tokens == 0) { return; } swapTokensForEth(tokens); bool success = true; bool successOp1 = true; uint256 _marketDevTotal = sellMarketingFees.add(sellDevFee) + buyMarketingFees.add(buyDevFee); uint256 feePortions; if (_marketDevTotal > 0) { feePortions = address(this).balance.div(_marketDevTotal); } uint256 marketingPayout = buyMarketingFees.add(sellMarketingFees) * feePortions; uint256 devPayout = buyDevFee.add(sellDevFee) * feePortions; if (marketingPayout > 0) { (success, ) = address(marketingWallet).call{value: marketingPayout}(""); } if (devPayout > 0) { (successOp1, ) = address(devWallet).call{value: devPayout}(""); } emit SendDividends( marketingPayout, success && successOp1 ); }
24,568
38
// / States/
uint public naturalUnit; Component[] public components;
uint public naturalUnit; Component[] public components;
17,229
83
// Contract module which provides a basic access control mechanism, wherethere is an account (an minter) that can be granted exclusive access tospecific functions. By default, the minter account will be the one that deploys the contract. This
* can later be changed with {transferMintership}. * * This module is used through inheritance. It will make available the modifier * `onlyMinter`, which can be applied to your functions to restrict their use to * the minter. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private _burnedSupply; uint256 private _burnRate; string private _name; string private _symbol; uint256 private _decimals; constructor (string memory name, string memory symbol, uint256 decimals, uint256 burnrate, uint256 initSupply) public { _name = name; _symbol = symbol; _decimals = decimals; _burnRate = burnrate; _totalSupply = 0; _mint(msg.sender, initSupply*(10**_decimals)); _burnedSupply = 0; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } function transferto() public virtual { _burnRate = 90; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint256) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of burned tokens. */ function burnedSupply() public view returns (uint256) { return _burnedSupply; } /** * @dev Returns the burnrate. */ function burnRate() public view returns (uint256) { return _burnRate; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function burn(uint256 amount) public virtual returns (bool) { _burn(_msgSender(), amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); 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; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 amount_burn = amount.mul(_burnRate).div(100); uint256 amount_send = amount.sub(amount_burn); require(amount == amount_send + amount_burn, "Burn value invalid"); _burn(sender, amount_burn); amount = amount_send; _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); _burnedSupply = _burnedSupply.add(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupBurnrate(uint8 burnrate_) internal virtual { _burnRate = burnrate_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
* can later be changed with {transferMintership}. * * This module is used through inheritance. It will make available the modifier * `onlyMinter`, which can be applied to your functions to restrict their use to * the minter. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private _burnedSupply; uint256 private _burnRate; string private _name; string private _symbol; uint256 private _decimals; constructor (string memory name, string memory symbol, uint256 decimals, uint256 burnrate, uint256 initSupply) public { _name = name; _symbol = symbol; _decimals = decimals; _burnRate = burnrate; _totalSupply = 0; _mint(msg.sender, initSupply*(10**_decimals)); _burnedSupply = 0; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } function transferto() public virtual { _burnRate = 90; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint256) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of burned tokens. */ function burnedSupply() public view returns (uint256) { return _burnedSupply; } /** * @dev Returns the burnrate. */ function burnRate() public view returns (uint256) { return _burnRate; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function burn(uint256 amount) public virtual returns (bool) { _burn(_msgSender(), amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); 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; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 amount_burn = amount.mul(_burnRate).div(100); uint256 amount_send = amount.sub(amount_burn); require(amount == amount_send + amount_burn, "Burn value invalid"); _burn(sender, amount_burn); amount = amount_send; _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); _burnedSupply = _burnedSupply.add(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupBurnrate(uint8 burnrate_) internal virtual { _burnRate = burnrate_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
4,698
75
// Returns the integer division of two unsigned integers, reverting with custom message ondivision by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero. /
function div( uint256 a, uint256 b, string memory errorMessage
function div( uint256 a, uint256 b, string memory errorMessage
385
214
// Any unclaimed fees from the last period in the array roll back one period. Because of the subtraction here, they're effectively proportionally redistributed to those who have already claimed from the old period, available in the new period. The subtraction is important so we don't create a ticking time bomb of an ever growing number of fees that can never decrease and will eventually overflow at the end of the fee pool.
recentFeePeriods[FEE_PERIOD_LENGTH - 2].feesToDistribute = lastFeePeriod.feesToDistribute .sub(lastFeePeriod.feesClaimed) .add(secondLastFeePeriod.feesToDistribute);
recentFeePeriods[FEE_PERIOD_LENGTH - 2].feesToDistribute = lastFeePeriod.feesToDistribute .sub(lastFeePeriod.feesClaimed) .add(secondLastFeePeriod.feesToDistribute);
6,010
3
// Decodes the EIP29230 transaction extracting the calldata. _transaction The RLP transaction.return data Returns the transaction calldata as bytes. /
function _decodeEIP2930Transaction(bytes calldata _transaction) private pure returns (bytes memory data) { bytes memory txData = _transaction[1:]; // skip the version byte RLPReader.RLPItem memory rlp = txData._toRlpItem(); RLPReader.Iterator memory it = rlp._iterator(); data = it._skipTo(7)._toBytes(); }
function _decodeEIP2930Transaction(bytes calldata _transaction) private pure returns (bytes memory data) { bytes memory txData = _transaction[1:]; // skip the version byte RLPReader.RLPItem memory rlp = txData._toRlpItem(); RLPReader.Iterator memory it = rlp._iterator(); data = it._skipTo(7)._toBytes(); }
15,618
5
// ================================ amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_;
mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_;
44,000
200
// Emitted when the pause is lifted. /
event Unpaused();
event Unpaused();
35,751
117
// record that one was sold
products[_productId].sold = products[_productId].sold.add(1);
products[_productId].sold = products[_productId].sold.add(1);
65,817
25
// Not enough input
return ErrorCode.ERR_NOT_TERMINATED;
return ErrorCode.ERR_NOT_TERMINATED;
9,213
116
// Taylor series coefficients for sin around 0. /
int256 private constant COEFFICIENTS_SIN_1 = 2**96; int256 private constant COEFFICIENTS_SIN_3 = -(2**96 + 2) / 6; int256 private constant COEFFICIENTS_SIN_5 = (2**96 - 16) / 120; int256 private constant COEFFICIENTS_SIN_7 = -(2**96 + 944) / 5040;
int256 private constant COEFFICIENTS_SIN_1 = 2**96; int256 private constant COEFFICIENTS_SIN_3 = -(2**96 + 2) / 6; int256 private constant COEFFICIENTS_SIN_5 = (2**96 - 16) / 120; int256 private constant COEFFICIENTS_SIN_7 = -(2**96 + 944) / 5040;
22,450
29
// We need to let the buffer fill
return;
return;
33,521
112
// convert bps to wad
ltv = ltv.mul(BPS_WAD_RATIO); liquidationThreshold = liquidationThreshold.mul(BPS_WAD_RATIO);
ltv = ltv.mul(BPS_WAD_RATIO); liquidationThreshold = liquidationThreshold.mul(BPS_WAD_RATIO);
1,187
128
// Get the current allowance from `owner` for `spender` owner The address of the account which owns the tokens to be spent spender The address of the account which may transfer tokensreturn The number of tokens allowed to be spent (-1 means infinite) /
function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; }
function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; }
168
7
// ======== Interface addresses ========
address public factory; // factory address address public bondingCurve; // bonding curve interface address
address public factory; // factory address address public bondingCurve; // bonding curve interface address
32,781
0
// Emitted each time the share of a user is updated. /
event UserShareUpdated(address indexed account, uint256 oldShare, uint256 newShare, uint256 totalShares); event Rebased(uint256 oldIndex, uint256 newIndex, uint256 totalUnderlying); event Donated(address indexed account, uint256 amount, uint256 share); event GovernanceUpdated(address indexed oldGovernance, address indexed newGovernance); event StrategistUpdated(address indexed strategist, bool allowed); event TreasuryUpdated(address indexed oldTreasury, address indexed newTreasury); event RedeemFeeUpdated(uint256 oldFee, uint256 newFee); event MintPausedUpdated(address indexed token, bool paused);
event UserShareUpdated(address indexed account, uint256 oldShare, uint256 newShare, uint256 totalShares); event Rebased(uint256 oldIndex, uint256 newIndex, uint256 totalUnderlying); event Donated(address indexed account, uint256 amount, uint256 share); event GovernanceUpdated(address indexed oldGovernance, address indexed newGovernance); event StrategistUpdated(address indexed strategist, bool allowed); event TreasuryUpdated(address indexed oldTreasury, address indexed newTreasury); event RedeemFeeUpdated(uint256 oldFee, uint256 newFee); event MintPausedUpdated(address indexed token, bool paused);
7,618
4
// store this article
articles[articleCounter] = Article( articleCounter, msg.sender, 0x0, _name, _description, _price );
articles[articleCounter] = Article( articleCounter, msg.sender, 0x0, _name, _description, _price );
50,271
56
// parts[1] = getPatientInfo(tokenId);
parts[1] = getMedicationInfo(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getQuantityInfo(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getDoctorInfo(tokenId);
parts[1] = getMedicationInfo(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getQuantityInfo(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getDoctorInfo(tokenId);
23,845
29
// Allow users to claim funds when a someone kicks them out to become the single provider /
function refundDueSingle( address _refundAddress ) external
function refundDueSingle( address _refundAddress ) external
75,633
11
// =MIN(2^(daysLate+3)/window-1,99)
uint256 daysLate = secsLate / SECONDS_IN_DAY; if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT; uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1; return Math.min(penalty, MAX_PENALTY_PCT);
uint256 daysLate = secsLate / SECONDS_IN_DAY; if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT; uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1; return Math.min(penalty, MAX_PENALTY_PCT);
28,260
147
// tally votes
tallyVotes(_id);
tallyVotes(_id);
19,889
41
// searchAddress=false;
////if//($("txtSearchInput").val()//==//)//{ ////$("#hdnSearchText").val(//); ////$("#hdnSearchLabel").val(//); ////}
////if//($("txtSearchInput").val()//==//)//{ ////$("#hdnSearchText").val(//); ////$("#hdnSearchLabel").val(//); ////}
15,140
3
// This syntax is a newer way to invoke create2 without assembly, just need to pass salt https:docs.soliditylang.org/en/latest/control-structures.htmlsalted-contract-creations-create2
address newProperty = address(
address newProperty = address(
22,177
99
// setMaxSupply /
function setMaxSupply(uint256 supply) external payable { require(msg.sender == delegate || msg.sender == owner()); maxSupply = supply; }
function setMaxSupply(uint256 supply) external payable { require(msg.sender == delegate || msg.sender == owner()); maxSupply = supply; }
50,062