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
24
// add investment on given account /
) internal { uint256 _totalInvestmentsOf = totalInvestmentsOfAddress(investor); // create a new investment object investmentsByAddress[investor][_totalInvestmentsOf].tokenId = tokenId; investmentsByAddress[investor][_totalInvestmentsOf].amount = amount; investmentsByAddress[investor][_totalInvestmentsOf] .tokenPrice = tokenPrice; investmentsByAddress[investor][_totalInvestmentsOf].creationDate = block .timestamp; investmentsByAddress[investor][_totalInvestmentsOf].account = investor; }
) internal { uint256 _totalInvestmentsOf = totalInvestmentsOfAddress(investor); // create a new investment object investmentsByAddress[investor][_totalInvestmentsOf].tokenId = tokenId; investmentsByAddress[investor][_totalInvestmentsOf].amount = amount; investmentsByAddress[investor][_totalInvestmentsOf] .tokenPrice = tokenPrice; investmentsByAddress[investor][_totalInvestmentsOf].creationDate = block .timestamp; investmentsByAddress[investor][_totalInvestmentsOf].account = investor; }
17,620
75
// use last stored affiliate code
_affID = plyr_[_pID].laff;
_affID = plyr_[_pID].laff;
1,976
162
// BearnTokenERC20Chef is the master of BFIE and he is a fair guy. Have fun reading it. Hopefully it's bug-free. God bless. Note that this pool has no minter key as the original MasterChef of Sushi. Instead, the governance will mint BFIE and forward to this pool at the beginning.
contract BearnTokenERC20Chef is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint amount; // How many LP tokens the user has provided. uint rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of BFIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accBfiePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accBfiePerShare` (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. uint accumulatedStakingPower; // will accumulate every time user harvest } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint allocPoint; // How many allocation points assigned to this pool. BFIs to distribute per block. uint lastRewardBlock; // Last block number that BFIs distribution occurs. uint accBfiePerShare; // Accumulated BFIs per share, times 1e18. See below. bool isStarted; // if lastRewardBlock has passed } // The BFIE TOKEN! BearnTokenERC20 public bfie; // BFIE tokens created per block. uint public bfiePerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint public totalAllocPoint = 0; // The block number when BFIE mining starts. uint public startBlock; uint public constant BLOCKS_PER_WEEK = 46500; address public rewardReferral; event Deposit(address indexed user, uint indexed pid, uint amount); event Withdraw(address indexed user, uint indexed pid, uint amount); event EmergencyWithdraw(address indexed user, uint indexed pid, uint amount); event RewardPaid(address indexed user, uint amount); constructor( BearnTokenERC20 _bfie, uint _bfiePerBlock, uint _startBlock ) public { bfie = _bfie; bfiePerBlock = _bfiePerBlock; // supposed to be 0.004 (4e16 wei) [set 0.01 at the first 2 weeks for bonus] startBlock = _startBlock; // supposed to be 11,360,000 (Mon Nov 30 2020 12:00:00 GMT+0) (https://etherscan.io/block/countdown/11360000) } function poolLength() external view returns (uint) { return poolInfo.length; } function setBfiePerBlock(uint _bfiePerBlock) public onlyOwner { massUpdatePools(); bfiePerBlock = _bfiePerBlock; } // Add a new lp to the pool. Can only be called by the owner. function add(uint _allocPoint, IERC20 _lpToken, bool _withUpdate, uint _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, accBfiePerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's BFIE allocation point. Can only be called by the owner. function set(uint _pid, uint _allocPoint) public onlyOwner { massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint); } pool.allocPoint = _allocPoint; } // View function to see pending BFIs on frontend. function pendingBearn(uint _pid, address _user) external view returns (uint) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint accBfiePerShare = pool.accBfiePerShare; uint lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint _numBlocks = block.number.sub(pool.lastRewardBlock); if (totalAllocPoint > 0) { uint _bfieReward = _numBlocks.mul(bfiePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accBfiePerShare = accBfiePerShare.add(_bfieReward.mul(1e18).div(lpSupply)); } } return user.amount.mul(accBfiePerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint length = poolInfo.length; for (uint pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint 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); } if (totalAllocPoint > 0) { uint _numBlocks = block.number.sub(pool.lastRewardBlock); uint _bfieReward = _numBlocks.mul(bfiePerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accBfiePerShare = pool.accBfiePerShare.add(_bfieReward.mul(1e18).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit LP tokens to BearnChef for BFIE allocation. function deposit(uint _pid, uint _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint _pending = user.amount.mul(pool.accBfiePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeBfieTransfer(_sender, _pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(_sender, address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBfiePerShare).div(1e18); emit Deposit(_sender, _pid, _amount); } // Withdraw LP tokens from BearnChef. function withdraw(uint _pid, uint _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint _pending = user.amount.mul(pool.accBfiePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeBfieTransfer(_sender, _pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(_sender, _amount); } user.rewardDebt = user.amount.mul(pool.accBfiePerShare).div(1e18); emit Withdraw(_sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint _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 bfie transfer function, just in case if rounding error causes pool to not have enough BFIs. function safeBfieTransfer(address _to, uint _amount) internal { uint _bfieBal = bfie.balanceOf(address(this)); if (_bfieBal > 0) { if (_amount > _bfieBal) { bfie.transfer(_to, _bfieBal); } else { bfie.transfer(_to, _amount); } } } // This function allows governance to take unsupported tokens out of the contract. 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, uint amount, address to) external onlyOwner { if (block.number < startBlock + BLOCKS_PER_WEEK * 24) {// do not allow to drain lpToken if less than 6 months (end of farming period) uint length = poolInfo.length; for (uint pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; // cant take staked asset require(_token != pool.lpToken, "!pool.lpToken"); } } _token.safeTransfer(to, amount); } }
contract BearnTokenERC20Chef is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint amount; // How many LP tokens the user has provided. uint rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of BFIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accBfiePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accBfiePerShare` (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. uint accumulatedStakingPower; // will accumulate every time user harvest } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint allocPoint; // How many allocation points assigned to this pool. BFIs to distribute per block. uint lastRewardBlock; // Last block number that BFIs distribution occurs. uint accBfiePerShare; // Accumulated BFIs per share, times 1e18. See below. bool isStarted; // if lastRewardBlock has passed } // The BFIE TOKEN! BearnTokenERC20 public bfie; // BFIE tokens created per block. uint public bfiePerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint public totalAllocPoint = 0; // The block number when BFIE mining starts. uint public startBlock; uint public constant BLOCKS_PER_WEEK = 46500; address public rewardReferral; event Deposit(address indexed user, uint indexed pid, uint amount); event Withdraw(address indexed user, uint indexed pid, uint amount); event EmergencyWithdraw(address indexed user, uint indexed pid, uint amount); event RewardPaid(address indexed user, uint amount); constructor( BearnTokenERC20 _bfie, uint _bfiePerBlock, uint _startBlock ) public { bfie = _bfie; bfiePerBlock = _bfiePerBlock; // supposed to be 0.004 (4e16 wei) [set 0.01 at the first 2 weeks for bonus] startBlock = _startBlock; // supposed to be 11,360,000 (Mon Nov 30 2020 12:00:00 GMT+0) (https://etherscan.io/block/countdown/11360000) } function poolLength() external view returns (uint) { return poolInfo.length; } function setBfiePerBlock(uint _bfiePerBlock) public onlyOwner { massUpdatePools(); bfiePerBlock = _bfiePerBlock; } // Add a new lp to the pool. Can only be called by the owner. function add(uint _allocPoint, IERC20 _lpToken, bool _withUpdate, uint _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, accBfiePerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's BFIE allocation point. Can only be called by the owner. function set(uint _pid, uint _allocPoint) public onlyOwner { massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint); } pool.allocPoint = _allocPoint; } // View function to see pending BFIs on frontend. function pendingBearn(uint _pid, address _user) external view returns (uint) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint accBfiePerShare = pool.accBfiePerShare; uint lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint _numBlocks = block.number.sub(pool.lastRewardBlock); if (totalAllocPoint > 0) { uint _bfieReward = _numBlocks.mul(bfiePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accBfiePerShare = accBfiePerShare.add(_bfieReward.mul(1e18).div(lpSupply)); } } return user.amount.mul(accBfiePerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint length = poolInfo.length; for (uint pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint 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); } if (totalAllocPoint > 0) { uint _numBlocks = block.number.sub(pool.lastRewardBlock); uint _bfieReward = _numBlocks.mul(bfiePerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accBfiePerShare = pool.accBfiePerShare.add(_bfieReward.mul(1e18).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit LP tokens to BearnChef for BFIE allocation. function deposit(uint _pid, uint _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint _pending = user.amount.mul(pool.accBfiePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeBfieTransfer(_sender, _pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(_sender, address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBfiePerShare).div(1e18); emit Deposit(_sender, _pid, _amount); } // Withdraw LP tokens from BearnChef. function withdraw(uint _pid, uint _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint _pending = user.amount.mul(pool.accBfiePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeBfieTransfer(_sender, _pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(_sender, _amount); } user.rewardDebt = user.amount.mul(pool.accBfiePerShare).div(1e18); emit Withdraw(_sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint _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 bfie transfer function, just in case if rounding error causes pool to not have enough BFIs. function safeBfieTransfer(address _to, uint _amount) internal { uint _bfieBal = bfie.balanceOf(address(this)); if (_bfieBal > 0) { if (_amount > _bfieBal) { bfie.transfer(_to, _bfieBal); } else { bfie.transfer(_to, _amount); } } } // This function allows governance to take unsupported tokens out of the contract. 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, uint amount, address to) external onlyOwner { if (block.number < startBlock + BLOCKS_PER_WEEK * 24) {// do not allow to drain lpToken if less than 6 months (end of farming period) uint length = poolInfo.length; for (uint pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; // cant take staked asset require(_token != pool.lpToken, "!pool.lpToken"); } } _token.safeTransfer(to, amount); } }
39,284
18
// Get the ownership for the specified tokenId
function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory)
function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory)
7,283
39
// var globalFee = div(mul(mul(div(div(fee,4), allTotalSupply), totalSupply[c]), scaleFactor),totalSupply[c]);
if (c==colorid){ buyerFee = (div(fee,4) + div(theExtraFee,scaleFactor))*scaleFactor - (div(fee, 4) + div(theExtraFee,scaleFactor)) * (scaleFactor - (reserve(colorid) + msg.value - fee) * numTokens * scaleFactor / (totalSupply[colorid] + numTokens) / (msg.value - fee))
if (c==colorid){ buyerFee = (div(fee,4) + div(theExtraFee,scaleFactor))*scaleFactor - (div(fee, 4) + div(theExtraFee,scaleFactor)) * (scaleFactor - (reserve(colorid) + msg.value - fee) * numTokens * scaleFactor / (totalSupply[colorid] + numTokens) / (msg.value - fee))
36,351
15
// generates a number from 0 to 2^n based on the last n blocks /
{ uint256 n = 0; for (uint256 i = 0; i < 3; i++) { n += uint256( keccak256( abi.encodePacked(blockhash(block.number - i - 1), seed) ) ); } return n % max; }
{ uint256 n = 0; for (uint256 i = 0; i < 3; i++) { n += uint256( keccak256( abi.encodePacked(blockhash(block.number - i - 1), seed) ) ); } return n % max; }
13,163
95
// transfer the ETH fee to fee tracker
payable(self.feeTracker).transfer(feePortion);
payable(self.feeTracker).transfer(feePortion);
46,852
6
// Add liquidity to pool (add_liquidity sends LP tokens to address provided as final argument)
return ICurveMeta2(pool).add_liquidity([transferToAmount, 0], _min_mint_amount, msg.sender);
return ICurveMeta2(pool).add_liquidity([transferToAmount, 0], _min_mint_amount, msg.sender);
49,371
108
// Hash(current computed hash + current element of the proof).
computedHash = keccak256(abi.encodePacked(computedSum, computedHash, proofElement));
computedHash = keccak256(abi.encodePacked(computedSum, computedHash, proofElement));
40,154
6
// Fallback function. If ETH has been transferred, call contribute()
function () public payable { contribute(); }
function () public payable { contribute(); }
7,035
51
// commissionAddress = 0x853A3F142430658A32f75A0dc891b98BF4bDF5c1;
currentStep = Step.FundingPreSale;
currentStep = Step.FundingPreSale;
15,355
38
// transfer to government
sentToGovernment = amount - amountToSend; ris3.transfer(msg.sender, amount - amountToSend); emit taxTransferred(msg.sender, amount - amountToSend);
sentToGovernment = amount - amountToSend; ris3.transfer(msg.sender, amount - amountToSend); emit taxTransferred(msg.sender, amount - amountToSend);
22,494
85
// The easiest way to bubble the revert reason is using memory via assembly
assembly { let returndata_size:= mload(returndata) revert(add(32, returndata), returndata_size) }
assembly { let returndata_size:= mload(returndata) revert(add(32, returndata), returndata_size) }
86,923
316
// Set the states the start time, starts the next round if there is one.
if(fundingPhases_[currentPhase_].fundingThreshold > 0) {
if(fundingPhases_[currentPhase_].fundingThreshold > 0) {
1,814
26
// Role based access control mixin for Rasmart Platform/Abha Mai <maiabha82@gmail.com>/Ignore DRY approach to achieve readability
contract RBACMixin { /// @notice Constant string message to throw on lack of access string constant FORBIDDEN = "Haven't enough right to access"; /// @notice Public map of owners mapping (address => bool) public owners; /// @notice Public map of minters mapping (address => bool) public minters; /// @notice The event indicates the addition of a new owner /// @param who is address of added owner event AddOwner(address indexed who); /// @notice The event indicates the deletion of an owner /// @param who is address of deleted owner event DeleteOwner(address indexed who); /// @notice The event indicates the addition of a new minter /// @param who is address of added minter event AddMinter(address indexed who); /// @notice The event indicates the deletion of a minter /// @param who is address of deleted minter event DeleteMinter(address indexed who); constructor () public { _setOwner(msg.sender, true); } /// @notice The functional modifier rejects the interaction of senders who are not owners modifier onlyOwner() { require(isOwner(msg.sender), FORBIDDEN); _; } /// @notice Functional modifier for rejecting the interaction of senders that are not minters modifier onlyMinter() { require(isMinter(msg.sender), FORBIDDEN); _; } /// @notice Look up for the owner role on providen address /// @param _who is address to look up /// @return A boolean of owner role function isOwner(address _who) public view returns (bool) { return owners[_who]; } /// @notice Look up for the minter role on providen address /// @param _who is address to look up /// @return A boolean of minter role function isMinter(address _who) public view returns (bool) { return minters[_who]; } /// @notice Adds the owner role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function addOwner(address _who) public onlyOwner returns (bool) { _setOwner(_who, true); } /// @notice Deletes the owner role to provided address /// @dev Requires owner role to interact /// @param _who is address to delete role /// @return A boolean that indicates if the operation was successful. function deleteOwner(address _who) public onlyOwner returns (bool) { _setOwner(_who, false); } /// @notice Adds the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function addMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, true); } /// @notice Deletes the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to delete role /// @return A boolean that indicates if the operation was successful. function deleteMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, false); } /// @notice Changes the owner role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setOwner(address _who, bool _flag) private returns (bool) { require(owners[_who] != _flag); owners[_who] = _flag; if (_flag) { emit AddOwner(_who); } else { emit DeleteOwner(_who); } return true; } /// @notice Changes the minter role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setMinter(address _who, bool _flag) private returns (bool) { require(minters[_who] != _flag); minters[_who] = _flag; if (_flag) { emit AddMinter(_who); } else { emit DeleteMinter(_who); } return true; } }
contract RBACMixin { /// @notice Constant string message to throw on lack of access string constant FORBIDDEN = "Haven't enough right to access"; /// @notice Public map of owners mapping (address => bool) public owners; /// @notice Public map of minters mapping (address => bool) public minters; /// @notice The event indicates the addition of a new owner /// @param who is address of added owner event AddOwner(address indexed who); /// @notice The event indicates the deletion of an owner /// @param who is address of deleted owner event DeleteOwner(address indexed who); /// @notice The event indicates the addition of a new minter /// @param who is address of added minter event AddMinter(address indexed who); /// @notice The event indicates the deletion of a minter /// @param who is address of deleted minter event DeleteMinter(address indexed who); constructor () public { _setOwner(msg.sender, true); } /// @notice The functional modifier rejects the interaction of senders who are not owners modifier onlyOwner() { require(isOwner(msg.sender), FORBIDDEN); _; } /// @notice Functional modifier for rejecting the interaction of senders that are not minters modifier onlyMinter() { require(isMinter(msg.sender), FORBIDDEN); _; } /// @notice Look up for the owner role on providen address /// @param _who is address to look up /// @return A boolean of owner role function isOwner(address _who) public view returns (bool) { return owners[_who]; } /// @notice Look up for the minter role on providen address /// @param _who is address to look up /// @return A boolean of minter role function isMinter(address _who) public view returns (bool) { return minters[_who]; } /// @notice Adds the owner role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function addOwner(address _who) public onlyOwner returns (bool) { _setOwner(_who, true); } /// @notice Deletes the owner role to provided address /// @dev Requires owner role to interact /// @param _who is address to delete role /// @return A boolean that indicates if the operation was successful. function deleteOwner(address _who) public onlyOwner returns (bool) { _setOwner(_who, false); } /// @notice Adds the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function addMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, true); } /// @notice Deletes the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to delete role /// @return A boolean that indicates if the operation was successful. function deleteMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, false); } /// @notice Changes the owner role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setOwner(address _who, bool _flag) private returns (bool) { require(owners[_who] != _flag); owners[_who] = _flag; if (_flag) { emit AddOwner(_who); } else { emit DeleteOwner(_who); } return true; } /// @notice Changes the minter role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setMinter(address _who, bool _flag) private returns (bool) { require(minters[_who] != _flag); minters[_who] = _flag; if (_flag) { emit AddMinter(_who); } else { emit DeleteMinter(_who); } return true; } }
32,305
185
// Gas spent here starts off proportional to the maximum mint batch size.It gradually moves to O(1) as tokens get transferred around over time. /
function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnershipOf(tokenId)); }
function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnershipOf(tokenId)); }
534
7
// Event emitted when an auction is unpaused./termAuctionId The ID of the auction./termRepoId The ID of the repo.
event CompleteAuctionUnpaused(bytes32 termAuctionId, bytes32 termRepoId);
event CompleteAuctionUnpaused(bytes32 termAuctionId, bytes32 termRepoId);
27,821
158
// set OrePerBlock
function setPerParam(uint256 _amount) public onlyOwner { orePerBlock = _amount; massUpdatePools(); }
function setPerParam(uint256 _amount) public onlyOwner { orePerBlock = _amount; massUpdatePools(); }
41,321
45
// maps the dispute to the Dispute struct
self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: false, reportedMiner: _miner, reportingParty: msg.sender, proposedForkAddress: address(0), executed: false, disputeVotePassed: false, tally: 0 });
self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: false, reportedMiner: _miner, reportingParty: msg.sender, proposedForkAddress: address(0), executed: false, disputeVotePassed: false, tally: 0 });
7,560
78
// Emitted when mint is paused/unpaused by admin or pause guardian
event MintPaused(address iToken, bool paused); function _setMintPaused(address iToken, bool paused) external; function _setAllMintPaused(bool paused) external;
event MintPaused(address iToken, bool paused); function _setMintPaused(address iToken, bool paused) external; function _setAllMintPaused(bool paused) external;
13,218
132
// The CAKE TOKEN!
BeeBandToken public cake; constructor( BeeBandToken _cake
BeeBandToken public cake; constructor( BeeBandToken _cake
10,016
445
// updates the state of the reserve as a consequence of a repay action._reserve the address of the reserve on which the user is repaying_user the address of the borrower_paybackAmountMinusFees the amount being paid back minus fees_balanceIncrease the accrued interest on the borrowed amount/
) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(_reserve, _user); //update the indexes reserves[_reserve].updateCumulativeIndexes(); //compound the cumulated interest to the borrow balance and then subtracting the payback amount if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _paybackAmountMinusFees, user.stableBorrowRate ); } else { reserve.increaseTotalBorrowsVariable(_balanceIncrease); reserve.decreaseTotalBorrowsVariable(_paybackAmountMinusFees); } }
) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(_reserve, _user); //update the indexes reserves[_reserve].updateCumulativeIndexes(); //compound the cumulated interest to the borrow balance and then subtracting the payback amount if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _paybackAmountMinusFees, user.stableBorrowRate ); } else { reserve.increaseTotalBorrowsVariable(_balanceIncrease); reserve.decreaseTotalBorrowsVariable(_paybackAmountMinusFees); } }
12,195
4
// Find all the keys held by this identity for a given purpose _purpose Purpose to findreturn Array with key bytes for that purpose (empty if none) /
function getKeysByPurpose(uint256 _purpose) public view returns(bytes32[] keys)
function getKeysByPurpose(uint256 _purpose) public view returns(bytes32[] keys)
40,527
42
// UUPSUpgradeable
{ // // EVENTS // event Referral(address indexed affiliate, uint128 wad, uint256 numMints); event Withdrawal(address indexed src, uint128 wad); // // VARIABLES // mapping(address => OwnerBalance) private _ownerBalance; mapping(address => mapping(address => uint128)) private _affiliateBalance; Config public config; Options public options; // // METHODS // function initialize( string memory name, string memory symbol, Config calldata config_, address _receiver ) initializerERC721A initializer external { __ERC721A_init(name, symbol); // check max bps not reached and min platform fee. if ( config_.affiliateFee > MAXBPS || config_.platformFee > MAXBPS || config_.platformFee < 500 || config_.discounts.affiliateDiscount > MAXBPS || config_.affiliateSigner == address(0) || config_.maxBatchSize == 0 ) { revert InvalidConfig(); } // ensure mint tiers are correctly ordered from highest to lowest. for (uint256 i = 1; i < config_.discounts.mintTiers.length; i++) { if ( config_.discounts.mintTiers[i].mintDiscount > MAXBPS || config_.discounts.mintTiers[i].numMints > config_.discounts.mintTiers[i - 1].numMints ) { revert InvalidConfig(); } } config = config_; __Ownable_init(); //__UUPSUpgradeable_init(); setDefaultRoyalty(_receiver, config.defaultRoyalty); } // // PUBLIC // function mint( uint256 quantity, address affiliate, bytes calldata signature ) external payable { mintTo(quantity, msg.sender, affiliate, signature); } function batchMintTo( address[] calldata toList, uint256[] calldata quantityList, address affiliate, bytes calldata signature ) external payable { if (quantityList.length != toList.length) { revert InvalidConfig(); } uint256 quantity = 0; { for (uint256 i = 0; i < quantityList.length; i++) { quantity += quantityList[i]; } } uint256 curSupply = _totalMinted(); SnippooLogic.validateMint( config, quantity, owner(), affiliate, curSupply, signature ); { for (uint256 i = 0; i < toList.length; i++) { _mint(toList[i], quantityList[i]); } } SnippooLogic.updateBalances( config, _ownerBalance, _affiliateBalance, affiliate, quantity ); } function mintTo( uint256 quantity, address to, address affiliate, bytes calldata signature ) public payable { uint256 curSupply = _totalMinted(); SnippooLogic.validateMint( config, quantity, owner(), affiliate, curSupply, signature ); _mint(to, quantity); SnippooLogic.updateBalances(config, _ownerBalance, _affiliateBalance, affiliate, quantity); } function withdraw() external { withdrawTokens(address(0)); } function withdrawTokens(address tokenAddress) public { SnippooLogic.withdrawTokens(config, _ownerBalance, _affiliateBalance, owner(), tokenAddress); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); return bytes(config.baseUri).length != 0 ? string(abi.encodePacked(config.baseUri, string.concat(LibString.toString(tokenId), ".json"))) : ""; } // // OWNER ONLY // function setBaseURI(string memory baseUri) external onlyOwner { if (options.uriLocked) { revert LockedForever(); } config.baseUri = baseUri; } /// @notice the password is "forever" function lockURI(string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } options.uriLocked = true; } /// @notice the password is "forever" // max supply cannot subceed total supply. Be careful changing. function setMaxSupply(uint32 maxSupply, string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } if (options.maxSupplyLocked) { revert LockedForever(); } if (maxSupply < _totalMinted()) { revert MaxSupplyExceeded(); } config.maxSupply = maxSupply; } /// @notice the password is "forever" function lockMaxSupply(string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } options.maxSupplyLocked = true; } function setAffiliateFee(uint16 affiliateFee) external onlyOwner { if (options.affiliateFeeLocked) { revert LockedForever(); } if (affiliateFee > MAXBPS) { revert InvalidConfig(); } config.affiliateFee = affiliateFee; } /// @notice the password is "forever" function lockAffiliateFee(string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } options.affiliateFeeLocked = true; } function setDiscounts(Discount calldata discounts) external onlyOwner { if (options.discountsLocked) { revert LockedForever(); } if (discounts.affiliateDiscount > MAXBPS) { revert InvalidConfig(); } // ensure mint tiers are correctly ordered from highest to lowest. for (uint256 i = 1; i < discounts.mintTiers.length; i++) { if ( discounts.mintTiers[i].mintDiscount > MAXBPS || discounts.mintTiers[i].numMints > discounts.mintTiers[i - 1].numMints ) { revert InvalidConfig(); } } config.discounts = discounts; } /// @notice the password is "forever" function lockDiscounts(string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } options.discountsLocked = true; } function setMaxBatchSize(uint32 maxBatchSize) external onlyOwner { config.maxBatchSize = maxBatchSize; } function setTokenAddress(address _newTokenAddress) external onlyOwner { config.tokenAddress = _newTokenAddress; } // // PLATFORM ONLY // function setSuperAffiliatePayout(address superAffiliatePayout) external onlyPlatform { config.superAffiliatePayout = superAffiliatePayout; } // // INTERNAL // function _startTokenId() internal view virtual override returns (uint256) { return 0; } modifier onlyPlatform() { if (msg.sender != PLATFORM) { revert NotPlatform(); } _; } // OPTIONAL ROYALTY ENFORCEMENT WITH OPENSEA function enableRoyaltyEnforcement() external onlyOwner { if (options.royaltyEnforcementLocked) { revert LockedForever(); } _registerForOperatorFiltering(); options.royaltyEnforcementEnabled = true; } function disableRoyaltyEnforcement() external onlyOwner { if (options.royaltyEnforcementLocked) { revert LockedForever(); } options.royaltyEnforcementEnabled = false; } /// @notice the password is "forever" function lockRoyaltyEnforcement(string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } options.royaltyEnforcementLocked = true; } function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { super.setApprovalForAll(operator, approved); } function approve(address operator, uint256 tokenId) public payable override onlyAllowedOperatorApproval(operator) { super.approve(operator, tokenId); } function transferFrom( address from, address to, uint256 tokenId ) public payable override onlyAllowedOperator(from) { super.transferFrom(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public payable override onlyAllowedOperator(from) { super.safeTransferFrom(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public payable override onlyAllowedOperator(from) { super.safeTransferFrom(from, to, tokenId, data); } function _operatorFilteringEnabled() internal view override returns (bool) { return options.royaltyEnforcementEnabled; } //ERC2981 ROYALTY function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721AUpgradeable, ERC2981Upgradeable) returns (bool) { // Supports the following `interfaceId`s: // - IERC165: 0x01ffc9a7 // - IERC721: 0x80ac58cd // - IERC721Metadata: 0x5b5e139f // - IERC2981: 0x2a55205a return ERC721AUpgradeable.supportsInterface(interfaceId) || ERC2981Upgradeable.supportsInterface(interfaceId); } function setDefaultRoyalty(address receiver, uint16 feeNumerator) public onlyOwner { config.defaultRoyalty = feeNumerator; _setDefaultRoyalty(receiver, feeNumerator); } }
{ // // EVENTS // event Referral(address indexed affiliate, uint128 wad, uint256 numMints); event Withdrawal(address indexed src, uint128 wad); // // VARIABLES // mapping(address => OwnerBalance) private _ownerBalance; mapping(address => mapping(address => uint128)) private _affiliateBalance; Config public config; Options public options; // // METHODS // function initialize( string memory name, string memory symbol, Config calldata config_, address _receiver ) initializerERC721A initializer external { __ERC721A_init(name, symbol); // check max bps not reached and min platform fee. if ( config_.affiliateFee > MAXBPS || config_.platformFee > MAXBPS || config_.platformFee < 500 || config_.discounts.affiliateDiscount > MAXBPS || config_.affiliateSigner == address(0) || config_.maxBatchSize == 0 ) { revert InvalidConfig(); } // ensure mint tiers are correctly ordered from highest to lowest. for (uint256 i = 1; i < config_.discounts.mintTiers.length; i++) { if ( config_.discounts.mintTiers[i].mintDiscount > MAXBPS || config_.discounts.mintTiers[i].numMints > config_.discounts.mintTiers[i - 1].numMints ) { revert InvalidConfig(); } } config = config_; __Ownable_init(); //__UUPSUpgradeable_init(); setDefaultRoyalty(_receiver, config.defaultRoyalty); } // // PUBLIC // function mint( uint256 quantity, address affiliate, bytes calldata signature ) external payable { mintTo(quantity, msg.sender, affiliate, signature); } function batchMintTo( address[] calldata toList, uint256[] calldata quantityList, address affiliate, bytes calldata signature ) external payable { if (quantityList.length != toList.length) { revert InvalidConfig(); } uint256 quantity = 0; { for (uint256 i = 0; i < quantityList.length; i++) { quantity += quantityList[i]; } } uint256 curSupply = _totalMinted(); SnippooLogic.validateMint( config, quantity, owner(), affiliate, curSupply, signature ); { for (uint256 i = 0; i < toList.length; i++) { _mint(toList[i], quantityList[i]); } } SnippooLogic.updateBalances( config, _ownerBalance, _affiliateBalance, affiliate, quantity ); } function mintTo( uint256 quantity, address to, address affiliate, bytes calldata signature ) public payable { uint256 curSupply = _totalMinted(); SnippooLogic.validateMint( config, quantity, owner(), affiliate, curSupply, signature ); _mint(to, quantity); SnippooLogic.updateBalances(config, _ownerBalance, _affiliateBalance, affiliate, quantity); } function withdraw() external { withdrawTokens(address(0)); } function withdrawTokens(address tokenAddress) public { SnippooLogic.withdrawTokens(config, _ownerBalance, _affiliateBalance, owner(), tokenAddress); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); return bytes(config.baseUri).length != 0 ? string(abi.encodePacked(config.baseUri, string.concat(LibString.toString(tokenId), ".json"))) : ""; } // // OWNER ONLY // function setBaseURI(string memory baseUri) external onlyOwner { if (options.uriLocked) { revert LockedForever(); } config.baseUri = baseUri; } /// @notice the password is "forever" function lockURI(string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } options.uriLocked = true; } /// @notice the password is "forever" // max supply cannot subceed total supply. Be careful changing. function setMaxSupply(uint32 maxSupply, string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } if (options.maxSupplyLocked) { revert LockedForever(); } if (maxSupply < _totalMinted()) { revert MaxSupplyExceeded(); } config.maxSupply = maxSupply; } /// @notice the password is "forever" function lockMaxSupply(string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } options.maxSupplyLocked = true; } function setAffiliateFee(uint16 affiliateFee) external onlyOwner { if (options.affiliateFeeLocked) { revert LockedForever(); } if (affiliateFee > MAXBPS) { revert InvalidConfig(); } config.affiliateFee = affiliateFee; } /// @notice the password is "forever" function lockAffiliateFee(string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } options.affiliateFeeLocked = true; } function setDiscounts(Discount calldata discounts) external onlyOwner { if (options.discountsLocked) { revert LockedForever(); } if (discounts.affiliateDiscount > MAXBPS) { revert InvalidConfig(); } // ensure mint tiers are correctly ordered from highest to lowest. for (uint256 i = 1; i < discounts.mintTiers.length; i++) { if ( discounts.mintTiers[i].mintDiscount > MAXBPS || discounts.mintTiers[i].numMints > discounts.mintTiers[i - 1].numMints ) { revert InvalidConfig(); } } config.discounts = discounts; } /// @notice the password is "forever" function lockDiscounts(string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } options.discountsLocked = true; } function setMaxBatchSize(uint32 maxBatchSize) external onlyOwner { config.maxBatchSize = maxBatchSize; } function setTokenAddress(address _newTokenAddress) external onlyOwner { config.tokenAddress = _newTokenAddress; } // // PLATFORM ONLY // function setSuperAffiliatePayout(address superAffiliatePayout) external onlyPlatform { config.superAffiliatePayout = superAffiliatePayout; } // // INTERNAL // function _startTokenId() internal view virtual override returns (uint256) { return 0; } modifier onlyPlatform() { if (msg.sender != PLATFORM) { revert NotPlatform(); } _; } // OPTIONAL ROYALTY ENFORCEMENT WITH OPENSEA function enableRoyaltyEnforcement() external onlyOwner { if (options.royaltyEnforcementLocked) { revert LockedForever(); } _registerForOperatorFiltering(); options.royaltyEnforcementEnabled = true; } function disableRoyaltyEnforcement() external onlyOwner { if (options.royaltyEnforcementLocked) { revert LockedForever(); } options.royaltyEnforcementEnabled = false; } /// @notice the password is "forever" function lockRoyaltyEnforcement(string memory password) external onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } options.royaltyEnforcementLocked = true; } function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) { super.setApprovalForAll(operator, approved); } function approve(address operator, uint256 tokenId) public payable override onlyAllowedOperatorApproval(operator) { super.approve(operator, tokenId); } function transferFrom( address from, address to, uint256 tokenId ) public payable override onlyAllowedOperator(from) { super.transferFrom(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public payable override onlyAllowedOperator(from) { super.safeTransferFrom(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public payable override onlyAllowedOperator(from) { super.safeTransferFrom(from, to, tokenId, data); } function _operatorFilteringEnabled() internal view override returns (bool) { return options.royaltyEnforcementEnabled; } //ERC2981 ROYALTY function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721AUpgradeable, ERC2981Upgradeable) returns (bool) { // Supports the following `interfaceId`s: // - IERC165: 0x01ffc9a7 // - IERC721: 0x80ac58cd // - IERC721Metadata: 0x5b5e139f // - IERC2981: 0x2a55205a return ERC721AUpgradeable.supportsInterface(interfaceId) || ERC2981Upgradeable.supportsInterface(interfaceId); } function setDefaultRoyalty(address receiver, uint16 feeNumerator) public onlyOwner { config.defaultRoyalty = feeNumerator; _setDefaultRoyalty(receiver, feeNumerator); } }
19,794
40
// ``` _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ /
library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } }
library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } }
24,786
187
// PreciseMathUtils.percPoints(1, 1) / MathUtils.percPoints(1, 1) => (1027) / 1000000
uint256 constant RESCALE_FACTOR = 10 ** 21;
uint256 constant RESCALE_FACTOR = 10 ** 21;
23,851
470
// Sets the fee recipient for the given fund/_comptrollerProxy The ComptrollerProxy contract for the fund/_recipient The fee recipient
function setRecipientForFund(address _comptrollerProxy, address _recipient) external { require( msg.sender == VaultLib(payable(ComptrollerLib(_comptrollerProxy).getVaultProxy())).getOwner(), "__setRecipientForFund: Only vault owner callable" ); __setRecipientForFund(_comptrollerProxy, _recipient); }
function setRecipientForFund(address _comptrollerProxy, address _recipient) external { require( msg.sender == VaultLib(payable(ComptrollerLib(_comptrollerProxy).getVaultProxy())).getOwner(), "__setRecipientForFund: Only vault owner callable" ); __setRecipientForFund(_comptrollerProxy, _recipient); }
68,628
0
// Given a utxo position and a unique ID, returns an exit priority.The combination of 'exitableAt' and 'txPos' is the priority for Plasma M(ore)VP protocol.'exitableAt' only provides granularity of block, thus add 'txPos' to provide priority for a transaction. exitId unique exit identifier.return An exit priority.Anatomy of returned value, most significant bits first42 bits- timestamp in seconds (exitable_at); we can represent dates until year 14143154 bits- blknumCHILD_BLOCK_INTERVAL10^5 + txindex; 54 bits represent all transactions for 85 years. We are assuming CHILD_BLOCK_INTERVAL = 1000.160 bits - exit id /
function computePriority(uint64 exitableAt, TxPosLib.TxPos memory txPos, uint160 exitId) internal pure returns (uint256)
function computePriority(uint64 exitableAt, TxPosLib.TxPos memory txPos, uint160 exitId) internal pure returns (uint256)
34,430
349
// Cache (v.debtFloorv.liquidationPenalty) to prevent excessive SLOADs [wad]
uint256 auctionDebtFloor;
uint256 auctionDebtFloor;
70,908
44
// Id of this instance of BlobStore. Unique across all blockchains. /
bytes12 contractId;
bytes12 contractId;
820
56
// newPoolSize = currentPoolSize - amount
uint256 newPoolSize = currentPoolSize.sub(amount);
uint256 newPoolSize = currentPoolSize.sub(amount);
38,793
187
// The fallback function corresponds to a donation in ETH. /
function() public payable { sellTokensForEth(msg.sender, msg.value); }
function() public payable { sellTokensForEth(msg.sender, msg.value); }
14,704
208
// Amount is zero.
error AmountIsZero();
error AmountIsZero();
20,063
49
// See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is notrequired by the EIP. See the note at the beginning of {ERC20}; Requirements:- `sender` and `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`.- the caller must have allowance for ``sender``'s tokens of at least`amount`. /
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
6,482
25
// Emits a {Approval} event.
function approve(address spender, uint256 amount) public virtual returns (bool) {
function approve(address spender, uint256 amount) public virtual returns (bool) {
1,160
12
// this is a sample to demostrate how to create a simple organization contract on FLOW/it is recommended to inherit Oragnization contract which is provided by FLOW Kernel
contract MyOrganization is Organization { /// @dev aclAddresses and aclRoles are used to demostrate the ACL capibility provided by Organization address[] aclAddresses; string[] aclRoles; string public constant ROLE_SAMPLE = "ROLE_SAMPLE"; string public constant FUNCTION_HASH_SAMPLE = "FUNCTION_HASH_SAMPLE"; /// @dev constructor of the contract /// intial acl settings are configured in the constructor /// @dev note that the constructor design will be SIMPLIFIED in the future /// registry and instructions settings will be moved to Organization contract in Kernel constructor(string organizationName) Organization(organizationName) public { aclAddresses = new address[](0); aclAddresses.push(msg.sender); aclRoles = new string[](0); aclRoles.push(ROLE_SAMPLE); configureAddressRoleInternal(msg.sender, ROLE_SAMPLE, OpMode.Add); configureFunctionAddressInternal(FUNCTION_HASH_SAMPLE, msg.sender, OpMode.Add); configureFunctionRoleInternal(FUNCTION_HASH_SAMPLE, ROLE_SAMPLE, OpMode.Add); } /// @notice {"cost":1000} /// @dev use notice to determine the cost of the function /// @dev only qualified addresses are allowed to call this function function function1() public authAddresses(aclAddresses) { /// @dev call registry and get a unique organization id /// which is prerequisite of asset creation and management register(); } /// @notice {"cost":1000} /// @dev only qualified roles are allowed to call this function function function2() public authRoles(aclRoles) { /// @dev create an indivisible asset whose inner asset index is 1 and initial amount is 10000 create(0, 1, 10000); } /// @notice {"cost":1000} /// @dev dynamic acl setting by functionHash function function3() public authFunctionHash(FUNCTION_HASH_SAMPLE) { /// @dev mint more asset whose inner asset index is 1 and additional issuance amount is 10000 mint(1, 10000); } }
contract MyOrganization is Organization { /// @dev aclAddresses and aclRoles are used to demostrate the ACL capibility provided by Organization address[] aclAddresses; string[] aclRoles; string public constant ROLE_SAMPLE = "ROLE_SAMPLE"; string public constant FUNCTION_HASH_SAMPLE = "FUNCTION_HASH_SAMPLE"; /// @dev constructor of the contract /// intial acl settings are configured in the constructor /// @dev note that the constructor design will be SIMPLIFIED in the future /// registry and instructions settings will be moved to Organization contract in Kernel constructor(string organizationName) Organization(organizationName) public { aclAddresses = new address[](0); aclAddresses.push(msg.sender); aclRoles = new string[](0); aclRoles.push(ROLE_SAMPLE); configureAddressRoleInternal(msg.sender, ROLE_SAMPLE, OpMode.Add); configureFunctionAddressInternal(FUNCTION_HASH_SAMPLE, msg.sender, OpMode.Add); configureFunctionRoleInternal(FUNCTION_HASH_SAMPLE, ROLE_SAMPLE, OpMode.Add); } /// @notice {"cost":1000} /// @dev use notice to determine the cost of the function /// @dev only qualified addresses are allowed to call this function function function1() public authAddresses(aclAddresses) { /// @dev call registry and get a unique organization id /// which is prerequisite of asset creation and management register(); } /// @notice {"cost":1000} /// @dev only qualified roles are allowed to call this function function function2() public authRoles(aclRoles) { /// @dev create an indivisible asset whose inner asset index is 1 and initial amount is 10000 create(0, 1, 10000); } /// @notice {"cost":1000} /// @dev dynamic acl setting by functionHash function function3() public authFunctionHash(FUNCTION_HASH_SAMPLE) { /// @dev mint more asset whose inner asset index is 1 and additional issuance amount is 10000 mint(1, 10000); } }
23,502
31
// 获取玩家ID 如果不存在,会创建新玩家档案
determinePID(msg.sender); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _tID;
determinePID(msg.sender); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _tID;
67,362
431
// Approve the tokens for the Vault (it does the actual transferring)
require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED);
require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED);
62,691
108
// If the current time is after the vesting period, all tokens are releasable, minus the amount already released.
else if ( currentTime >= vestingSchedule.start + vestingSchedule.duration ) { return vestingSchedule.amountTotal - vestingSchedule.released; }
else if ( currentTime >= vestingSchedule.start + vestingSchedule.duration ) { return vestingSchedule.amountTotal - vestingSchedule.released; }
21,656
105
// Returns the number of tokens in ''owner'''s account. /
function balanceOf(address owner) external view returns(uint256 balance);
function balanceOf(address owner) external view returns(uint256 balance);
43,765
54
// Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],but performing a static call. _Available since v3.3._ /
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); }
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); }
901
13
// setting deadline to avoid scenario where miners hang onto it and execute at a more profitable time
deadline = block.timestamp + 300; // 5 minutes asset_fromToken = IERC20(asset_from); amountToTrade = asset_fromToken.balanceOf(address(this));
deadline = block.timestamp + 300; // 5 minutes asset_fromToken = IERC20(asset_from); amountToTrade = asset_fromToken.balanceOf(address(this));
19,879
2
// Returns the name of the token. /
function name() public view returns (string memory) { return _name; }
function name() public view returns (string memory) { return _name; }
767
66
// full refund because their bid no longer affects the total sale valuation
refundWei = self.hasContributed[msg.sender];
refundWei = self.hasContributed[msg.sender];
1,159
82
// Amount is informed in bridgeableToken currency
event BridgeDeposit(address indexed wallet, uint256 amount); event BridgeExit(address indexed wallet, uint256 amount); event ReserveChanged(address indexed reserve); IERC20 public reserveToken; IBridgableToken public bridgeableToken; ISwapManager public swapManager; address public posBridge;
event BridgeDeposit(address indexed wallet, uint256 amount); event BridgeExit(address indexed wallet, uint256 amount); event ReserveChanged(address indexed reserve); IERC20 public reserveToken; IBridgableToken public bridgeableToken; ISwapManager public swapManager; address public posBridge;
26,313
204
// seance circle: our governance token
address private seanceAddress; SeanceCircle public seance; address public team; // receives 1/8 soul supply address public dao; // recieves 1/8 soul supply
address private seanceAddress; SeanceCircle public seance; address public team; // receives 1/8 soul supply address public dao; // recieves 1/8 soul supply
19,779
59
// For redemption.
for (uint j = balances[user].lastRedemptionPayoutNumber; j < amountOfRedemptionPayouts; j++) { addedRedemption += (balances[user].balance * redemptionPayouts[j].amount) / redemptionPayouts[j].momentTotalSupply; }
for (uint j = balances[user].lastRedemptionPayoutNumber; j < amountOfRedemptionPayouts; j++) { addedRedemption += (balances[user].balance * redemptionPayouts[j].amount) / redemptionPayouts[j].momentTotalSupply; }
38,773
0
// Initializes the contract by setting a `name` and a `symbol` to the token collection./name is a non-empty string/symbol is a non-empty string
constructor(string memory name, string memory symbol) ERC721(name, symbol)
constructor(string memory name, string memory symbol) ERC721(name, symbol)
33,783
0
// The owner of this contract./ return 0 The owner address.
address public owner; constructor () public
address public owner; constructor () public
7,909
369
// Returns the index of the most significant bit of the number,/ where the least significant bit is at index 0 and the most significant bit is at index 255/The function satisfies the property:/ x >= 2mostSignificantBit(x) and x < 2(mostSignificantBit(x)+1)/x the value for which to compute the most significant bit, must be greater than 0/ return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; }
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; }
2,575
149
// Internal function to match an arbitrary number of full or partial orders, each with an arbitrary number of items for offer and consideration, supplying criteria resolvers containing specific token identifiers and associated proofs as well as fulfillments allocating offer components to consideration components.advancedOrdersThe advanced orders to match. Note that both the offerer and fulfiller on each order must first approve this contract (or their conduit if indicated by the order) to transfer any relevant tokens on their behalf and each consideration recipient must implement `onERC1155Received` in order to receive ERC1155 tokens. Also note that the offer and consideration components for
function _matchAdvancedOrders( AdvancedOrder[] memory advancedOrders, CriteriaResolver[] memory criteriaResolvers, Fulfillment[] memory fulfillments, address recipient
function _matchAdvancedOrders( AdvancedOrder[] memory advancedOrders, CriteriaResolver[] memory criteriaResolvers, Fulfillment[] memory fulfillments, address recipient
16,933
104
// Reads an address from a position in a byte array./b Byte array containing an address./index Index in byte array of address./ return address from byte array.
function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address
function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address
362
5
// allow an admin to pause and unpause the adapter inverse the current pause state /
function pauseToggleAdapter() external onlyAdmin { _state.pauseToggle(); }
function pauseToggleAdapter() external onlyAdmin { _state.pauseToggle(); }
30,082
10
// deposit _underlying to mint CappedMkrToken/amount of underlying to deposit/vaultId recipient vault of tokens
function deposit(uint256 amount, uint96 vaultId) public { if (amount == 0) revert CannotDepositZero(); MKRVotingVault votingVault = MKRVotingVault(_mkrVotingVaultController.votingVaultAddress(vaultId)); if (address(votingVault) == address(0)) revert InvalidMKRVotingVault(); IVault vault = IVault(_vaultController.vaultAddress(vaultId)); if (address(vault) == address(0)) revert InvalidVault(); checkCap(amount); // check allowance and ensure transfer success uint256 allowance_ = _underlying.allowance(_msgSender(), address(this)); if (allowance_ < amount) revert InsufficientAllowance(); // mint this token, the collateral token, to the vault ERC20Upgradeable._mint(address(vault), amount); // send the actual underlying to the voting vault for the vault _underlying.safeTransferFrom(_msgSender(), address(votingVault), amount); }
function deposit(uint256 amount, uint96 vaultId) public { if (amount == 0) revert CannotDepositZero(); MKRVotingVault votingVault = MKRVotingVault(_mkrVotingVaultController.votingVaultAddress(vaultId)); if (address(votingVault) == address(0)) revert InvalidMKRVotingVault(); IVault vault = IVault(_vaultController.vaultAddress(vaultId)); if (address(vault) == address(0)) revert InvalidVault(); checkCap(amount); // check allowance and ensure transfer success uint256 allowance_ = _underlying.allowance(_msgSender(), address(this)); if (allowance_ < amount) revert InsufficientAllowance(); // mint this token, the collateral token, to the vault ERC20Upgradeable._mint(address(vault), amount); // send the actual underlying to the voting vault for the vault _underlying.safeTransferFrom(_msgSender(), address(votingVault), amount); }
19,532
416
// revert if we're writing in occupied memory
if gt(ptr, _newLoc) { revert(0x60, 0x20) // empty revert message }
if gt(ptr, _newLoc) { revert(0x60, 0x20) // empty revert message }
14,085
178
// Create lighthouse smart contract _minimalFreeze Minimal freeze value of XRT token _timeoutBlocks Max time of lighthouse silence in blocks _name Lighthouse subdomain, example: for 'my-name' will created 'my-name.lighthouse.1.robonomics.eth' domain /
function createLighthouse( uint256 _minimalFreeze, uint256 _timeoutBlocks, string _name ) external returns (address lighthouse)
function createLighthouse( uint256 _minimalFreeze, uint256 _timeoutBlocks, string _name ) external returns (address lighthouse)
61,826
32
// set how many blocks a token is locked from trading for after withdrawing
function setWithdrawalLockBlocks(uint32 _blocks) external { _requireAdmin(); withdrawalLockBlocks = _blocks; }
function setWithdrawalLockBlocks(uint32 _blocks) external { _requireAdmin(); withdrawalLockBlocks = _blocks; }
9,206
13
// Returns whether the transfer with the submissionId was claimed./ submissionId is generated in getSubmissionIdFrom
mapping(bytes32 => bool) public override isSubmissionUsed;
mapping(bytes32 => bool) public override isSubmissionUsed;
76,711
53
// To set new fee denominator for creator & resolver./_othersFeeDenominator new creator & resolver fee denominator.
function setOthersFeeDenominator(uint16 _othersFeeDenominator) external onlyOwner { OTHERS_FEE_DENOMINATOR = _othersFeeDenominator; emit NewOthersFeeDenominator(_othersFeeDenominator, block.timestamp); }
function setOthersFeeDenominator(uint16 _othersFeeDenominator) external onlyOwner { OTHERS_FEE_DENOMINATOR = _othersFeeDenominator; emit NewOthersFeeDenominator(_othersFeeDenominator, block.timestamp); }
11,500
120
// View function to see pending FOBOs on frontend.
function pendingFobo(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accFoboPerShare = pool.accFoboPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 foboReward = multiplier.mul(foboPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accFoboPerShare = accFoboPerShare.add(foboReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accFoboPerShare).div(1e12).sub(user.rewardDebt); }
function pendingFobo(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accFoboPerShare = pool.accFoboPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 foboReward = multiplier.mul(foboPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accFoboPerShare = accFoboPerShare.add(foboReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accFoboPerShare).div(1e12).sub(user.rewardDebt); }
23,270
210
// MathHelpers Contract/Enzyme Council <[email protected]>/Helper functions for common math operations
abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio. /// Caller is responsible as-necessary for: /// 1. validating _quantity1 to be non-zero /// 2. validating relativeQuantity2_ to be non-zero function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } }
abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio. /// Caller is responsible as-necessary for: /// 1. validating _quantity1 to be non-zero /// 2. validating relativeQuantity2_ to be non-zero function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } }
52,026
34
// Initializes a buffer with an initial capacity.buf The buffer to initialize.capacity The number of bytes of space to allocate the buffer. return The buffer, for chaining./
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } return buf; }
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } return buf; }
26,917
59
// Router for SushiSwaps.
contract UniswapV2Router02 { using SafeMath for uint; address constant sushiSwapFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); _; } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) private returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (ISushiSwap(sushiSwapFactory).getPair(tokenA, tokenB) == address(0)) { ISushiSwap(sushiSwapFactory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(sushiSwapFactory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidityInternal( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) internal ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UniswapV2Library.pairFor(sushiSwapFactory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = ISushiSwap(pair).mint(to); } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UniswapV2Library.pairFor(sushiSwapFactory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = ISushiSwap(pair).mint(to); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) private { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(sushiSwapFactory, output, path[i + 2]) : _to; ISushiSwap(UniswapV2Library.pairFor(sushiSwapFactory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokensInternal( uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) internal ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsOut(sushiSwapFactory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(sushiSwapFactory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsOut(sushiSwapFactory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(sushiSwapFactory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } }
contract UniswapV2Router02 { using SafeMath for uint; address constant sushiSwapFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); _; } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) private returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (ISushiSwap(sushiSwapFactory).getPair(tokenA, tokenB) == address(0)) { ISushiSwap(sushiSwapFactory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(sushiSwapFactory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidityInternal( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) internal ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UniswapV2Library.pairFor(sushiSwapFactory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = ISushiSwap(pair).mint(to); } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UniswapV2Library.pairFor(sushiSwapFactory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = ISushiSwap(pair).mint(to); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) private { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(sushiSwapFactory, output, path[i + 2]) : _to; ISushiSwap(UniswapV2Library.pairFor(sushiSwapFactory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokensInternal( uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) internal ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsOut(sushiSwapFactory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(sushiSwapFactory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsOut(sushiSwapFactory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(sushiSwapFactory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } }
64,736
1
// @inheritdocERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC2981Royalties).interfaceId || super.supportsInterface(interfaceId); }
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC2981Royalties).interfaceId || super.supportsInterface(interfaceId); }
21,836
68
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
uniswapV2Router = _uniswapV2Router;
400
4
// Modifiers /
modifier onlyWallet() { require(msg.sender == address(this)); _; }
modifier onlyWallet() { require(msg.sender == address(this)); _; }
7,934
99
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x); uint256 msb = mostSignificantBit(result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16383 + msb) << 112); if (x < 0) result |= 0x80000000000000000000000000000000;
uint256 result = uint256(x > 0 ? x : -x); uint256 msb = mostSignificantBit(result); if (msb < 112) result <<= 112 - msb; else if (msb > 112) result >>= msb - 112; result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16383 + msb) << 112); if (x < 0) result |= 0x80000000000000000000000000000000;
18,496
40
// Only manager is able to call this function Sets USDP limit for a specific collateral asset The address of the main collateral token limit The limit number /
function setTokenDebtLimit(address asset, uint limit) public onlyManager { tokenDebtLimit[asset] = limit; }
function setTokenDebtLimit(address asset, uint limit) public onlyManager { tokenDebtLimit[asset] = limit; }
18,911
277
// The ATIVO TOKEN!
AtivoToken public ativo;
AtivoToken public ativo;
6,575
52
// Transfer from sender to another accountto Destination addressvalue Amount of wfctokens to send/
function transfer(address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) { return super.transfer(to, value); }
function transfer(address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) { return super.transfer(to, value); }
42,228
65
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1);--> BSC Testnet for Pancake!IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); --> PROD address for Pancake?
4,560
31
// authDisabled
for (i = 0; i < authDisabled.length; i++){ if(authDisabled[i]) { workflow.authDisabled = workflow.authDisabled | (1<<i); }
for (i = 0; i < authDisabled.length; i++){ if(authDisabled[i]) { workflow.authDisabled = workflow.authDisabled | (1<<i); }
16,273
198
// Transfer funds to the funds which previously were sent to the proxy
CollateralLike(CollateralJoinLike(gntJoin).collateral()).transfer(bag, collateralAmount); safe = openLockTokenCollateralAndGenerateDebt(manager, taxCollector, gntJoin, coinJoin, collateralType, collateralAmount, deltaWad, false);
CollateralLike(CollateralJoinLike(gntJoin).collateral()).transfer(bag, collateralAmount); safe = openLockTokenCollateralAndGenerateDebt(manager, taxCollector, gntJoin, coinJoin, collateralType, collateralAmount, deltaWad, false);
12,662
33
// for production card
function getCardInfo(uint256 cardId, uint256 existing, uint256 amount) external constant returns (uint256, uint256, uint256, uint256, bool) { return (cardInfo[cardId].cardId, cardInfo[cardId].baseCoinProduction, getCostForCards(cardId, existing, amount), SafeMath.mul(cardInfo[cardId].ethCost, amount),cardInfo[cardId].unitSellable); }
function getCardInfo(uint256 cardId, uint256 existing, uint256 amount) external constant returns (uint256, uint256, uint256, uint256, bool) { return (cardInfo[cardId].cardId, cardInfo[cardId].baseCoinProduction, getCostForCards(cardId, existing, amount), SafeMath.mul(cardInfo[cardId].ethCost, amount),cardInfo[cardId].unitSellable); }
32,210
2
// Add a voter as manager/ When msg.sender isn't specified, default account (i.e., account-0) is considered as the sender
function addVoter() public { Assert.equal(addVoter(acc1, 'Alice'), 1, 'Should be equal to 1'); }
function addVoter() public { Assert.equal(addVoter(acc1, 'Alice'), 1, 'Should be equal to 1'); }
43,879
63
// See {ERC20-totalSupply}./
function totalSupply() external view returns (uint256) { return _totalSupply; }
function totalSupply() external view returns (uint256) { return _totalSupply; }
11,866
24
// Determine how many queens to send, bound by number of remaining queens There are two sets here, so multiply by 2 to offset the division by two sets/ Send queens
toERC1155.safeTransferFrom(address(this), msg.sender, toWQueenERC1155Id, numWQueens, ""); toERC1155.safeTransferFrom(address(this), msg.sender, toBQueenERC1155Id, numBQueens, "");
toERC1155.safeTransferFrom(address(this), msg.sender, toWQueenERC1155Id, numWQueens, ""); toERC1155.safeTransferFrom(address(this), msg.sender, toBQueenERC1155Id, numBQueens, "");
23,507
63
// returns the presale round by number /
function getPresaleRound(uint256 roundId_) external view returns (PresaleRound memory) { return _rounds[roundId_]; }
function getPresaleRound(uint256 roundId_) external view returns (PresaleRound memory) { return _rounds[roundId_]; }
35,286
41
// A Solidity high level call has three parts:1. The target address is checked to verify it contains contract code2. The call itself is made, and success asserted3. The return value is decoded, which in turn checks the size of the returned data. solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
require(address(token).isContract(), "SafeERC20: call to non-contract");
4,914
131
// Now get the price at a higher amount, expected to be lower due to slippage
uint256 _bigAmount = _tokenBalance.mul(maxPercentSell).div(DIVISION_FACTOR); _return = simulateExchange(originID, targetID, _bigAmount, doFlashLoan); _return = _return.mul(10**originDecimals).div(10**targetDecimals); // Convert to origin decimals uint256 _endPrice = _return.mul(1e18).div(_bigAmount); if(_endPrice >= _startPrice){
uint256 _bigAmount = _tokenBalance.mul(maxPercentSell).div(DIVISION_FACTOR); _return = simulateExchange(originID, targetID, _bigAmount, doFlashLoan); _return = _return.mul(10**originDecimals).div(10**targetDecimals); // Convert to origin decimals uint256 _endPrice = _return.mul(1e18).div(_bigAmount); if(_endPrice >= _startPrice){
6,094
32
// Single liquidation function. Closes the trove if its ICR is lower than the minimum collateral ratio.
function liquidate(address _borrower) external override { _requireTroveIsActive(_borrower); address[] memory borrowers = new address[](1); borrowers[0] = _borrower; batchLiquidateTroves(borrowers); }
function liquidate(address _borrower) external override { _requireTroveIsActive(_borrower); address[] memory borrowers = new address[](1); borrowers[0] = _borrower; batchLiquidateTroves(borrowers); }
1,020
4,408
// 2206
entry "memorially" : ENG_ADVERB
entry "memorially" : ENG_ADVERB
23,042
207
// update leftover amount to raise in the bid struct
bids[id].amountToRaise = (multiply(adjustedBid, RAY) > bids[id].amountToRaise) ? 0 : subtract(bids[id].amountToRaise, multiply(adjustedBid, RAY));
bids[id].amountToRaise = (multiply(adjustedBid, RAY) > bids[id].amountToRaise) ? 0 : subtract(bids[id].amountToRaise, multiply(adjustedBid, RAY));
31,433
56
// Now with the tokens this contract can send them to msg.sender
bool xfer = IERC20(token).transfer(msg.sender, deltaBalance); require(xfer, "ERR_ERC20_FALSE"); self.pullPoolShareFromLib(msg.sender, poolShares); self.burnPoolShareFromLib(poolShares);
bool xfer = IERC20(token).transfer(msg.sender, deltaBalance); require(xfer, "ERR_ERC20_FALSE"); self.pullPoolShareFromLib(msg.sender, poolShares); self.burnPoolShareFromLib(poolShares);
9,175
26
// 1538488800 - Tuesday, 2. October 2018 14:00:00 GMT && 1538499600 - Tuesday, 2. October 2018 17:00:00 GMT
if( 1538488800 <= _currentDate && _currentDate <= 1538499600){ return 0; }
if( 1538488800 <= _currentDate && _currentDate <= 1538499600){ return 0; }
43,392
142
// parses the passed in action arguments to get the arguments for a settle vault action _args general action arguments structurereturn arguments for a settle vault action /
function _parseSettleVaultArgs(ActionArgs memory _args) internal pure returns (SettleVaultArgs memory) { require(_args.actionType == ActionType.SettleVault, "A15"); require(_args.owner != address(0), "A16"); require(_args.secondAddress != address(0), "A17"); return SettleVaultArgs({owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress}); }
function _parseSettleVaultArgs(ActionArgs memory _args) internal pure returns (SettleVaultArgs memory) { require(_args.actionType == ActionType.SettleVault, "A15"); require(_args.owner != address(0), "A16"); require(_args.secondAddress != address(0), "A17"); return SettleVaultArgs({owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress}); }
6,619
64
// Get pet information
PetInfo memory petInfo = petsInfo[_petId];
PetInfo memory petInfo = petsInfo[_petId];
52,607
31
// Remove the last item
enabledContracts.pop();
enabledContracts.pop();
50,915
136
// Update lockup information
undelegateRequests[_delegator] = UndelegateStakeRequest({ lockupExpiryBlock: _lockupExpiryBlock, amount: _amount, serviceProvider: _serviceProvider });
undelegateRequests[_delegator] = UndelegateStakeRequest({ lockupExpiryBlock: _lockupExpiryBlock, amount: _amount, serviceProvider: _serviceProvider });
17,940
167
// LEGACY ERC721CreatorCore interface
bytes4 internal constant IERC721CreatorCore_v1 = 0x478c8530;
bytes4 internal constant IERC721CreatorCore_v1 = 0x478c8530;
2,094
22
// A single bond is fixed at bond value, or 0 for user defined value on buy
uint256 amountPerBond = bondValue == 0 ? msg.value : bondValue;
uint256 amountPerBond = bondValue == 0 ? msg.value : bondValue;
48,857
56
// Moves tokens `amount` from `sender` to `recipient`.
* This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _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); }
* This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _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); }
3,059
60
// Modifies a campaign's category._campaignAddress of the campaign_newCategoryId ID of the category being switched to /
function modifyCampaignCategory(Campaign _campaign, uint256 _newCategoryId) external campaignOwner(_campaign) whenNotPaused
function modifyCampaignCategory(Campaign _campaign, uint256 _newCategoryId) external campaignOwner(_campaign) whenNotPaused
15,176
55
// This is the actual transfer function in the token contract, it can/only be called by other functions in this contract./_from The address holding the tokens being transferred/_to The address of the recipient/_amount The amount of tokens to be transferred/ return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
function doTransfer(address _from, address _to, uint _amount
28,535
9
// Allows a user to use the protocol in eMode categoryId The id of the category /
function setUserEMode(uint8 categoryId) external;
function setUserEMode(uint8 categoryId) external;
36,322
141
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; }
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; }
9,604
44
// Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, Emits an {ApprovalForAll} event. Requirements: - `operator` cannot be the caller. /
function setApprovalForAll(address operator, bool approved) external;
function setApprovalForAll(address operator, bool approved) external;
2,564
89
// See {IERC2612Permit-permit}./
function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline");
function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline");
72,548
7
// Updates the subToken implementation for the reserve asset The address of the underlying asset of the reserve to be updated implementation The address of the new subToken implementation /
function updateSubToken(address asset, address implementation) external onlyPoolAdmin { DataTypes.ReserveData memory reserveData = pool.getReserveData(asset); _upgradeTokenImplementation(asset, reserveData.subTokenAddress, implementation); emit SubTokenUpgraded(asset, reserveData.subTokenAddress, implementation); }
function updateSubToken(address asset, address implementation) external onlyPoolAdmin { DataTypes.ReserveData memory reserveData = pool.getReserveData(asset); _upgradeTokenImplementation(asset, reserveData.subTokenAddress, implementation); emit SubTokenUpgraded(asset, reserveData.subTokenAddress, implementation); }
8,910
158
// Buy cozy right from the auction_pepeId Pepe to cozy with_cozyCandidate the pepe to cozy with_candidateAsFather Is the _cozyCandidate father?_pepeReceiver address receiving the pepe after cozy time / solhint-disable-next-line max-line-length
function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable { require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract PepeAuction storage auction = auctions[_pepeId]; // solhint-disable-next-line not-rely-on-time require(now < auction.auctionEnd);// auction must be still going uint256 price = calculateBid(_pepeId); require(msg.value >= price);//must send enough ether uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed? //Send ETH to seller auction.seller.transfer(price - totalFee); //send ETH to beneficiary address affiliate = affiliateContract.userToAffiliate(_pepeReceiver); //solhint-disable-next-line if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate //nothing just to suppress warning } //actual cozytiming if (_candidateAsFather) { if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) { revert(); } } else { // Swap around the two pepes, they have no set gender, the user decides what they are. if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) { revert(); } } //Send pepe to seller of auction if (!pepeContract.transfer(auction.seller, _pepeId)) { revert(); //can't complete transfer if this fails } if (msg.value > price) { //return ether send to much _pepeReceiver.transfer(msg.value - price); } emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event delete auctions[_pepeId];//deletes auction }
function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable { require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract PepeAuction storage auction = auctions[_pepeId]; // solhint-disable-next-line not-rely-on-time require(now < auction.auctionEnd);// auction must be still going uint256 price = calculateBid(_pepeId); require(msg.value >= price);//must send enough ether uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed? //Send ETH to seller auction.seller.transfer(price - totalFee); //send ETH to beneficiary address affiliate = affiliateContract.userToAffiliate(_pepeReceiver); //solhint-disable-next-line if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate //nothing just to suppress warning } //actual cozytiming if (_candidateAsFather) { if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) { revert(); } } else { // Swap around the two pepes, they have no set gender, the user decides what they are. if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) { revert(); } } //Send pepe to seller of auction if (!pepeContract.transfer(auction.seller, _pepeId)) { revert(); //can't complete transfer if this fails } if (msg.value > price) { //return ether send to much _pepeReceiver.transfer(msg.value - price); } emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event delete auctions[_pepeId];//deletes auction }
16,379