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
// SPDX-License-Identifier: MIT /** * ____ ____ _ ___ ____ _ * |_ \ / _| / \ |_ ||_ _| / \ * | \/ | / _ \ | |_/ / / _ \ * | |\ /| | / ___ \ | __'. / ___ \ * _| |_\/_| |_ _/ / \ \_ _| | \ \_ _/ / \ \_ * |_____||_____|____| |____|____||____|____| |____| * * Site: https://maka.finance * Telegram: https://t.me/MakaFinance * Twitter: https://twitter.com/MakaFinance * */ pragma solidity 0.8.5; import "./MakaBase.sol"; // Implements rewards & burns contract Maka is MakaBase { // REWARD CYCLE uint256 private _rewardCyclePeriod = 1 days; // The duration of the reward cycle (e.g. can claim rewards once a day) uint256 private _rewardCycleExtensionThreshold; // If someone sends or receives more than a % of their balance in a transaction, their reward cycle date will increase accordingly mapping(address => uint256) private _nextAvailableClaimDate; // The next available reward claim date for each address uint256 private _totalBNBLiquidityAddedFromFees; // The total number of BNB added to the pool through fees uint256 private _totalBNBClaimed; // The total number of BNB claimed by all addresses uint256 private _totalBNBAsMakaClaimed; // The total number of BNB that was converted to Maka and claimed by all addresses uint256 private _totalBNBAsBusdClaimed; // The total number of BNB that was converted to BUSD and claimed by all addresses mapping(address => uint256) private _bnbRewardClaimed; // The amount of BNB claimed by each address mapping(address => uint256) private _bnbAsBusdClaimed; // The amount of BNB converted to BNB and claimed by each address mapping(address => uint256) private _bnbAsMakaClaimed; // The amount of BNB converted to Maka and claimed by each address mapping(address => bool) private _addressesExcludedFromRewards; // The list of addresses excluded from rewards mapping(address => mapping(address => bool)) private _rewardClaimApprovals; //Used to allow an address to claim rewards on behalf of someone else mapping(address => uint256) private _claimRewardAsBnbPercentage; //Allows users to optionally use a % of the reward pool to receive Bnb automatically mapping(address => uint256) private _claimRewardAsBusdPercentage; //Allows users to optionally use a % of the reward pool to receive Busd automatically mapping(address => uint256) private _claimRewardAsMakaPercentage; //Allows users to optionally use a % of the reward pool to buy Maka automatically uint256 private _minRewardBalance; //The minimum balance required to be eligible for rewards uint256 private _maxClaimAllowed = 100 ether; // Can only claim up to 100 bnb at a time. uint256 private _globalRewardDampeningPercentage = 3; // Rewards are reduced by 3% at the start to fill the main BNB pool faster and ensure consistency in rewards uint256 private _mainBnbPoolSize = 10000 ether; // Any excess BNB after the main pool will be used as reserves to ensure consistency in rewards bool private _rewardAsTokensEnabled; //If enabled, the contract will give out tokens instead of BNB according to the preference of each user uint256 private _gradualBurnMagnitude; // The contract can optionally burn tokens (By buying them from reward pool). This is the magnitude of the burn (1 = 0.01%). uint256 private _gradualBurnTimespan = 1 days; //Burn every 1 day by default uint256 private _lastBurnDate; //The last burn date uint256 private _minBnbPoolSizeBeforeBurn = 10 ether; //The minimum amount of BNB that need to be in the pool before initiating gradual burns // AUTO-CLAIM bool private _autoClaimEnabled; uint256 private _maxGasForAutoClaim = 600000; // The maximum gas to consume for processing the auto-claim queue address[] _rewardClaimQueue; mapping(address => uint) _rewardClaimQueueIndices; uint256 private _rewardClaimQueueIndex; mapping(address => bool) _addressesInRewardClaimQueue; // Mapping between addresses and false/true depending on whether they are queued up for auto-claim or not bool private _reimburseAfterMakaClaimFailure; // If true, and Maka reward claim portion fails, the portion will be given as BNB instead bool private _processingQueue; //Flag that indicates whether the queue is currently being processed and sending out rewards mapping(address => bool) private _whitelistedExternalProcessors; //Contains a list of addresses that are whitelisted for low-gas queue processing uint256 private _sendWeiGasLimit; bool private _excludeNonHumansFromRewards = true; event RewardClaimed(address recipient, uint256 amountBnb, uint256 amountBusd, uint256 amountMaka, uint256 nextAvailableClaimDate); event Burned(uint256 bnbAmount); constructor (address routerAddress, address busdAddr) MakaBase(routerAddress, busdAddr) { // Exclude addresses from rewards _addressesExcludedFromRewards[BURN_WALLET] = true; _addressesExcludedFromRewards[owner()] = true; _addressesExcludedFromRewards[address(this)] = true; _addressesExcludedFromRewards[address(0)] = true; // If someone sends or receives more than 15% of their balance in a transaction, their reward cycle date will increase accordingly setRewardCycleExtensionThreshold(25); } // This function is used to enable all functions of the contract, after the setup of the token sale (e.g. Liquidity) is completed function onActivated() internal override { super.onActivated(); setRewardAsTokensEnabled(true); setAutoClaimEnabled(true); setReimburseAfterMakaClaimFailure(true); setMinRewardBalance(100000 * 10**decimals()); //At least 100000 tokens are required to be eligible for rewards setGradualBurnMagnitude(1); //Buy tokens using 0.01% of reward pool and burn them _lastBurnDate = block.timestamp; } function onBeforeTransfer(address sender, address recipient, uint256 amount) internal override { super.onBeforeTransfer(sender, recipient, amount); if (!isMarketTransfer(sender, recipient)) { return; } // Extend the reward cycle according to the amount transferred. This is done so that users do not abuse the cycle (buy before it ends & sell after they claim the reward) _nextAvailableClaimDate[recipient] += calculateRewardCycleExtension(balanceOf(recipient), amount); _nextAvailableClaimDate[sender] += calculateRewardCycleExtension(balanceOf(sender), amount); bool isSelling = isPancakeSwapPair(recipient); if (!isSelling) { // Wait for a dip :p return; } // Process gradual burns bool burnTriggered = processGradualBurn(); // Do not burn & process queue in the same transaction if (!burnTriggered && isAutoClaimEnabled()) { // Trigger auto-claim try this.processRewardClaimQueue(_maxGasForAutoClaim) { } catch { } } } function onTransfer(address sender, address recipient, uint256 amount) internal override { super.onTransfer(sender, recipient, amount); if (!isMarketTransfer(sender, recipient)) { return; } // Update auto-claim queue after balances have been updated updateAutoClaimQueue(sender); updateAutoClaimQueue(recipient); } function processGradualBurn() private returns(bool) { if (!shouldBurn()) { return false; } uint256 burnAmount = address(this).balance * _gradualBurnMagnitude / 10000; doBuyAndBurn(burnAmount); return true; } function updateAutoClaimQueue(address user) private { bool isQueued = _addressesInRewardClaimQueue[user]; if (!isIncludedInRewards(user)) { if (isQueued) { // Need to dequeue uint index = _rewardClaimQueueIndices[user]; address lastUser = _rewardClaimQueue[_rewardClaimQueue.length - 1]; // Move the last one to this index, and pop it _rewardClaimQueueIndices[lastUser] = index; _rewardClaimQueue[index] = lastUser; _rewardClaimQueue.pop(); // Clean-up delete _rewardClaimQueueIndices[user]; delete _addressesInRewardClaimQueue[user]; } } else { if (!isQueued) { // Need to enqueue _rewardClaimQueue.push(user); _rewardClaimQueueIndices[user] = _rewardClaimQueue.length - 1; _addressesInRewardClaimQueue[user] = true; } } } function claimReward() isHuman nonReentrant external { claimReward(msg.sender); } function claimReward(address user) public { require(msg.sender == user || isClaimApproved(user, msg.sender), "You are not allowed to claim rewards on behalf of this user"); require(isRewardReady(user), "Claim date for this address has not passed yet"); require(isIncludedInRewards(user), "Address is excluded from rewards, make sure there is enough MAKA balance"); bool success = doClaimReward(user); require(success, "Reward claim failed"); } function doClaimReward(address user) private returns (bool) { // Update the next claim date & the total amount claimed _nextAvailableClaimDate[user] = block.timestamp + rewardCyclePeriod(); (uint256 claimBnbRewards, uint256 claimBusdRewards, uint256 claimMakaRewards) = calculateClaimRewards(user); bool tokenClaimSuccess = true; // Claim MAKA tokens if (!claimMaka(user, claimMakaRewards)) { // If token claim fails for any reason, award whole portion as BNB if (_reimburseAfterMakaClaimFailure) { claimBnbRewards += claimMakaRewards; } else { tokenClaimSuccess = false; } claimMakaRewards = 0; } // Claim BUSD tokens bool busdClaimSuccess = true; if (!claimBusd(user, claimBusdRewards)) { claimBnbRewards += claimBusdRewards; claimBusdRewards = 0; busdClaimSuccess = false; } // Claim BNB bool bnbClaimSuccess = claimBNB(user, claimBnbRewards); // Fire the event in case something was claimed if (tokenClaimSuccess || busdClaimSuccess || bnbClaimSuccess) { emit RewardClaimed(user, claimBnbRewards, claimBusdRewards, claimMakaRewards, _nextAvailableClaimDate[user]); } return bnbClaimSuccess && busdClaimSuccess && tokenClaimSuccess; } function claimBNB(address user, uint256 bnbAmount) private returns (bool) { if (bnbAmount == 0) { return true; } // Send the reward to the caller if (_sendWeiGasLimit > 0) { (bool sent,) = user.call{value : bnbAmount, gas: _sendWeiGasLimit}(""); if (!sent) { return false; } } else { (bool sent,) = user.call{value : bnbAmount}(""); if (!sent) { return false; } } _bnbRewardClaimed[user] += bnbAmount; _totalBNBClaimed += bnbAmount; return true; } function claimMaka(address user, uint256 bnbAmount) private returns (bool) { if (bnbAmount == 0) { return true; } bool success = swapBNBForTokens(bnbAmount, user); if (!success) { return false; } _bnbAsMakaClaimed[user] += bnbAmount; _totalBNBAsMakaClaimed += bnbAmount; return true; } function claimBusd(address user, uint256 bnbAmount) private returns (bool) { if (bnbAmount == 0) { return true; } bool success = swapBNBForBusd(bnbAmount, user); if (!success) { return false; } _bnbAsBusdClaimed[user] += bnbAmount; _totalBNBAsBusdClaimed += bnbAmount; return true; } // Processes users in the claim queue and sends out rewards when applicable. The amount of users processed depends on the gas provided, up to 1 cycle through the whole queue. // Note: Any external processor can process the claim queue (e.g. even if auto claim is disabled from the contract, an external contract/user/service can process the queue for it // and pay the gas cost). "gas" parameter is the maximum amount of gas allowed to be consumed function processRewardClaimQueue(uint256 gas) public { require(gas > 0, "Gas limit is required"); uint256 queueLength = _rewardClaimQueue.length; if (queueLength == 0) { return; } uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iteration = 0; _processingQueue = true; // Keep claiming rewards from the list until we either consume all available gas or we finish one cycle while (gasUsed < gas && iteration < queueLength) { if (_rewardClaimQueueIndex >= queueLength) { _rewardClaimQueueIndex = 0; } address user = _rewardClaimQueue[_rewardClaimQueueIndex]; if (isRewardReady(user) && isIncludedInRewards(user)) { doClaimReward(user); } uint256 newGasLeft = gasleft(); if (gasLeft > newGasLeft) { uint256 consumedGas = gasLeft - newGasLeft; gasUsed += consumedGas; gasLeft = newGasLeft; } iteration++; _rewardClaimQueueIndex++; } _processingQueue = false; } // Allows a whitelisted external contract/user/service to process the queue and have a portion of the gas costs refunded. // This can be used to help with transaction fees and payout response time when/if the queue grows too big for the contract. // "gas" parameter is the maximum amount of gas allowed to be used. function processRewardClaimQueueAndRefundGas(uint256 gas) external { require(_whitelistedExternalProcessors[msg.sender], "Not whitelisted - use processRewardClaimQueue instead"); uint256 startGas = gasleft(); processRewardClaimQueue(gas); uint256 gasUsed = startGas - gasleft(); payable(msg.sender).transfer(gasUsed); } function isRewardReady(address user) public view returns(bool) { return _nextAvailableClaimDate[user] <= block.timestamp; } function isIncludedInRewards(address user) public view returns(bool) { if (_excludeNonHumansFromRewards) { if (isContract(user)) { return false; } } return balanceOf(user) >= _minRewardBalance && !_addressesExcludedFromRewards[user]; } // This function calculates how much (and if) the reward cycle of an address should increase based on its current balance and the amount transferred in a transaction function calculateRewardCycleExtension(uint256 balance, uint256 amount) public view returns (uint256) { uint256 basePeriod = rewardCyclePeriod(); if (balance == 0) { // Receiving $Maka on a zero balance address: // This means that either the address has never received tokens before (So its current reward date is 0) in which case we need to set its initial value // Or the address has transferred all of its tokens in the past and has now received some again, in which case we will set the reward date to a date very far in the future return block.timestamp + basePeriod; } uint256 rate = amount * 100 / balance; // Depending on the % of $Maka tokens transferred, relative to the balance, we might need to extend the period if (rate >= _rewardCycleExtensionThreshold) { // If new balance is X percent higher, then we will extend the reward date by X percent uint256 extension = basePeriod * rate / 100; // Cap to the base period if (extension >= basePeriod) { extension = basePeriod; } return extension; } return 0; } function calculateClaimRewards(address ofAddress) public view returns (uint256, uint256, uint256) { uint256 reward = calculateBNBReward(ofAddress); uint256 percentageBnb = _claimRewardAsBnbPercentage[ofAddress]; uint256 percentageBusd = _claimRewardAsBusdPercentage[ofAddress]; uint256 percentageMaka = _claimRewardAsMakaPercentage[ofAddress]; uint256 claimBnbRewards = reward * percentageBnb / 100; uint256 claimBusdRewards = reward * percentageBusd / 100; uint256 claimMakaRewards = reward * percentageMaka / 100; return (claimBnbRewards, claimBusdRewards, claimMakaRewards); } function calculateBNBReward(address ofAddress) public view returns (uint256) { uint256 holdersAmount = totalAmountOfTokensHeld(); uint256 balance = balanceOf(ofAddress); uint256 bnbPool = address(this).balance * (100 - _globalRewardDampeningPercentage) / 100; // Limit to main pool size. The rest of the pool is used as a reserve to improve consistency if (bnbPool > _mainBnbPoolSize) { bnbPool = _mainBnbPoolSize; } // If an address is holding X percent of the supply, then it can claim up to X percent of the reward pool uint256 reward = bnbPool * balance / holdersAmount; if (reward > _maxClaimAllowed) { reward = _maxClaimAllowed; } return reward; } function onPancakeSwapRouterUpdated() internal override { _addressesExcludedFromRewards[pancakeSwapRouterAddress()] = true; _addressesExcludedFromRewards[pancakeSwapPairAddress()] = true; } function isMarketTransfer(address sender, address recipient) internal override view returns(bool) { // Not a market transfer when we are burning or sending out rewards return super.isMarketTransfer(sender, recipient) && !isBurnTransfer(sender, recipient) && !_processingQueue; } function isBurnTransfer(address sender, address recipient) private view returns (bool) { return isPancakeSwapPair(sender) && recipient == BURN_WALLET; } function shouldBurn() public view returns(bool) { return _gradualBurnMagnitude > 0 && address(this).balance >= _minBnbPoolSizeBeforeBurn && block.timestamp - _lastBurnDate > _gradualBurnTimespan; } // Up to 1% manual buyback & burn function buyAndBurn(uint256 bnbAmount) external onlyOwner { require(bnbAmount <= address(this).balance / 100, "Manual burn amount is too high!"); require(bnbAmount > 0, "Amount must be greater than zero"); doBuyAndBurn(bnbAmount); } function doBuyAndBurn(uint256 bnbAmount) private { if (bnbAmount > address(this).balance) { bnbAmount = address(this).balance; } if (bnbAmount == 0) { return; } if (swapBNBForTokens(bnbAmount, BURN_WALLET)) { emit Burned(bnbAmount); } _lastBurnDate = block.timestamp; } function isContract(address account) public view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function totalAmountOfTokensHeld() public view returns (uint256) { return totalSupply() - balanceOf(address(0)) - balanceOf(BURN_WALLET) - balanceOf(pancakeSwapPairAddress()); } function bnbRewardClaimed(address byAddress) public view returns (uint256) { return _bnbRewardClaimed[byAddress]; } function bnbRewardClaimedAsBusd(address byAddress) public view returns (uint256) { return _bnbAsBusdClaimed[byAddress]; } function bnbRewardClaimedAsMaka(address byAddress) public view returns (uint256) { return _bnbAsMakaClaimed[byAddress]; } function totalBNBClaimed() public view returns (uint256) { return _totalBNBClaimed; } function totalBNBClaimedAsMaka() public view returns (uint256) { return _totalBNBAsMakaClaimed; } function totalBNBClaimedAsBusd() public view returns (uint256) { return _totalBNBAsBusdClaimed; } function rewardCyclePeriod() public view returns (uint256) { return _rewardCyclePeriod; } function setRewardCyclePeriod(uint256 period) public onlyOwner { require(period > 0 && period <= 7 days, "Value out of range"); _rewardCyclePeriod = period; } function setRewardCycleExtensionThreshold(uint256 threshold) public onlyOwner { _rewardCycleExtensionThreshold = threshold; } function nextAvailableClaimDate(address ofAddress) public view returns (uint256) { return _nextAvailableClaimDate[ofAddress]; } function maxClaimAllowed() public view returns (uint256) { return _maxClaimAllowed; } function setMaxClaimAllowed(uint256 value) public onlyOwner { require(value > 0, "Value must be greater than zero"); _maxClaimAllowed = value; } function minRewardBalance() public view returns (uint256) { return _minRewardBalance; } function setMinRewardBalance(uint256 balance) public onlyOwner { _minRewardBalance = balance; } function maxGasForAutoClaim() public view returns (uint256) { return _maxGasForAutoClaim; } function setMaxGasForAutoClaim(uint256 gas) public onlyOwner { _maxGasForAutoClaim = gas; } function isAutoClaimEnabled() public view returns (bool) { return _autoClaimEnabled; } function setAutoClaimEnabled(bool isEnabled) public onlyOwner { _autoClaimEnabled = isEnabled; } function isExcludedFromRewards(address addr) public view returns (bool) { return _addressesExcludedFromRewards[addr]; } // Will be used to exclude unicrypt fees/token vesting addresses from rewards function setExcludedFromRewards(address addr, bool isExcluded) public onlyOwner { _addressesExcludedFromRewards[addr] = isExcluded; updateAutoClaimQueue(addr); } function globalRewardDampeningPercentage() public view returns(uint256) { return _globalRewardDampeningPercentage; } function setGlobalRewardDampeningPercentage(uint256 value) public onlyOwner { require(value <= 90, "Cannot be greater than 90%"); _globalRewardDampeningPercentage = value; } function approveClaim(address byAddress, bool isApproved) public { require(byAddress != address(0), "Invalid address"); _rewardClaimApprovals[msg.sender][byAddress] = isApproved; } function isClaimApproved(address ofAddress, address byAddress) public view returns(bool) { return _rewardClaimApprovals[ofAddress][byAddress]; } function isRewardAsTokensEnabled() public view returns(bool) { return _rewardAsTokensEnabled; } function setRewardAsTokensEnabled(bool isEnabled) public onlyOwner { _rewardAsTokensEnabled = isEnabled; } function gradualBurnMagnitude() public view returns (uint256) { return _gradualBurnMagnitude; } function setGradualBurnMagnitude(uint256 magnitude) public onlyOwner { require(magnitude <= 100, "Must be equal or less to 100"); _gradualBurnMagnitude = magnitude; } function gradualBurnTimespan() public view returns (uint256) { return _gradualBurnTimespan; } function setGradualBurnTimespan(uint256 timespan) public onlyOwner { require(timespan >= 5 minutes, "Cannot be less than 5 minutes"); _gradualBurnTimespan = timespan; } function minBnbPoolSizeBeforeBurn() public view returns(uint256) { return _minBnbPoolSizeBeforeBurn; } function setMinBnbPoolSizeBeforeBurn(uint256 amount) public onlyOwner { require(amount > 0, "Amount must be greater than zero"); _minBnbPoolSizeBeforeBurn = amount; } function claimRewardAsBnbPercentage(address ofAddress) public view returns(uint256) { return _claimRewardAsBnbPercentage[ofAddress]; } function claimRewardAsBusdPercentage(address ofAddress) public view returns(uint256) { return _claimRewardAsBusdPercentage[ofAddress]; } function claimRewardAsMakaPercentage(address ofAddress) public view returns(uint256) { return _claimRewardAsMakaPercentage[ofAddress]; } function setClaimRewardPercentage(uint256 percentageBnb, uint256 percentageBusd, uint256 percentageMaka) public { require((percentageBnb + percentageBusd + percentageMaka) == 100, "Sum is not 100%"); _claimRewardAsBnbPercentage[msg.sender] = percentageBnb; _claimRewardAsBusdPercentage[msg.sender] = percentageBusd; _claimRewardAsMakaPercentage[msg.sender] = percentageMaka; } function mainBnbPoolSize() public view returns (uint256) { return _mainBnbPoolSize; } function setMainBnbPoolSize(uint256 size) public onlyOwner { require(size >= 10 ether, "Size is too small"); _mainBnbPoolSize = size; } function isInRewardClaimQueue(address addr) public view returns(bool) { return _addressesInRewardClaimQueue[addr]; } function reimburseAfterMakaClaimFailure() public view returns(bool) { return _reimburseAfterMakaClaimFailure; } function setReimburseAfterMakaClaimFailure(bool value) public onlyOwner { _reimburseAfterMakaClaimFailure = value; } function lastBurnDate() public view returns(uint256) { return _lastBurnDate; } function rewardClaimQueueLength() public view returns(uint256) { return _rewardClaimQueue.length; } function rewardClaimQueueIndex() public view returns(uint256) { return _rewardClaimQueueIndex; } function isWhitelistedExternalProcessor(address addr) public view returns(bool) { return _whitelistedExternalProcessors[addr]; } function setWhitelistedExternalProcessor(address addr, bool isWhitelisted) public onlyOwner { require(addr != address(0), "Invalid address"); _whitelistedExternalProcessors[addr] = isWhitelisted; } function setSendWeiGasLimit(uint256 amount) public onlyOwner { _sendWeiGasLimit = amount; } function setExcludeNonHumansFromRewards(bool exclude) public onlyOwner { _excludeNonHumansFromRewards = exclude; } }
Allows users to optionally use a % of the reward pool to buy Maka automatically
mapping(address => uint256) private _claimRewardAsMakaPercentage;
5,411,724
[ 1, 4625, 348, 7953, 560, 30, 25619, 3677, 358, 8771, 999, 279, 738, 434, 326, 19890, 2845, 358, 30143, 490, 581, 69, 6635, 203, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6770, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 14784, 17631, 1060, 1463, 49, 581, 69, 16397, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x4A3E2FB22cc795B1E0BF89ab9D5111Cae3d13B6e/sources/BaseToken.sol
* @title BASE ERC20 token @dev This is part of an implementation of the BASE Index Fund protocol. BASE is a normal ERC20 token, but its supply can be adjusted by splitting and combining tokens proportionally across all wallets. BASE balances are internally represented with a hidden denomination, 'shares'. We support splitting the currency in expansion and combining the currency on contraction by changing the exchange rate between the hidden 'shares' and the public 'BASE'./ PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH Anytime there is division, there is a risk of numerical instability from rounding errors. In order to minimize this risk, we adhere to the following guidelines: 1) The conversion rate adopted is the number of shares that equals 1 BASE. The inverse rate must not be used--totalShares is always the numerator and _totalSupply is always the denominator. (i.e. If you want to convert shares to BASE instead of multiplying by the inverse rate, you should divide by the normal rate) 2) Share balances converted into BaseToken are always rounded down (truncated). We make the following guarantees: - If address 'A' transfers x BaseToken to address 'B'. A's resulting external balance will be decreased by precisely x BaseToken, and B's external balance will be precisely increased by x BaseToken. We do not guarantee that the sum of all balances equals the result of calling totalSupply(). This is because, for any conversion function 'f()' that has non-zero rounding error, f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). Used for authentication
contract BaseToken is ERC20UpgradeSafe, ERC677Token, OwnableUpgradeSafe { using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogMonetaryPolicyUpdated(address monetaryPolicy); event LogUserBanStatusUpdated(address user, bool banned); address public monetaryPolicy; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_SUPPLY = 8_795_645 * 10**DECIMALS; uint256 private constant INITIAL_SHARES = (MAX_UINT256 / (10 ** 36)) - ((MAX_UINT256 / (10 ** 36)) % INITIAL_SUPPLY); uint256 private _totalShares; uint256 private _totalSupply; uint256 private _sharesPerBASE; mapping(address => uint256) private _shareBalances; mapping(address => bool) public bannedUsers; bool public transfersPaused; bool public rebasesPaused; mapping(address => bool) public transferPauseExemptList; mapping (address => mapping (address => uint256)) private _allowedBASE; function setTransfersPaused(bool _transfersPaused) public onlyOwner { transfersPaused = _transfersPaused; } function setTransferPauseExempt(address user, bool exempt) public onlyOwner { if (exempt) { transferPauseExemptList[user] = true; delete transferPauseExemptList[user]; } } function setTransferPauseExempt(address user, bool exempt) public onlyOwner { if (exempt) { transferPauseExemptList[user] = true; delete transferPauseExemptList[user]; } } } else { function setRebasesPaused(bool _rebasesPaused) public onlyOwner { rebasesPaused = _rebasesPaused; } function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; emit LogMonetaryPolicyUpdated(monetaryPolicy_); } function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256) { require(msg.sender == monetaryPolicy, "only monetary policy"); require(!rebasesPaused, "rebases paused"); if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerBASE = _totalShares.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256) { require(msg.sender == monetaryPolicy, "only monetary policy"); require(!rebasesPaused, "rebases paused"); if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerBASE = _totalShares.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256) { require(msg.sender == monetaryPolicy, "only monetary policy"); require(!rebasesPaused, "rebases paused"); if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerBASE = _totalShares.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } } else { function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256) { require(msg.sender == monetaryPolicy, "only monetary policy"); require(!rebasesPaused, "rebases paused"); if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerBASE = _totalShares.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } function totalShares() public view returns (uint256) { return _totalShares; } function sharesOf(address user) public view returns (uint256) { return _shareBalances[user]; } function mintShares(address recipient, uint256 amount) public { require(msg.sender == monetaryPolicy, "forbidden"); _shareBalances[recipient] = _shareBalances[recipient].add(amount); _totalShares = _totalShares.add(amount); } function burnShares(address recipient, uint256 amount) public { require(msg.sender == monetaryPolicy, "forbidden"); require(_shareBalances[recipient] >= amount, "amount"); _shareBalances[recipient] = _shareBalances[recipient].sub(amount); _totalShares = _totalShares.sub(amount); } function mintSSSS(address recipient, uint256 amount) public { require(msg.sender == monetaryPolicy, "forbidden"); _shareBalances[recipient] = _shareBalances[recipient].add(amount); _totalShares = _totalShares.add(amount); } function initialize() public initializer { __ERC20_init("Base Protocol", "BASE"); _setupDecimals(uint8(DECIMALS)); __Ownable_init(); _totalShares = INITIAL_SHARES; _totalSupply = INITIAL_SUPPLY; _shareBalances[owner()] = _totalShares; _sharesPerBASE = _totalShares.div(_totalSupply); bannedUsers[0xeB31973E0FeBF3e3D7058234a5eBbAe1aB4B8c23] = true; emit Transfer(address(0x0), owner(), _totalSupply); } function setUserBanStatus(address user, bool banned) public onlyOwner { if (banned) { bannedUsers[user] = true; delete bannedUsers[user]; } emit LogUserBanStatusUpdated(user, banned); } function setUserBanStatus(address user, bool banned) public onlyOwner { if (banned) { bannedUsers[user] = true; delete bannedUsers[user]; } emit LogUserBanStatusUpdated(user, banned); } } else { function totalSupply() public override view returns (uint256) { return _totalSupply; } function balanceOf(address who) public override view returns (uint256) { return _shareBalances[who].div(_sharesPerBASE); } function transfer(address to, uint256 value) public override(ERC20UpgradeSafe, ERC677) validRecipient(to) returns (bool) { require(bannedUsers[msg.sender] == false, "you are banned"); require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); uint256 shareValue = value.mul(_sharesPerBASE); _shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(msg.sender, to, value); return true; } function allowance(address owner_, address spender) public override view returns (uint256) { return _allowedBASE[owner_][spender]; } function transferFrom(address from, address to, uint256 value) public override validRecipient(to) returns (bool) { require(bannedUsers[msg.sender] == false, "you are banned"); require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); _allowedBASE[from][msg.sender] = _allowedBASE[from][msg.sender].sub(value); uint256 shareValue = value.mul(_sharesPerBASE); _shareBalances[from] = _shareBalances[from].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(from, to, value); return true; } function approve(address spender, uint256 value) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); _allowedBASE[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); _allowedBASE[msg.sender][spender] = _allowedBASE[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedBASE[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); uint256 oldValue = _allowedBASE[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedBASE[msg.sender][spender] = 0; _allowedBASE[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedBASE[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); uint256 oldValue = _allowedBASE[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedBASE[msg.sender][spender] = 0; _allowedBASE[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedBASE[msg.sender][spender]); return true; } } else { }
5,306,354
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2649, 10250, 4232, 39, 3462, 1147, 632, 5206, 1220, 353, 1087, 434, 392, 4471, 434, 326, 10250, 3340, 478, 1074, 1771, 18, 1377, 10250, 353, 279, 2212, 4232, 39, 3462, 1147, 16, 1496, 2097, 14467, 848, 506, 13940, 635, 20347, 471, 1377, 29189, 2430, 23279, 1230, 10279, 777, 17662, 2413, 18, 1377, 10250, 324, 26488, 854, 12963, 10584, 598, 279, 5949, 10716, 1735, 16, 296, 30720, 10332, 1377, 1660, 2865, 20347, 326, 5462, 316, 17965, 471, 29189, 326, 5462, 603, 16252, 1128, 635, 1377, 12770, 326, 7829, 4993, 3086, 326, 5949, 296, 30720, 11, 471, 326, 1071, 296, 8369, 10332, 19, 453, 22357, 10746, 21203, 6469, 3388, 1360, 16743, 29437, 1360, 4869, 28394, 5502, 957, 1915, 353, 16536, 16, 1915, 353, 279, 18404, 434, 17409, 1804, 2967, 628, 13885, 1334, 18, 657, 1353, 358, 18935, 333, 18404, 16, 732, 1261, 14852, 358, 326, 3751, 9875, 14567, 30, 404, 13, 1021, 4105, 4993, 1261, 3838, 329, 353, 326, 1300, 434, 24123, 716, 1606, 404, 10250, 18, 565, 1021, 8322, 4993, 1297, 486, 506, 1399, 413, 4963, 24051, 353, 3712, 326, 16730, 471, 389, 4963, 3088, 1283, 353, 565, 3712, 326, 15030, 18, 261, 77, 18, 73, 18, 971, 1846, 2545, 358, 1765, 24123, 358, 10250, 3560, 434, 565, 10194, 310, 635, 326, 8322, 4993, 16, 1846, 1410, 12326, 635, 326, 2212, 4993, 13, 576, 13, 25805, 324, 26488, 5970, 1368, 3360, 1345, 854, 3712, 16729, 2588, 261, 23558, 690, 2934, 1660, 1221, 326, 3751, 28790, 30, 300, 971, 1758, 296, 37, 11, 29375, 619, 3360, 1345, 358, 1758, 296, 38, 10332, 432, 1807, 8156, 3903, 11013, 903, 282, 506, 23850, 8905, 635, 13382, 291, 2357, 619, 3360, 1345, 16, 471, 605, 1807, 3903, 11013, 903, 506, 13382, 291, 2357, 282, 31383, 635, 619, 3360, 1345, 18, 1660, 741, 486, 18779, 716, 326, 2142, 434, 777, 324, 26488, 1606, 326, 563, 434, 4440, 2078, 3088, 1283, 7675, 1220, 353, 2724, 16, 364, 1281, 4105, 445, 296, 74, 11866, 716, 711, 1661, 17, 7124, 13885, 555, 16, 284, 12, 92, 20, 13, 397, 284, 12, 92, 21, 13, 397, 1372, 397, 284, 12, 22695, 13, 353, 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 39, 26, 4700, 1345, 16, 14223, 6914, 10784, 9890, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 1702, 364, 509, 5034, 31, 203, 203, 565, 871, 1827, 426, 1969, 12, 11890, 5034, 8808, 7632, 16, 2254, 5034, 2078, 3088, 1283, 1769, 203, 565, 871, 1827, 11415, 14911, 2582, 7381, 12, 2867, 31198, 2582, 1769, 203, 565, 871, 1827, 1299, 38, 304, 1482, 7381, 12, 2867, 729, 16, 1426, 324, 10041, 1769, 203, 203, 565, 1758, 1071, 31198, 2582, 31, 203, 203, 203, 565, 9606, 923, 18241, 12, 2867, 358, 13, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 92, 20, 10019, 203, 3639, 2583, 12, 869, 480, 1758, 12, 2211, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 3238, 5381, 25429, 55, 273, 2468, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 57, 3217, 5034, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 28226, 67, 13272, 23893, 273, 1725, 67, 7235, 25, 67, 1105, 25, 380, 1728, 636, 23816, 55, 31, 203, 565, 2254, 5034, 3238, 5381, 28226, 67, 8325, 7031, 273, 261, 6694, 67, 57, 3217, 5034, 342, 261, 2163, 2826, 6580, 3719, 300, 14015, 6694, 67, 57, 3217, 5034, 342, 261, 2163, 2826, 6580, 3719, 738, 28226, 67, 13272, 23893, 1769, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 24051, 31, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 565, 2254, 5034, 3238, 389, 30720, 2173, 8369, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 14419, 38, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 324, 10041, 6588, 31, 203, 203, 203, 565, 1426, 1071, 29375, 28590, 31, 203, 565, 1426, 1071, 283, 18602, 28590, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 7412, 19205, 424, 5744, 682, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 8151, 8369, 31, 203, 565, 445, 444, 1429, 18881, 28590, 12, 6430, 389, 2338, 18881, 28590, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 29375, 28590, 273, 389, 2338, 18881, 28590, 31, 203, 565, 289, 203, 203, 565, 445, 444, 5912, 19205, 424, 5744, 12, 2867, 729, 16, 1426, 431, 5744, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 309, 261, 338, 5744, 13, 288, 203, 5411, 7412, 19205, 424, 5744, 682, 63, 1355, 65, 273, 638, 31, 203, 5411, 1430, 7412, 19205, 424, 5744, 682, 63, 1355, 15533, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 444, 5912, 19205, 424, 5744, 12, 2867, 729, 16, 1426, 431, 5744, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 309, 261, 338, 5744, 13, 288, 203, 5411, 7412, 19205, 424, 5744, 682, 63, 1355, 65, 273, 638, 31, 203, 5411, 1430, 7412, 19205, 424, 5744, 682, 63, 1355, 15533, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 445, 444, 426, 18602, 28590, 12, 6430, 389, 266, 18602, 28590, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 283, 18602, 28590, 273, 389, 266, 18602, 28590, 31, 203, 565, 289, 203, 203, 565, 445, 444, 11415, 14911, 2582, 12, 2867, 31198, 2582, 67, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 31198, 2582, 273, 31198, 2582, 67, 31, 203, 3639, 3626, 1827, 11415, 14911, 2582, 7381, 12, 2586, 14911, 2582, 67, 1769, 203, 565, 289, 203, 203, 565, 445, 283, 1969, 12, 11890, 5034, 7632, 16, 509, 5034, 14467, 9242, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 31198, 2582, 16, 315, 3700, 31198, 3329, 8863, 203, 3639, 2583, 12, 5, 266, 18602, 28590, 16, 315, 266, 18602, 17781, 8863, 203, 203, 3639, 309, 261, 2859, 1283, 9242, 422, 374, 13, 288, 203, 5411, 3626, 1827, 426, 1969, 12, 12015, 16, 389, 4963, 3088, 1283, 1769, 203, 5411, 327, 389, 4963, 3088, 1283, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 2859, 1283, 9242, 411, 374, 13, 288, 203, 5411, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1717, 12, 11890, 5034, 12, 2859, 1283, 9242, 18, 5113, 1435, 10019, 203, 5411, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1289, 12, 11890, 5034, 12, 2859, 1283, 9242, 10019, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 4963, 3088, 1283, 405, 4552, 67, 13272, 23893, 13, 288, 203, 5411, 389, 4963, 3088, 1283, 273, 4552, 67, 13272, 23893, 31, 203, 3639, 289, 203, 203, 3639, 389, 30720, 2173, 8369, 273, 389, 4963, 24051, 18, 2892, 24899, 4963, 3088, 1283, 1769, 203, 203, 3639, 3626, 1827, 426, 1969, 12, 12015, 16, 389, 4963, 3088, 1283, 1769, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 283, 1969, 12, 11890, 5034, 7632, 16, 509, 5034, 14467, 9242, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 31198, 2582, 16, 315, 3700, 31198, 3329, 8863, 203, 3639, 2583, 12, 5, 266, 18602, 28590, 16, 315, 266, 18602, 17781, 8863, 203, 203, 3639, 309, 261, 2859, 1283, 9242, 422, 374, 13, 288, 203, 5411, 3626, 1827, 426, 1969, 12, 12015, 16, 389, 4963, 3088, 1283, 1769, 203, 5411, 327, 389, 4963, 3088, 1283, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 2859, 1283, 9242, 411, 374, 13, 288, 203, 5411, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1717, 12, 11890, 5034, 12, 2859, 1283, 9242, 18, 5113, 1435, 10019, 203, 5411, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1289, 12, 11890, 5034, 12, 2859, 1283, 9242, 10019, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 4963, 3088, 1283, 405, 4552, 67, 13272, 23893, 13, 288, 203, 5411, 389, 4963, 3088, 1283, 273, 4552, 67, 13272, 23893, 31, 203, 2 ]
./full_match/11155111/0x79173518CDc6f5a65a106253898A04BA70d9a242/sources/project_/contracts/ERC721A.sol
* @dev Transfers `tokenId` from `from` to `to`. 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./ The nested ifs save around 20+ gas over a compound boolean condition. Clear approvals from the previous owner. This is equivalent to `delete _tokenApprovals[tokenId]`. Underflow of the sender's balance is impossible because we check for ownership above and the recipient's balance can't realistically overflow. Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256. We can directly increment and decrement the balances. Updates: - `address` to the next owner. - `startTimestamp` to the timestamp of transfering. - `burned` to `false`. - `nextInitialized` to `true`. If the next slot may not have been initialized (i.e. `nextInitialized == false`) . If the next slot's address is zero and not burned (i.e. packed value is zero). If the next slot is within bounds. Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
function transferFrom( address from, address to, uint256 tokenId ) public payable virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId); if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A())) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedOwnerships[tokenId] = _packOwnershipData( to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); }
3,803,570
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 2604, 18881, 1375, 2316, 548, 68, 628, 1375, 2080, 68, 358, 1375, 869, 8338, 29076, 30, 300, 1375, 2080, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2316, 548, 68, 1147, 1297, 506, 16199, 635, 1375, 2080, 8338, 300, 971, 326, 4894, 353, 486, 1375, 2080, 9191, 518, 1297, 506, 20412, 358, 3635, 333, 1147, 635, 3344, 288, 12908, 537, 97, 578, 288, 542, 23461, 1290, 1595, 5496, 7377, 1282, 279, 288, 5912, 97, 871, 18, 19, 1021, 4764, 309, 87, 1923, 6740, 4200, 15, 16189, 1879, 279, 11360, 1250, 2269, 18, 10121, 6617, 4524, 628, 326, 2416, 3410, 18, 1220, 353, 7680, 358, 1375, 3733, 389, 2316, 12053, 4524, 63, 2316, 548, 65, 8338, 21140, 2426, 434, 326, 5793, 1807, 11013, 353, 23343, 2724, 732, 866, 364, 23178, 5721, 471, 326, 8027, 1807, 11013, 848, 1404, 2863, 5846, 1230, 9391, 18, 9354, 9391, 353, 7290, 1118, 24755, 640, 7688, 5846, 487, 1375, 2316, 548, 68, 4102, 1240, 358, 506, 576, 636, 5034, 18, 1660, 848, 5122, 5504, 471, 15267, 326, 324, 26488, 18, 15419, 30, 300, 1375, 2867, 68, 358, 326, 1024, 3410, 18, 300, 1375, 1937, 4921, 68, 358, 326, 2858, 434, 7412, 310, 18, 300, 1375, 70, 321, 329, 68, 358, 1375, 5743, 8338, 300, 1375, 4285, 11459, 68, 358, 1375, 3767, 8338, 971, 326, 1024, 4694, 2026, 486, 1240, 2118, 6454, 261, 77, 18, 73, 18, 1375, 4285, 11459, 422, 629, 24065, 263, 971, 326, 1024, 4694, 1807, 1758, 353, 3634, 471, 486, 18305, 329, 261, 77, 18, 73, 18, 12456, 460, 353, 3634, 2934, 971, 326, 1024, 4694, 353, 3470, 4972, 18, 9190, 326, 1024, 4694, 358, 17505, 3434, 4496, 364, 1375, 8443, 951, 12, 2316, 548, 397, 404, 13, 8338, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 1071, 8843, 429, 5024, 3849, 288, 203, 3639, 2254, 5034, 2807, 5460, 12565, 4420, 329, 273, 389, 2920, 329, 5460, 12565, 951, 12, 2316, 548, 1769, 203, 203, 3639, 309, 261, 2867, 12, 11890, 16874, 12, 10001, 5460, 12565, 4420, 329, 3719, 480, 628, 13, 15226, 12279, 1265, 16268, 5541, 5621, 203, 203, 3639, 261, 11890, 5034, 20412, 1887, 8764, 16, 1758, 20412, 1887, 13, 273, 389, 588, 31639, 8764, 1876, 1887, 12, 2316, 548, 1769, 203, 203, 3639, 309, 16051, 67, 291, 12021, 31639, 1162, 5541, 12, 25990, 1887, 16, 628, 16, 389, 3576, 12021, 654, 39, 27, 5340, 37, 1435, 3719, 203, 5411, 309, 16051, 291, 31639, 1290, 1595, 12, 2080, 16, 389, 3576, 12021, 654, 39, 27, 5340, 37, 1435, 3719, 15226, 12279, 11095, 1248, 5541, 50, 280, 31639, 5621, 203, 203, 3639, 309, 261, 869, 422, 1758, 12, 20, 3719, 15226, 12279, 774, 7170, 1887, 5621, 203, 203, 3639, 389, 5771, 1345, 1429, 18881, 12, 2080, 16, 358, 16, 1147, 548, 16, 404, 1769, 203, 203, 3639, 19931, 288, 203, 5411, 309, 20412, 1887, 288, 203, 7734, 272, 2233, 12, 25990, 1887, 8764, 16, 374, 13, 203, 5411, 289, 203, 3639, 289, 203, 203, 565, 22893, 288, 203, 203, 3639, 389, 2920, 329, 5460, 12565, 87, 63, 2316, 548, 65, 273, 389, 2920, 5460, 12565, 751, 12, 203, 5411, 358, 16, 203, 5411, 389, 15650, 11704, 67, 25539, 67, 12919, 25991, 571, 389, 4285, 7800, 751, 12, 2080, 16, 358, 16, 2807, 5460, 12565, 4420, 329, 13, 203, 3639, 11272, 203, 203, 3639, 309, 261, 10001, 5460, 12565, 4420, 329, 473, 389, 15650, 11704, 67, 25539, 67, 12919, 25991, 422, 374, 13, 288, 203, 5411, 2254, 5034, 9617, 548, 273, 1147, 548, 397, 404, 31, 203, 5411, 309, 261, 67, 2920, 329, 5460, 12565, 87, 63, 4285, 1345, 548, 65, 422, 374, 13, 288, 203, 7734, 309, 261, 4285, 1345, 548, 480, 389, 2972, 1016, 13, 288, 203, 10792, 389, 2920, 329, 5460, 12565, 87, 63, 4285, 1345, 548, 65, 273, 2807, 5460, 12565, 4420, 329, 31, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 3626, 12279, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 3639, 389, 5205, 1345, 1429, 18881, 12, 2080, 16, 358, 16, 1147, 548, 16, 404, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.4; import "./DNTfixedPointMath.sol"; // Interface for IERC20. 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); } // Interface for IERC20Metadata. interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // Interface for IAccessControl. interface IAccessControl { event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // Interface for IERC165 interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } // Contract for Context. abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // Contract for ERC165 abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // Contract for ERC20. 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } 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 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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } 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; } 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); } 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); } 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); } 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 {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // Contract for AccessControl. abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // Library for SafeCast. library SafeCast { function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // Library for SafeMath 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 for Strings. library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) { 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); } 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); } 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); } } // Smart contract for the Dynamic Network Token. contract DynamicNetworkToken is ERC20, AccessControl { // Declaration of roles in the network. bytes32 public constant ADMIN = keccak256("ADMIN"); bytes32 public constant LIQ_PROVIDER = keccak256("LIQ_PROVIDER"); // Govern the amount of tokens with a min and a max. uint256 private minimumSupply = 21000000 ether; uint256 private maximumSupply = 52500000 ether; // Keep track of total amount of burned and minted tokens. uint256 private totalBurned = 0; uint256 private totalMinted = 0; // Keep track of previous burn and mint transaction. uint256 private prevAmountMint = 0; uint256 private prevAmountBurn = 0; // Keep track of wallets in the network with balance > 0. uint256 private totalWallets = 0; // Network Based Burn. uint256 private networkBasedBurn = 1000000 ether; uint256 private nextBurn = 100; // The reserve address. address private reserveAddress; // The minimum balance for the reserveAddress. uint256 private minimumReserve = 4200000 ether; // The initial supply of the token. uint256 private _initialSupply = 42000000 ether; // The current supply of the token. uint256 private currentSupply = _initialSupply; // Number of decimals for DNT. uint256 private _decimals = 18; // Booleans for exp burning and minting. bool private isExpBurn = false; bool private isExpMint = false; using SafeMath for uint256; constructor() ERC20("Dynamic Network Token", "DNT"){ _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(LIQ_PROVIDER, _msgSender()); _setupRole(ADMIN, _msgSender()); _mint(_msgSender(), _initialSupply); reserveAddress = _msgSender(); } // Getter for nextBurn. function getNextBurn() public view returns(uint256){ return(nextBurn); } // Getter for networkBasedBurn. function getNetworkBasedBurn() public view returns(uint256){ return(networkBasedBurn/(10**18)); } // Getter for currentSupply. Returns currentSupply with two decimals. function getCurrentSupply() public view returns(uint256){ return(currentSupply/(10**16)); } // Getter for totalBurned. function getTotalBurned() public view returns(uint256){ return(totalBurned/(10**18)); } // Getter for totalMinted. function getTotalMinted() public view returns(uint256){ return(totalMinted/(10**18)); } // Getter for totalWallets. function getTotalWallets() public view returns(uint256){ return(totalWallets); } // Function for calculating mint. function calculateMint(uint256 amount) public returns(uint256){ uint256 toBeMinted = SafeMath.add(prevAmountMint,amount); prevAmountMint = amount; uint256 uLog = DNTfixedPointMath.ln(toBeMinted); // Check if log < 1, if so calculate exp for minting. if(uLog<1) { isExpMint = true; int256 iExp = DNTfixedPointMath.exp(SafeCast.toInt256(toBeMinted)); iExp = iExp * 8; iExp = DNTfixedPointMath.div(SafeCast.toInt256(toBeMinted),iExp); uint256 uExp = SafeCast.toUint256(iExp); uExp = uExp * 10**4; return uExp; } uint256 log = SafeMath.mul(uLog,8); uint256 logMint = SafeMath.div(toBeMinted,log); logMint = logMint * 10 ** _decimals; return logMint; } // Function for calculating burn. function calculateBurn(uint256 amount) public returns(uint256){ uint256 toBeBurned = SafeMath.add(prevAmountBurn,amount); prevAmountBurn = amount; uint256 uLog = DNTfixedPointMath.ln(toBeBurned); // Check if log < 1, if so calculate exp for burning. if(uLog<1) { isExpBurn = true; int256 iExp = DNTfixedPointMath.exp(SafeCast.toInt256(toBeBurned)); iExp = iExp * 4; iExp = DNTfixedPointMath.div(SafeCast.toInt256(toBeBurned),iExp); uint256 uExp = SafeCast.toUint256(iExp); uExp = uExp * 10**4; return uExp; } uint256 log = SafeMath.mul(uLog,4); uint256 logBurn = SafeMath.div(toBeBurned,log); logBurn = logBurn * 10 ** _decimals; return logBurn; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { // Calculate burn and mint. uint256 toBeBurned = calculateBurn(amount); uint256 toBeMinted = calculateMint(amount); uint256 currentSupplyAfterBurn = SafeMath.sub(currentSupply,toBeBurned); uint256 currentSupplyAfterMint = SafeMath.add(currentSupply,toBeMinted); // Add to totalWalelts if balance is 0. if(balanceOf(recipient)==0) { totalWallets += 1; } // Check if Network Based Burn. if(totalWallets>=nextBurn && SafeMath.sub(currentSupply,amount)>=minimumSupply && SafeMath.sub(balanceOf(reserveAddress),networkBasedBurn)>=minimumReserve) { _burn(reserveAddress,networkBasedBurn); currentSupply = SafeMath.sub(currentSupply,networkBasedBurn); totalBurned = SafeMath.add(totalBurned,networkBasedBurn); nextBurn = nextBurn*2; networkBasedBurn = networkBasedBurn/2; } if(hasRole(LIQ_PROVIDER, _msgSender())) { if(currentSupplyAfterMint<=maximumSupply && isExpMint) { _mint(reserveAddress,SafeMath.div(toBeMinted,10**4)); isExpMint = false; currentSupply = SafeMath.add(currentSupply,SafeMath.div(toBeMinted,10**4)); totalMinted = SafeMath.add(totalMinted,SafeMath.div(toBeMinted,10**4)); } else if(currentSupplyAfterMint<=maximumSupply && toBeMinted > 0) { _mint(reserveAddress,toBeMinted); currentSupply = SafeMath.add(currentSupply,toBeMinted); totalMinted = SafeMath.add(totalMinted,toBeMinted); } } if(hasRole(LIQ_PROVIDER, recipient)) { if(isExpBurn && currentSupplyAfterBurn>=minimumSupply) { if(SafeMath.sub(balanceOf(reserveAddress),SafeMath.div(toBeBurned,10**4))>= minimumReserve) { _burn(reserveAddress,SafeMath.div(toBeBurned,10**4)); isExpBurn= false; currentSupply = SafeMath.sub(currentSupply,SafeMath.div(toBeBurned,10**4)); totalBurned = SafeMath.add(totalBurned,SafeMath.div(toBeBurned,10**4)); } } else if(currentSupplyAfterBurn>=minimumSupply && toBeBurned > 0) { if(SafeMath.sub(balanceOf(reserveAddress),toBeBurned)>= minimumReserve) { _burn(reserveAddress,toBeBurned); currentSupply = SafeMath.sub(currentSupply,toBeBurned); totalBurned = SafeMath.add(totalBurned,toBeBurned); } } } _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender,address recipient, uint256 amount) public virtual override returns (bool) { uint256 toBeBurned = calculateBurn(amount); uint256 currentSupplyAfterBurn = SafeMath.sub(currentSupply,toBeBurned); if(hasRole(LIQ_PROVIDER, recipient)) { if(isExpBurn && currentSupplyAfterBurn>=minimumSupply) { if(SafeMath.sub(balanceOf(reserveAddress),SafeMath.div(toBeBurned,10**4))>= minimumReserve) { _burn(reserveAddress,SafeMath.div(toBeBurned,10**4)); isExpBurn= false; currentSupply = SafeMath.sub(currentSupply,SafeMath.div(toBeBurned,10**4)); totalBurned = SafeMath.add(totalBurned,SafeMath.div(toBeBurned,10**4)); } } else if(currentSupplyAfterBurn>=minimumSupply && toBeBurned > 0) { if(SafeMath.sub(balanceOf(reserveAddress), amount) >= minimumReserve) { _burn(reserveAddress,toBeBurned); currentSupply = SafeMath.sub(currentSupply,toBeBurned); totalBurned = SafeMath.add(totalBurned,toBeBurned); } } } _transfer(sender, recipient, amount); uint256 currentAllowance = allowance(sender,_msgSender()); require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } }
Calculate burn and mint. Add to totalWalelts if balance is 0.
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { uint256 toBeBurned = calculateBurn(amount); uint256 toBeMinted = calculateMint(amount); uint256 currentSupplyAfterBurn = SafeMath.sub(currentSupply,toBeBurned); uint256 currentSupplyAfterMint = SafeMath.add(currentSupply,toBeMinted); if(balanceOf(recipient)==0) { totalWallets += 1; } { _burn(reserveAddress,networkBasedBurn); currentSupply = SafeMath.sub(currentSupply,networkBasedBurn); totalBurned = SafeMath.add(totalBurned,networkBasedBurn); nextBurn = nextBurn*2; networkBasedBurn = networkBasedBurn/2; } if(hasRole(LIQ_PROVIDER, _msgSender())) { if(currentSupplyAfterMint<=maximumSupply && isExpMint) { _mint(reserveAddress,SafeMath.div(toBeMinted,10**4)); isExpMint = false; currentSupply = SafeMath.add(currentSupply,SafeMath.div(toBeMinted,10**4)); totalMinted = SafeMath.add(totalMinted,SafeMath.div(toBeMinted,10**4)); } else if(currentSupplyAfterMint<=maximumSupply && toBeMinted > 0) { _mint(reserveAddress,toBeMinted); currentSupply = SafeMath.add(currentSupply,toBeMinted); totalMinted = SafeMath.add(totalMinted,toBeMinted); } } if(hasRole(LIQ_PROVIDER, recipient)) { if(isExpBurn && currentSupplyAfterBurn>=minimumSupply) { if(SafeMath.sub(balanceOf(reserveAddress),SafeMath.div(toBeBurned,10**4))>= minimumReserve) { _burn(reserveAddress,SafeMath.div(toBeBurned,10**4)); isExpBurn= false; currentSupply = SafeMath.sub(currentSupply,SafeMath.div(toBeBurned,10**4)); totalBurned = SafeMath.add(totalBurned,SafeMath.div(toBeBurned,10**4)); } } else if(currentSupplyAfterBurn>=minimumSupply && toBeBurned > 0) { if(SafeMath.sub(balanceOf(reserveAddress),toBeBurned)>= minimumReserve) { _burn(reserveAddress,toBeBurned); currentSupply = SafeMath.sub(currentSupply,toBeBurned); totalBurned = SafeMath.add(totalBurned,toBeBurned); } } } _transfer(_msgSender(), recipient, amount); return true; }
7,021,257
[ 1, 4625,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 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 1071, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 21333, 38, 321, 329, 273, 4604, 38, 321, 12, 8949, 1769, 203, 3639, 2254, 5034, 21333, 49, 474, 329, 273, 4604, 49, 474, 12, 8949, 1769, 203, 3639, 2254, 5034, 783, 3088, 1283, 4436, 38, 321, 273, 14060, 10477, 18, 1717, 12, 2972, 3088, 1283, 16, 869, 1919, 38, 321, 329, 1769, 203, 3639, 2254, 5034, 783, 3088, 1283, 4436, 49, 474, 273, 14060, 10477, 18, 1289, 12, 2972, 3088, 1283, 16, 869, 1919, 49, 474, 329, 1769, 203, 3639, 309, 12, 12296, 951, 12, 20367, 13, 631, 20, 13, 203, 3639, 288, 203, 5411, 2078, 26558, 2413, 1011, 404, 31, 203, 3639, 289, 203, 3639, 288, 203, 5411, 389, 70, 321, 12, 455, 6527, 1887, 16, 5185, 9802, 38, 321, 1769, 203, 5411, 783, 3088, 1283, 273, 14060, 10477, 18, 1717, 12, 2972, 3088, 1283, 16, 5185, 9802, 38, 321, 1769, 203, 5411, 2078, 38, 321, 329, 273, 14060, 10477, 18, 1289, 12, 4963, 38, 321, 329, 16, 5185, 9802, 38, 321, 1769, 203, 5411, 1024, 38, 321, 273, 1024, 38, 321, 14, 22, 31, 203, 5411, 2483, 9802, 38, 321, 273, 2483, 9802, 38, 321, 19, 22, 31, 203, 3639, 289, 203, 3639, 309, 12, 5332, 2996, 12, 2053, 53, 67, 26413, 16, 389, 3576, 12021, 1435, 3719, 203, 3639, 288, 203, 5411, 309, 12, 2972, 3088, 1283, 4436, 49, 474, 32, 33, 15724, 3088, 1283, 597, 353, 2966, 49, 474, 13, 203, 5411, 288, 203, 7734, 389, 81, 474, 12, 455, 6527, 1887, 16, 9890, 10477, 18, 2892, 12, 869, 1919, 49, 474, 329, 16, 2163, 636, 24, 10019, 203, 7734, 353, 2966, 49, 474, 273, 629, 31, 203, 7734, 783, 3088, 1283, 273, 14060, 10477, 18, 1289, 12, 2972, 3088, 1283, 16, 9890, 10477, 18, 2892, 12, 869, 1919, 49, 474, 329, 16, 2163, 636, 24, 10019, 203, 7734, 2078, 49, 474, 329, 273, 14060, 10477, 18, 1289, 12, 4963, 49, 474, 329, 16, 9890, 10477, 18, 2892, 12, 869, 1919, 49, 474, 329, 16, 2163, 636, 24, 10019, 203, 5411, 289, 203, 5411, 469, 309, 12, 2972, 3088, 1283, 4436, 49, 474, 32, 33, 15724, 3088, 1283, 597, 21333, 49, 474, 329, 405, 374, 13, 203, 5411, 288, 203, 7734, 389, 81, 474, 12, 455, 6527, 1887, 16, 869, 1919, 49, 474, 329, 1769, 203, 7734, 783, 3088, 1283, 273, 14060, 10477, 18, 1289, 12, 2972, 3088, 1283, 16, 869, 1919, 49, 474, 329, 1769, 203, 7734, 2078, 49, 474, 329, 273, 14060, 10477, 18, 1289, 12, 4963, 49, 474, 329, 16, 869, 1919, 49, 474, 329, 1769, 203, 5411, 289, 203, 3639, 289, 203, 3639, 309, 12, 5332, 2996, 12, 2053, 53, 67, 26413, 16, 8027, 3719, 203, 3639, 288, 203, 5411, 309, 12, 291, 2966, 38, 321, 597, 783, 3088, 1283, 4436, 38, 321, 34, 33, 15903, 3088, 1283, 13, 203, 5411, 288, 203, 7734, 309, 12, 9890, 10477, 18, 1717, 12, 12296, 951, 12, 455, 6527, 1887, 3631, 9890, 10477, 18, 2892, 12, 869, 1919, 38, 321, 329, 16, 2163, 636, 24, 3719, 34, 33, 5224, 607, 6527, 13, 203, 7734, 288, 203, 10792, 389, 70, 321, 12, 455, 6527, 1887, 16, 9890, 10477, 18, 2892, 12, 869, 1919, 38, 321, 329, 16, 2163, 636, 24, 10019, 203, 10792, 353, 2966, 38, 321, 33, 629, 31, 203, 10792, 783, 3088, 1283, 273, 14060, 10477, 18, 1717, 12, 2972, 3088, 1283, 16, 9890, 10477, 18, 2892, 12, 869, 1919, 38, 321, 329, 16, 2163, 636, 24, 10019, 203, 10792, 2078, 38, 321, 329, 273, 14060, 10477, 18, 1289, 12, 4963, 38, 321, 329, 16, 9890, 10477, 18, 2892, 12, 869, 1919, 38, 321, 329, 16, 2163, 636, 24, 10019, 203, 7734, 289, 203, 5411, 289, 203, 5411, 469, 309, 12, 2972, 3088, 1283, 4436, 38, 321, 34, 33, 15903, 3088, 1283, 597, 21333, 38, 321, 329, 405, 374, 13, 203, 5411, 288, 203, 7734, 309, 12, 9890, 10477, 18, 1717, 12, 12296, 951, 12, 455, 6527, 1887, 3631, 869, 1919, 38, 321, 329, 13, 34, 33, 5224, 607, 6527, 13, 203, 7734, 288, 203, 10792, 389, 70, 321, 12, 455, 6527, 1887, 16, 869, 1919, 38, 321, 329, 1769, 203, 10792, 783, 3088, 1283, 273, 14060, 10477, 18, 1717, 12, 2972, 3088, 1283, 16, 869, 1919, 38, 321, 329, 1769, 203, 10792, 2078, 38, 321, 329, 273, 14060, 10477, 18, 1289, 12, 4963, 38, 321, 329, 16, 869, 1919, 38, 321, 329, 1769, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 3639, 389, 13866, 24899, 3576, 12021, 9334, 8027, 16, 3844, 1769, 203, 3639, 327, 638, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x29d3646Af367dBa96E1b09A196c60FA20A3dAfF4/sources/contracts/wETHBondDepository.sol
* @notice deposit bond @param _amount uint @param _maxPrice uint @param _depositor address @return uint/ total debt is increased depositor info is stored
) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); uint nativePrice = _bondPrice(); uint value = ITreasury( treasury ).valueOf( principle, _amount ); asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); totalDebt = totalDebt.add( value ); function deposit( uint _amount, uint _maxPrice, address _depositor bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: block.timestamp, pricePaid: priceInUSD }); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); return payout; emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); }
11,552,434
[ 1, 4625, 348, 7953, 560, 30, 380, 225, 632, 20392, 443, 1724, 8427, 225, 632, 891, 389, 8949, 2254, 225, 632, 891, 389, 1896, 5147, 2254, 225, 632, 891, 389, 323, 1724, 280, 1758, 225, 632, 2463, 2254, 19, 2078, 18202, 88, 353, 31383, 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 3639, 2583, 12, 2078, 758, 23602, 1648, 6548, 18, 1896, 758, 23602, 16, 315, 2747, 7519, 8675, 6, 11272, 203, 540, 203, 3639, 2254, 6448, 5147, 273, 389, 26425, 5147, 5621, 203, 203, 203, 3639, 2254, 460, 273, 24142, 266, 345, 22498, 12, 9787, 345, 22498, 262, 18, 1132, 951, 12, 846, 9523, 2444, 16, 389, 8949, 11272, 203, 203, 203, 5411, 3310, 5926, 566, 281, 18404, 471, 353, 486, 312, 474, 329, 5314, 203, 5411, 3310, 7412, 329, 358, 9787, 345, 22498, 471, 283, 6397, 312, 474, 329, 487, 293, 2012, 203, 3639, 467, 654, 39, 3462, 12, 846, 9523, 2444, 262, 18, 4626, 5912, 1265, 12, 1234, 18, 15330, 16, 9787, 345, 22498, 16, 389, 8949, 11272, 203, 3639, 24142, 266, 345, 22498, 12, 9787, 345, 22498, 262, 18, 81, 474, 17631, 14727, 12, 1758, 12, 2211, 3631, 293, 2012, 11272, 203, 540, 203, 3639, 2078, 758, 23602, 273, 2078, 758, 23602, 18, 1289, 12, 460, 11272, 7010, 1171, 203, 203, 565, 445, 443, 1724, 12, 7010, 3639, 2254, 389, 8949, 16, 7010, 3639, 2254, 389, 1896, 5147, 16, 203, 3639, 1758, 389, 323, 1724, 280, 203, 3639, 8427, 966, 63, 389, 323, 1724, 280, 308, 273, 605, 1434, 12590, 7010, 5411, 293, 2012, 30, 8427, 966, 63, 389, 323, 1724, 280, 308, 18, 84, 2012, 18, 1289, 12, 293, 2012, 262, 16, 203, 5411, 331, 10100, 30, 6548, 18, 90, 10100, 4065, 16, 203, 5411, 31323, 30, 1203, 18, 5508, 16, 203, 5411, 6205, 16507, 350, 30, 6205, 382, 3378, 40, 203, 3639, 15549, 203, 203, 3639, 3626, 605, 1434, 5147, 5033, 12, 8427, 5147, 382, 3378, 40, 9334, 389, 26425, 5147, 9334, 18202, 88, 8541, 1435, 11272, 203, 203, 3639, 327, 293, 2012, 31, 7010, 3639, 3626, 605, 1434, 6119, 12, 389, 8949, 16, 293, 2012, 16, 1203, 18, 5508, 18, 1289, 12, 6548, 18, 90, 10100, 4065, 262, 16, 6205, 382, 3378, 40, 11272, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/42/0x590E6Da5d35450ffc3Eed3BC5a25A302f5E584FD/sources/contracts/survey.sol
* @dev Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); }
9,566,669
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 490, 10829, 2430, 1375, 8949, 68, 628, 1375, 15330, 68, 358, 1375, 20367, 8338, 1220, 353, 2713, 445, 353, 7680, 358, 288, 13866, 5779, 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, 5912, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 2713, 225, 288, 203, 3639, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 203, 3639, 389, 70, 26488, 63, 15330, 65, 273, 389, 70, 26488, 63, 15330, 8009, 1717, 12, 8949, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 11013, 8863, 203, 3639, 389, 70, 26488, 63, 20367, 65, 273, 389, 70, 26488, 63, 20367, 8009, 1289, 12, 8949, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xa94b887e15f30db3831AcdDDCd2008a0fFDDe0E3/sources/SchemeRegistrar.sol
Return the final result.
return uint216(realResult / REAL_ONE);
9,165,868
[ 1, 4625, 348, 7953, 560, 30, 225, 2000, 326, 727, 563, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 327, 2254, 22, 2313, 12, 7688, 1253, 342, 2438, 1013, 67, 5998, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-10-23 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/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 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) { 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/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); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @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; } // File: @openzeppelin/contracts/token/ERC721/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 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); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @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); } // File: @openzeppelin/contracts/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); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^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; } } // File: @openzeppelin/contracts/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; // 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); } } } } // File: @openzeppelin/contracts/utils/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; // 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]; } // 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); } // 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)))); } // 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)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity ^0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 _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)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @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 || ERC721.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 _tokenOwners.contains(tokenId); } /** * @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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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"); // internal 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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, 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), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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 { } } // File: @openzeppelin/contracts/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 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; } } pragma solidity ^0.8.0; pragma abicoder v2; contract EtherealCollectiveArtSupporter is ERC721, Ownable { using SafeMath for uint256; // Basic // string public ecasProvenance = ""; // IPFS URL WILL BE ADDED WHEN ALL SOLD OUT uint256 public collectiblePrice = 0.128 ether; uint256 public constant maxCollectiblePerPurchase = 3; // 1-3 tokens per transaction uint256 public constant maxCollectibles = 8168; uint256 public presalePurchaseLimit = 3; // PRESALE: 3 tokens per wallet maximum. uint256 public purchaseLimit = 10; // PUBLIC SALE: 10 tokens per wallet maximum. uint256 public collectibleReserve = 168; // FREE MINT FOR OWNER // Arrays // mapping(address => bool) public presalerList; mapping(address => uint256) public presalerListPurchases; mapping(address => uint256) public purchases; // Booleans bool public saleIsActive = false; bool public presaleIsLive = false; bool public locked = false; constructor() ERC721("Ethereal Collective Art Supporter", "ECAS") { } modifier notLocked { require(!locked, "Contract metadata methods are locked"); _; } function addToPresaleList(address[] calldata entries) external onlyOwner { for(uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), "Null address"); require(!presalerList[entry], "Duplicated entry"); presalerList[entry] = true; } } function removeFromPresaleList(address[] calldata entries) external onlyOwner { for(uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), "Null address"); presalerList[entry] = false; } } function reserve(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply() + 1; require(_reserveAmount > 0 && _reserveAmount <= collectibleReserve, "Not enough reserve left for team."); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } collectibleReserve = collectibleReserve.sub(_reserveAmount); } function withdraw() public onlyOwner { _withdraw(msg.sender, address(this).balance); } function _withdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } function setProvenanceHash(string memory provenanceHash) public onlyOwner notLocked { ecasProvenance = provenanceHash; } function setMintingPrice(uint256 mintingPrice) public onlyOwner notLocked { collectiblePrice = mintingPrice; } function setBaseURI(string memory baseURI) public onlyOwner notLocked { _setBaseURI(baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function flipPreSaleState() public onlyOwner { presaleIsLive = !presaleIsLive; } function lockMetadata() external onlyOwner { locked = true; } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function mint(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint"); require(!presaleIsLive, "Only presale"); require(numberOfTokens > 0 && numberOfTokens <= maxCollectiblePerPurchase, "Can only mint 3 tokens at a time."); require(totalSupply().add(numberOfTokens) <= maxCollectibles, "Purchase would exceed max supply"); require(msg.value >= collectiblePrice.mul(numberOfTokens), "Ether value sent is not correct."); require(purchases[msg.sender] + numberOfTokens <= purchaseLimit, "Exceed Alloc"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply() +1; if (totalSupply() < maxCollectibles) { purchases[msg.sender]++; _safeMint(msg.sender, mintIndex); } } } function presaleMint(uint256 numberOfTokens) external payable { require(!saleIsActive && presaleIsLive, "Presale closed"); require(presalerList[msg.sender], "Not qualified"); require(totalSupply().add(numberOfTokens) <= maxCollectibles, "Purchase would exceed max supply"); require(presalerListPurchases[msg.sender] + numberOfTokens <= presalePurchaseLimit, "Exceed Alloc"); require(msg.value >= collectiblePrice.mul(numberOfTokens), "Ether value sent is not correct."); for (uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply() +1; presalerListPurchases[msg.sender]++; _safeMint(msg.sender, mintIndex); } } }
@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 { pragma solidity ^0.8.0; function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { return msg.data; } }
7,928,028
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 28805, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 611, 13653, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17801, 6835, 1772, 288, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 1234, 18, 892, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-02-28 */ // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.4.23; /** * @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. */ 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: contracts/WhiteList.sol pragma solidity ^0.4.21; contract WhiteList is Ownable{ mapping(address => uint8) public whitelist; bool public publicsale_need_whitelist = true; event ImportList(address indexed owner, address[] users, uint8 flag); event UpdatePublicSaleWhitelistStatus(address indexed owner, bool flag); /** * @dev Function to import user's address into whitelist, only user who in the whitelist can purchase token. * Whitelistにユーザーアドレスを記録。sale期間に、Whitelistに記録したユーザーたちしかトークンを購入できない * @param _users The address list that can purchase token when sale period. * @param _flag The flag for record different lv user, 1: pre sale user, 2: public sale user. 3: premium sale user * @return A bool that indicates if the operation was successful. */ function importList(address[] _users, uint8 _flag) onlyOwner public returns(bool){ require(_users.length > 0); for(uint i = 0; i < _users.length; i++) { whitelist[_users[i]] = _flag; } emit ImportList(msg.sender, _users, _flag); return true; } /** * @dev Function check the current user can purchase token or not. * ユーザーアドレスはWhitelistに記録かどうかチェック * @param _user The user address that can purchase token or not when public salse. * @return A bool that indicates if the operation was successful. */ function checkList(address _user)public view returns(uint8){ return whitelist[_user]; } /** * @dev Function get whitelist able status in public sale * @return A bool that indicates if the operation was successful. */ function getPublicSaleWhitelistStatus()public view returns(bool){ return publicsale_need_whitelist; } /** * @dev Function update whitelist able status in public sale * @param _flag bool whitelist status * @return A bool that indicates if the operation was successful. */ function updatePublicSaleWhitelistStatus(bool _flag) onlyOwner public returns(bool){ publicsale_need_whitelist = _flag; emit UpdatePublicSaleWhitelistStatus(msg.sender, _flag); return true; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.23; /** * @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) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } 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: contracts/Deliver.sol pragma solidity ^0.4.21; contract Deliver is Ownable{ using SafeMath for uint256; mapping(address => uint256) public waiting_plate; mapping(bytes32 => uint256) public token_deliver_date_plate; mapping(bytes32 => uint256) public token_deliver_plate; mapping(bytes32 => bool) public already_deliver_token; mapping(address => uint256) public deliver_balance; mapping(bytes32 => address) public hash_mapping; mapping(bytes32 => bool) public deliver_suspending; event UpdateWaitingPlate(address indexed updater, address indexed user, uint256 waiting_time); event UpdateTokenDeliverPlate(address indexed updater, bytes32 indexed hash_id, uint256 token_amount); event UpdateTokenDeliverCheck(address indexed updater, bytes32 indexed hash_id, bool flag); event UpdateTokenDeliverBalance(address indexed updater, address indexed user, uint256 pending_token_amount); event UpdateHashMapping(address indexed updater, bytes32 indexed hash_id, address indexed user); event UpdateDeliverSuspending(address indexed updater, bytes32 indexed hash_id, bool deliver_suspending); /** * @dev called for get user waiting time * @param _user Address * @return A uint256 that if the operation was successful. */ function getWaitingPlate(address _user) public view returns(uint256){ return waiting_plate[_user]; } /** * @dev called for get user deliver date * @param _hash_id transaction unique hash id * @return A uint256 that if the operation was successful. */ function getTokenDeliverDatePlate(bytes32 _hash_id) public view returns(uint256){ return token_deliver_date_plate[_hash_id]; } /** * @dev called for get user waiting time * @param _hash_id transaction unique hash id * @return A uint256 that if the operation was successful. */ function getTokenDeliverPlate(bytes32 _hash_id) public view returns(uint256){ return token_deliver_plate[_hash_id]; } /** * @dev called for get user total pending token amount * @param _user user address * @return A uint256 that if the operation was successful. */ function getPendingDeliverToken(address _user) public view returns(uint256){ return deliver_balance[_user]; } /** * @dev called for get user address from hash_id * @param _hash_id transaction unique hash id * @return A address that if the operation was successful. */ function getHashMappingAddress(bytes32 _hash_id) public view returns(address){ return hash_mapping[_hash_id]; } /** * @dev called for get user token deliver suspending status * @param _hash_id transaction unique hash id * @return A bool that if the operation was successful. */ function getDeliverSuspending(bytes32 _hash_id) public view returns(bool){ return deliver_suspending[_hash_id]; } /** * @dev called for get user total pending token amount * @param _hash_id transaction unique hash id * @return A bool that if the operation was successful. */ function deliverCheck(bytes32 _hash_id) public view returns(bool){ return already_deliver_token[_hash_id]; } /** * @dev called for insert user waiting time * @param _users Address list * @param _waiting_times 時期申告時間リスト * @return A bool that if the operation was successful. */ function pushWaitingPlate(address[] _users, uint256[] _waiting_times)onlyOwner public returns(bool){ require(_users.length > 0 && _waiting_times.length > 0); require(_users.length == _waiting_times.length); address user; uint256 waiting_time; for(uint i = 0; i < _users.length; i++) { user = _users[i]; waiting_time = _waiting_times[i]; waiting_plate[user] = waiting_time; emit UpdateWaitingPlate(msg.sender, user, waiting_time); } return true; } /** * @dev called for insert user waiting time * @param _hash_id transaction unique hash id * @param _suspending ユーザーのトークン配布禁止フラグ * @return A bool that if the operation was successful. */ function updateDeliverSuspending(bytes32 _hash_id, bool _suspending)onlyOwner public returns(bool){ deliver_suspending[_hash_id] = _suspending; emit UpdateDeliverSuspending(msg.sender, _hash_id, _suspending); return true; } /** * @dev called for insert user token info in the mapping * @param _hash_id transaction unique hash id * @param _total_token_amount the token amount that include bonus * @return A bool that if the operation was successful. */ function pushTokenDeliverPlate(address _beneficiary, bytes32 _hash_id, uint256 _total_token_amount, uint256 _deliver_date)onlyOwner public returns(bool){ require(_total_token_amount > 0); token_deliver_plate[_hash_id] = _total_token_amount; already_deliver_token[_hash_id] = false; deliver_balance[_beneficiary] = deliver_balance[_beneficiary].add(_total_token_amount); hash_mapping[_hash_id] = _beneficiary; token_deliver_date_plate[_hash_id] = _deliver_date; emit UpdateTokenDeliverPlate(msg.sender, _hash_id, _total_token_amount); emit UpdateTokenDeliverCheck(msg.sender, _hash_id, true); emit UpdateTokenDeliverBalance(msg.sender, _beneficiary, deliver_balance[_beneficiary]); emit UpdateHashMapping(msg.sender, _hash_id, _beneficiary); return true; } /** * @dev called for reset user token info in the mapping * @param _hash_id transaction unique hash id * @return A bool that if the operation was successful. */ function resetTokenDeliverPlate(address _beneficiary, bytes32 _hash_id, uint256 _token_amount)onlyOwner public returns(bool){ require(_token_amount > 0); token_deliver_plate[_hash_id] = 0; already_deliver_token[_hash_id] = true; deliver_balance[_beneficiary] = deliver_balance[_beneficiary].sub(_token_amount); emit UpdateTokenDeliverPlate(msg.sender, _hash_id, 0); emit UpdateTokenDeliverCheck(msg.sender, _hash_id, false); emit UpdateTokenDeliverBalance(msg.sender, _beneficiary, deliver_balance[_beneficiary]); return true; } } // File: contracts/Bonus.sol pragma solidity ^0.4.21; contract Bonus is Ownable{ using SafeMath for uint256; uint256 public constant day = 24*60*60; uint256 public publicSale_first_stage_endTime; mapping(uint8 => uint256) public bonus_time_gate; mapping(uint8 => uint8) public bonus_rate; event UpdateBonusPhase(address indexed updater, uint8 indexed phase_type, uint256 time_gate, uint8 bonus); event UpdatePublicSaleFirstStageEndTime(address indexed updater, uint256 publicSale_first_stage_endTime); constructor( uint256 _publicSale_first_stage_endTime, uint256 _bonus_time_gate_1, uint256 _bonus_time_gate_2, uint256 _bonus_time_gate_3, uint256 _bonus_time_gate_4, uint8 _bonus_rate_1, uint8 _bonus_rate_2, uint8 _bonus_rate_3, uint8 _bonus_rate_4) public { bonus_time_gate[0] = _bonus_time_gate_1*uint256(day); bonus_time_gate[1] = _bonus_time_gate_2*uint256(day); bonus_time_gate[2] = _bonus_time_gate_3*uint256(day); bonus_time_gate[3] = _bonus_time_gate_4*uint256(day); bonus_rate[0] = _bonus_rate_1; bonus_rate[1] = _bonus_rate_2; bonus_rate[2] = _bonus_rate_3; bonus_rate[3] = _bonus_rate_4; publicSale_first_stage_endTime = _publicSale_first_stage_endTime; emit UpdateBonusPhase(msg.sender, 1, _bonus_time_gate_1, _bonus_rate_1); emit UpdateBonusPhase(msg.sender, 2, _bonus_time_gate_2, _bonus_rate_2); emit UpdateBonusPhase(msg.sender, 3, _bonus_time_gate_3, _bonus_rate_3); emit UpdateBonusPhase(msg.sender, 4, _bonus_time_gate_4, _bonus_rate_4); } /** * @dev called for get bonus rate * @param _phase_type uint8 bonus phase block * @return A uint8, bonus rate that if the operation was successful. */ function getBonusRate(uint8 _phase_type) public view returns(uint8){ return bonus_rate[_phase_type]; } /** * @dev called for get bonus time block * @param _phase_type uint8 bonus phase block * @return A uint8, phase block time that if the operation was successful. */ function getBonusTimeGate(uint8 _phase_type) public view returns(uint256){ return bonus_time_gate[_phase_type]; } /** * @dev called for get the public sale first stage end time * @return A uint256, the public sale first stage end time that if the operation was successful. */ function getPublicSaleFirstStageEndTime() public view returns(uint256){ return publicSale_first_stage_endTime; } /** * @dev called for get total token amount that include the bonus * @param _waiting_time uint256 KYV waiting time * @param _tokenAmount uint256 basic token amount * @return A uint256, total token amount that if the operation was successful. */ function getTotalAmount(uint256 _waiting_time, uint256 _tokenAmount) public view returns(uint256){ uint256 total_token_amount; if(_waiting_time < bonus_time_gate[0]){ //user still can get bonus if user purchase token before publicSale first stage end time. if(now <= publicSale_first_stage_endTime){ total_token_amount = _tokenAmount + (_tokenAmount * uint256(bonus_rate[0])) / 100; }else{ total_token_amount = _tokenAmount; } }else if(_waiting_time < bonus_time_gate[1]){ total_token_amount = _tokenAmount + (_tokenAmount * uint256(bonus_rate[0])) / 100; }else if(_waiting_time < bonus_time_gate[2]){ total_token_amount = _tokenAmount + (_tokenAmount * uint256(bonus_rate[1])) / 100; }else if(_waiting_time < bonus_time_gate[3]){ total_token_amount = _tokenAmount + (_tokenAmount * uint256(bonus_rate[2])) / 100; }else{ total_token_amount = _tokenAmount + (_tokenAmount * uint256(bonus_rate[3])) / 100; } return total_token_amount; } /** * @dev called for update the public sale first stage end time * @param _new_stage_endTime uint256 new public sale first stage end time * @return A uint256, the public sale first stage end time that if the operation was successful. */ function updatePublicSaleFirstStageEndTime(uint256 _new_stage_endTime)onlyOwner public returns(bool){ publicSale_first_stage_endTime = _new_stage_endTime; emit UpdatePublicSaleFirstStageEndTime(msg.sender, _new_stage_endTime); return true; } /** * @dev called for update bonus phase time block and rate * @param _phase_type uint8 phase block * @param _new_days uint256 new phase block time * @param _new_bonus uint8 new rate * @return A bool that if the operation was successful. */ function updateBonusPhase(uint8 _phase_type, uint256 _new_days, uint8 _new_bonus)onlyOwner public returns(bool){ uint256 _new_gate = _new_days * uint256(day); //gate phase only have 4 phase require(0 < _phase_type && _phase_type <= 4); //gate phase 1 if(_phase_type == 1){ //new gate time needs to be early than the next gate time require( _new_gate < bonus_time_gate[1] ); //new gate rate needs to be less than the next gate's rate require( _new_bonus < bonus_rate[1] ); bonus_time_gate[0] = _new_gate; bonus_rate[0] = _new_bonus; }else if(_phase_type == 2){ //new gate time needs to be early than the next gate time and need to be late than the perious gate time require( bonus_time_gate[0] < _new_gate && _new_gate < bonus_time_gate[2] ); //new gate rate needs to be less than the next gate's rate and need to be bigger than the perious gate rate require( bonus_rate[0] < _new_bonus && _new_bonus < bonus_rate[2] ); bonus_time_gate[1] = _new_gate; bonus_rate[1] = _new_bonus; }else if(_phase_type == 3){ require( bonus_time_gate[1] < _new_gate && _new_gate < bonus_time_gate[3] ); require( bonus_rate[1] < _new_bonus && _new_bonus < bonus_rate[3] ); bonus_time_gate[2] = _new_gate; bonus_rate[2] = _new_bonus; }else{ require( bonus_time_gate[2] < _new_gate ); require( bonus_rate[2] < _new_bonus ); bonus_time_gate[3] = _new_gate; bonus_rate[3] = _new_bonus; } emit UpdateBonusPhase(msg.sender, _phase_type, _new_days, _new_bonus); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); 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); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.23; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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 ); } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol pragma solidity ^0.4.23; /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * 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 ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol pragma solidity ^0.4.23; /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.4.23; /** * @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: contracts/COTCoinPublicSaleCrowdsale.sol pragma solidity ^0.4.21; contract COTCoinPublicSaleCrowdsale is TimedCrowdsale, Ownable, Pausable{ using SafeMath for uint256; address public admin_wallet; //wallet to controll system address public sale_owner_wallet; address public eth_management_wallet; //wallet to reveive eth address public refund_token_wallet; //wallet that contract will return token address public cot_sale_wallet; uint256 public minimum_weiAmount; uint256 public public_opening_time; uint256 public public_closing_time; WhiteList public white_list; Deliver public deliver; Bonus public bonus; uint256 public pending_balance; event UpdateRate(address indexed updater, uint256 transaction_date, uint256 rate); event ReFundToken(address indexed from, address indexed to, uint256 token_amount); event PublicsalePurchase(address indexed beneficiary, uint256 transaction_date, uint256 waiting_time, uint256 deliver_date, uint256 value, uint256 origin_token_amount, uint256 total_token_amount, bytes32 hash_id, uint256 sale_balance, uint256 publicsale_balance, uint256 remain_balance); event DeliverTokens(address indexed from, address indexed to, uint256 token_amount, uint256 deliver_time, bytes32 hash_id); event UpdateMinimumAmount( address indexed updater, uint256 minimumWeiAmount); event UpdateReFundAddress( address indexed updater, address indexed refund_address); constructor( uint256 _openingTime, uint256 _closingTime, uint256 _minimum_weiAmount, uint256 _rate, address _admin_wallet, address _eth_management_wallet, address _refund_token_wallet, address _cot_sale_wallet, WhiteList _whiteList, ERC20 _cot, Deliver _deliver, Bonus _bonus) public Crowdsale(_rate, _eth_management_wallet, _cot) TimedCrowdsale(_openingTime, _closingTime) { minimum_weiAmount = _minimum_weiAmount; admin_wallet = _admin_wallet; eth_management_wallet = _eth_management_wallet; refund_token_wallet = _refund_token_wallet; cot_sale_wallet = _cot_sale_wallet; public_opening_time = _openingTime; public_closing_time = _closingTime; white_list = _whiteList; deliver = _deliver; bonus = _bonus; emit UpdateRate( msg.sender, now, _rate); emit UpdateMinimumAmount(msg.sender, _minimum_weiAmount); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) onlyWhileOpen whenNotPaused public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); //minimum ether check uint256 publicSale_first_stage_endTime = bonus.getPublicSaleFirstStageEndTime(); //need to check minimum ether require(_weiAmount >= minimum_weiAmount); //owner can not purchase token require(_beneficiary != admin_wallet); require(_beneficiary != eth_management_wallet); //whitelist check //whitelist 2-public sale user uint8 inWhitelist = white_list.checkList(_beneficiary); //if need to check whitelist status //0:white listに入ってない, 1:プレセール, 2:パブリックセール, 3:プレミアムセール if( white_list.getPublicSaleWhitelistStatus() ){ require( inWhitelist != 0); } } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { //check waiting time date which provided by KVC uint256 waiting_time = deliver.getWaitingPlate(_beneficiary); require(waiting_time != 0); //calculate that when will deliver token to purchaser uint256 deliver_date = waiting_time + now; //calculate the token + bonus uint256 total_token_amount = bonus.getTotalAmount(waiting_time, _tokenAmount); //make the unique id bytes32 hash_id = keccak256(abi.encodePacked(_beneficiary,now)); //get total cot sale amount uint256 cot_sale_wallet_balance = token.balanceOf(cot_sale_wallet); uint256 publicsale_balance = token.balanceOf(address(this)); uint256 total_cot_amount = cot_sale_wallet_balance.add(publicsale_balance); uint256 expect_pending_balance = pending_balance.add(total_token_amount); require(total_cot_amount > expect_pending_balance); uint256 remain_cot_amount = total_cot_amount.sub(expect_pending_balance); pending_balance = pending_balance.add(total_token_amount); require(deliver.pushTokenDeliverPlate(_beneficiary, hash_id, total_token_amount , deliver_date)); emit PublicsalePurchase(_beneficiary, now, waiting_time, deliver_date, msg.value, _tokenAmount, total_token_amount, hash_id, cot_sale_wallet_balance, publicsale_balance, remain_cot_amount); } /** * @dev called for get pending balance */ function getPendingBalance() public view returns(uint256){ return pending_balance; } /** * @dev called for update user waiting time * @param _users Address * @param _waiting_times 時期申告時間 * @return A bool that indicates if the operation was successful. */ function updateWaitingPlate(address[] _users, uint256[] _waiting_times)onlyOwner public returns(bool){ require(deliver.pushWaitingPlate(_users, _waiting_times)); return true; } /** * @dev called for update user deliver suspending status * @param _hash_id unique hash id * @param _suspending ユーザーのトークン配布禁止フラグ * @return A bool that indicates if the operation was successful. */ function updateDeliverSuspending(bytes32 _hash_id, bool _suspending)onlyOwner public returns(bool){ require(deliver.updateDeliverSuspending(_hash_id, _suspending)); return true; } /** * @dev called for get status of pause. */ function ispause() public view returns(bool){ return paused; } /** * @dev Function update rate * @param _newRate rate * @return A bool that indicates if the operation was successful. */ function updateRate(int256 _newRate)onlyOwner public returns(bool){ require(_newRate >= 1); rate = uint256(_newRate); emit UpdateRate( msg.sender, now, rate); return true; } /** * @dev Function get rate * @return A uint256 that indicates if the operation was successful. */ function getRate() public view returns(uint256){ return rate; } /** * @dev Function return token back to the admin wallet * @return A bool that indicates if the operation was successful. */ function reFundToken(uint256 _value)onlyOwner public returns (bool){ token.transfer(refund_token_wallet, _value); emit ReFundToken(msg.sender, refund_token_wallet, _value); } /** * @dev Function to update refund address * @param _add new refund Address * @return A bool that indicates if the operation was successful. */ function updateReFundAddress(address _add)onlyOwner public returns (bool){ refund_token_wallet = _add; emit UpdateReFundAddress(msg.sender, _add); return true; } /** * @dev called for deliver token * @param _beneficiary Address * @param _hash_id unique hash id * @return A bool that indicates if the operation was successful. */ function deliverTokens(address _beneficiary, bytes32 _hash_id)onlyOwner public returns (bool){ // will reject if already delivered token bool already_delivered = deliver.deliverCheck(_hash_id); require(already_delivered == false); //get the token deliver date uint256 deliver_token_date = deliver.getTokenDeliverDatePlate(_hash_id); require(deliver_token_date <= now); //get the token amount that need to deliver uint256 deliver_token_amount = deliver.getTokenDeliverPlate(_hash_id); require(deliver_token_amount > 0); //deliver user should match address deliver_user = deliver.getHashMappingAddress(_hash_id); require(deliver_user == _beneficiary); //get token deliver suspending status bool deliver_suspending = deliver.getDeliverSuspending(_hash_id); require(!deliver_suspending); //get the total pending token amount for this user uint256 penging_total_deliver_token_amount = deliver.getPendingDeliverToken(_beneficiary); require(penging_total_deliver_token_amount > 0); //the remain pending token amount should not less than 0 uint256 remain_panding_total_deliver_token_amount = penging_total_deliver_token_amount - deliver_token_amount; require(remain_panding_total_deliver_token_amount >= 0); //deliver token token.transfer(_beneficiary, deliver_token_amount); //reset data require(deliver.resetTokenDeliverPlate(_beneficiary, _hash_id, deliver_token_amount)); pending_balance = pending_balance.sub(deliver_token_amount); emit DeliverTokens(msg.sender, _beneficiary, deliver_token_amount, now, _hash_id); } /** * @dev get admin wallet */ function getAdminAddress() public view returns(address) { return admin_wallet; } /** * @dev get eth management owner wallet */ function getEtherManagementAddress() public view returns(address) { return eth_management_wallet; } /** * @dev get token refund wallet */ function getReFundAddress() public view returns(address) { return refund_token_wallet; } /** * @dev get start date for public sale */ function getPublicsaleOpeningDate() public view returns(uint256) { return public_opening_time; } /** * @dev get end date for public sale */ function getPublicsaleClosingDate() public view returns(uint256) { return public_closing_time; } /** * @dev Function get minimum wei amount * @return A uint256 that indicates if the operation was successful. */ function getMinimumAmount() public view returns(uint256){ return minimum_weiAmount; } /** * @dev Function update minimum wei amount * @return A uint256 that indicates if the operation was successful. */ function updateMinimumAmount(int256 _new_minimum_weiAmount)onlyOwner public returns(bool){ require(_new_minimum_weiAmount >= 0); minimum_weiAmount = uint256(_new_minimum_weiAmount); emit UpdateMinimumAmount( msg.sender, minimum_weiAmount); return true; } }
* @dev Function update whitelist able status in public sale @param _flag bool whitelist status @return A bool that indicates if the operation was successful./
function updatePublicSaleWhitelistStatus(bool _flag) onlyOwner public returns(bool){ publicsale_need_whitelist = _flag; emit UpdatePublicSaleWhitelistStatus(msg.sender, _flag); return true; }
15,445,030
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 4284, 1089, 10734, 7752, 1267, 316, 1071, 272, 5349, 632, 891, 389, 6420, 1426, 10734, 1267, 632, 2463, 432, 1426, 716, 8527, 309, 326, 1674, 1703, 6873, 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, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1089, 4782, 30746, 18927, 1482, 12, 6430, 389, 6420, 13, 1338, 5541, 1071, 1135, 12, 6430, 15329, 203, 202, 202, 482, 87, 5349, 67, 14891, 67, 20409, 273, 389, 6420, 31, 203, 203, 202, 202, 18356, 2315, 4782, 30746, 18927, 1482, 12, 3576, 18, 15330, 16, 389, 6420, 1769, 203, 203, 202, 202, 2463, 638, 31, 203, 202, 97, 202, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IRiskManagerV1.sol"; import "./RiskManagerV1.sol"; import "./CoveragePool.sol"; import "./CoveragePoolConstants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @notice Interface for the Uniswap v2 router. /// @dev This is an interface with just a few function signatures of the /// router contract. For more info and function description please see: /// https://uniswap.org/docs/v2/smart-contracts/router02 interface IUniswapV2Router { function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function factory() external pure returns (address); /* solhint-disable-next-line func-name-mixedcase */ function WETH() external pure returns (address); } /// @notice Interface for the Uniswap v2 pair. /// @dev This is an interface with just a few function signatures of the /// pair contract. For more info and function description please see: /// https://uniswap.org/docs/v2/smart-contracts/pair interface IUniswapV2Pair { function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); } /// @title SignerBondsUniswapV2 /// @notice ETH purchased by the risk manager from tBTC signer bonds needs to be /// swapped and deposited back to the coverage pool as collateral. /// SignerBondsUniswapV2 is a swap strategy implementation which /// can withdraw the given bonds amount from the risk manager, swap them /// on Uniswap v2 exchange and deposit as coverage pool collateral. /// The governance can set crucial swap parameters: max allowed /// percentage impact, slippage tolerance and swap deadline, to force /// reasonable swap outcomes. It is up to the governance to decide what /// these values should be. contract SignerBondsUniswapV2 is ISignerBondsSwapStrategy, Ownable { // One basis point is equivalent to 1/100th of a percent. uint256 public constant BASIS_POINTS_DIVISOR = 10000; IUniswapV2Router public immutable uniswapRouter; IUniswapV2Pair public immutable uniswapPair; address public immutable assetPool; address public immutable collateralToken; mapping(address => bool) public approvedSwappers; // Determines the maximum allowed price impact for the swap transaction. // If transaction's price impact is higher, transaction will be reverted. // Default value is 100 basis points (1%). uint256 public maxAllowedPriceImpact = 100; // Determines the slippage tolerance for the swap transaction. // If transaction's slippage is higher, transaction will be reverted. // Default value is 50 basis points (0.5%). uint256 public slippageTolerance = 50; // Determines the deadline in which the swap transaction has to be mined. // If that deadline is exceeded, transaction will be reverted. uint256 public swapDeadline = 20 minutes; // Determines if the swap should revert when open auctions exists. If true, // swaps cannot be performed if there is at least one open auction. // If false, open auctions are not taken into account. bool public revertIfAuctionOpen = true; event SignerBondsSwapperApproved(address swapper); event SignerBondsSwapperUnapproved(address swapper); event UniswapV2SwapExecuted(uint256[] amounts); /// @notice Reverts if called by a signer bonds swapper that is not approved modifier onlyApprovedSwapper() { require( approvedSwappers[msg.sender], "Signer bonds swapper not approved" ); _; } constructor(IUniswapV2Router _uniswapRouter, CoveragePool _coveragePool) { uniswapRouter = _uniswapRouter; assetPool = address(_coveragePool.assetPool()); address _collateralToken = address(_coveragePool.collateralToken()); collateralToken = _collateralToken; uniswapPair = IUniswapV2Pair( computePairAddress( _uniswapRouter.factory(), _uniswapRouter.WETH(), _collateralToken ) ); } /// @notice Receive ETH upon withdrawal of risk manager's signer bonds. /// @dev Do not send arbitrary funds. They will be locked forever. receive() external payable {} /// @notice Notifies the strategy about signer bonds purchase. /// @param amount Amount of purchased signer bonds. function onSignerBondsPurchased(uint256 amount) external override {} /// @notice Sets the maximum price impact allowed for a swap transaction. /// @param _maxAllowedPriceImpact Maximum allowed price impact specified /// in basis points. Value of this parameter must be between /// 0 and 10000 (inclusive). It should be chosen carefully as /// high limit level will accept transactions with high volumes. /// Those transactions may result in poor execution prices. Very low /// limit will force low swap volumes. Limit equal to 0 will /// effectively make swaps impossible. function setMaxAllowedPriceImpact(uint256 _maxAllowedPriceImpact) external onlyOwner { require( _maxAllowedPriceImpact <= BASIS_POINTS_DIVISOR, "Maximum value is 10000 basis points" ); maxAllowedPriceImpact = _maxAllowedPriceImpact; } /// @notice Sets the slippage tolerance for a swap transaction. /// @param _slippageTolerance Slippage tolerance in basis points. Value of /// this parameter must be between 0 and 10000 (inclusive). It /// should be chosen carefully as transactions with high slippage /// tolerance result in poor execution prices. On the other hand, /// very low slippage tolerance may cause transactions to be /// reverted frequently. Slippage tolerance equal to 0 is possible /// and disallows any slippage to happen on the swap at the cost /// of higher revert risk. function setSlippageTolerance(uint256 _slippageTolerance) external onlyOwner { require( _slippageTolerance <= BASIS_POINTS_DIVISOR, "Maximum value is 10000 basis points" ); slippageTolerance = _slippageTolerance; } /// @notice Sets the deadline for a swap transaction. /// @param _swapDeadline Swap deadline in seconds. Value of this parameter /// should be equal or greater than 0. It should be chosen carefully /// as transactions with long deadlines may result in poor execution /// prices. On the other hand, very short deadlines may cause /// transactions to be reverted frequently, especially in a /// gas-expensive environment. Deadline equal to 0 will effectively // make swaps impossible. function setSwapDeadline(uint256 _swapDeadline) external onlyOwner { swapDeadline = _swapDeadline; } /// @notice Sets whether a swap should revert if at least one /// open auction exists. /// @param _revertIfAuctionOpen If true, revert the swap if there is at /// least one open auction. If false, open auctions won't be taken /// into account. function setRevertIfAuctionOpen(bool _revertIfAuctionOpen) external onlyOwner { revertIfAuctionOpen = _revertIfAuctionOpen; } /// @notice Swaps signer bonds on Uniswap v2 exchange. /// @dev Swaps the given ETH amount for the collateral token using the /// Uniswap exchange. The maximum ETH amount is capped by the /// contract balance. Some governance parameters are applied on the /// transaction. The swap's price impact must fit within the /// maximum allowed price impact and the transaction is constrained /// with the slippage tolerance and deadline. Acquired collateral /// tokens are sent to the asset pool address set during /// contract construction. /// @param riskManager Address of the risk manager which holds the bonds. /// @param amount Amount to swap. function swapSignerBondsOnUniswapV2( IRiskManagerV1 riskManager, uint256 amount ) external onlyApprovedSwapper { require(amount > 0, "Amount must be greater than 0"); require( amount <= address(riskManager).balance, "Amount exceeds risk manager balance" ); if (revertIfAuctionOpen) { require(!riskManager.hasOpenAuctions(), "There are open auctions"); } riskManager.withdrawSignerBonds(amount); // Setup the swap path. WETH must be the first component. address[] memory path = new address[](2); path[0] = uniswapRouter.WETH(); path[1] = collateralToken; // Calculate the maximum output token amount basing on pair reserves. // This value will be used as the minimum amount of output tokens that // must be received for the transaction not to revert. // This value includes liquidity fee equal to 0.3%. uint256 amountOutMin = uniswapRouter.getAmountsOut(amount, path)[1]; require( isAllowedPriceImpact(amountOutMin), "Price impact exceeds allowed limit" ); // Include slippage tolerance into the minimum amount of output tokens. amountOutMin = (amountOutMin * (BASIS_POINTS_DIVISOR - slippageTolerance)) / BASIS_POINTS_DIVISOR; // slither-disable-next-line arbitrary-send,reentrancy-events uint256[] memory amounts = uniswapRouter.swapExactETHForTokens{ value: amount }( amountOutMin, path, assetPool, /* solhint-disable-next-line not-rely-on-time */ block.timestamp + swapDeadline ); emit UniswapV2SwapExecuted(amounts); } /// @notice Approves the signer bonds swapper. The change takes effect /// immediately. /// @dev Can be called only by the contract owner. /// @param swapper Swapper that will be approved function approveSwapper(address swapper) external onlyOwner { require( !approvedSwappers[swapper], "Signer bonds swapper has been already approved" ); emit SignerBondsSwapperApproved(swapper); approvedSwappers[swapper] = true; } /// @notice Unapproves the signer bonds swapper. The change takes effect /// immediately. /// @dev Can be called only by the contract owner. /// @param swapper Swapper that will be unapproved function unapproveSwapper(address swapper) external onlyOwner { require( approvedSwappers[swapper], "Signer bonds swapper is not approved" ); emit SignerBondsSwapperUnapproved(swapper); delete approvedSwappers[swapper]; } /// @notice Checks the price impact of buying a given amount of tokens /// against the maximum allowed price impact limit. /// @param amount Amount of tokens. /// @return True if the price impact is allowed, false otherwise. function isAllowedPriceImpact(uint256 amount) public view returns (bool) { // Get reserve of the collateral token. address WETH = uniswapRouter.WETH(); address token0 = WETH < collateralToken ? WETH : collateralToken; (uint256 reserve0, uint256 reserve1, ) = uniswapPair.getReserves(); uint256 collateralTokenReserve = WETH == token0 ? reserve1 : reserve0; // Same as: priceImpact <= priceImpactLimit return amount * BASIS_POINTS_DIVISOR <= maxAllowedPriceImpact * collateralTokenReserve; } /// @notice Compute Uniswap v2 pair address. /// @param factory Address of the Uniswap v2 factory. /// @param tokenA Address of token A. /// @param tokenB Address of token B. /// @return Address of token pair. function computePairAddress( address factory, address tokenA, address tokenB ) internal pure returns (address) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); return address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" ) ) ) ) ); } }
@notice Checks the price impact of buying a given amount of tokens against the maximum allowed price impact limit. @param amount Amount of tokens. @return True if the price impact is allowed, false otherwise. Get reserve of the collateral token. Same as: priceImpact <= priceImpactLimit
function isAllowedPriceImpact(uint256 amount) public view returns (bool) { address WETH = uniswapRouter.WETH(); address token0 = WETH < collateralToken ? WETH : collateralToken; (uint256 reserve0, uint256 reserve1, ) = uniswapPair.getReserves(); uint256 collateralTokenReserve = WETH == token0 ? reserve1 : reserve0; return amount * BASIS_POINTS_DIVISOR <= maxAllowedPriceImpact * collateralTokenReserve; }
919,700
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 13074, 326, 6205, 15800, 434, 30143, 310, 279, 864, 3844, 434, 2430, 540, 5314, 326, 4207, 2935, 6205, 15800, 1800, 18, 632, 891, 3844, 16811, 434, 2430, 18, 632, 2463, 1053, 309, 326, 6205, 15800, 353, 2935, 16, 629, 3541, 18, 968, 20501, 434, 326, 4508, 2045, 287, 1147, 18, 17795, 487, 30, 6205, 22683, 621, 1648, 6205, 22683, 621, 3039, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 21956, 5147, 22683, 621, 12, 11890, 5034, 3844, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1758, 678, 1584, 44, 273, 640, 291, 91, 438, 8259, 18, 59, 1584, 44, 5621, 203, 3639, 1758, 1147, 20, 273, 678, 1584, 44, 411, 4508, 2045, 287, 1345, 692, 678, 1584, 44, 294, 4508, 2045, 287, 1345, 31, 203, 3639, 261, 11890, 5034, 20501, 20, 16, 2254, 5034, 20501, 21, 16, 262, 273, 640, 291, 91, 438, 4154, 18, 588, 607, 264, 3324, 5621, 203, 3639, 2254, 5034, 4508, 2045, 287, 1345, 607, 6527, 273, 678, 1584, 44, 422, 1147, 20, 692, 20501, 21, 294, 20501, 20, 31, 203, 203, 3639, 327, 203, 5411, 3844, 380, 28143, 15664, 67, 8941, 55, 67, 2565, 26780, 916, 1648, 203, 5411, 943, 5042, 5147, 22683, 621, 380, 4508, 2045, 287, 1345, 607, 6527, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.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.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.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 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 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 virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @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: * * - `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 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 virtual { _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 { } } // 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.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.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 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function parseAssetsForAction( address _vaultProxy, bytes4 _selector, bytes calldata _encodedCallArgs ) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../utils/actions/ParaSwapV5ActionsMixin.sol"; import "../utils/AdapterBase.sol"; /// @title ParaSwapV5Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with ParaSwap (v5) /// @dev Does not support any protocol that collects additional protocol fees as ETH/WETH, e.g., 0x v3 contract ParaSwapV5Adapter is AdapterBase, ParaSwapV5ActionsMixin { constructor( address _integrationManager, address _augustusSwapper, address _tokenTransferProxy ) public AdapterBase(_integrationManager) ParaSwapV5ActionsMixin(_augustusSwapper, _tokenTransferProxy) {} // EXTERNAL FUNCTIONS /// @notice Trades assets on ParaSwap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action /// @dev ParaSwap v5 completely uses entire outgoing asset balance and incoming asset /// is sent directly to the beneficiary (the _vaultProxy) function takeOrder( address _vaultProxy, bytes calldata _actionData, bytes calldata ) external onlyIntegrationManager { ( uint256 minIncomingAssetAmount, uint256 expectedIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount, bytes16 uuid, IParaSwapV5AugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_actionData); __paraSwapV5MultiSwap( outgoingAsset, outgoingAssetAmount, minIncomingAssetAmount, expectedIncomingAssetAmount, payable(_vaultProxy), uuid, paths ); } /// @notice Parses the expected assets in a particular action /// @param _selector The function selector for the callOnIntegration /// @param _actionData Data specific to this action /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForAction( address, bytes4 _selector, bytes calldata _actionData ) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForAction: _selector invalid"); ( uint256 minIncomingAssetAmount, , address outgoingAsset, uint256 outgoingAssetAmount, , IParaSwapV5AugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_actionData); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = paths[paths.length - 1].to; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper to decode the encoded callOnIntegration call arguments function __decodeCallArgs(bytes calldata _actionData) private pure returns ( uint256 minIncomingAssetAmount_, uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics address outgoingAsset_, uint256 outgoingAssetAmount_, bytes16 uuid_, IParaSwapV5AugustusSwapper.Path[] memory paths_ ) { return abi.decode( _actionData, (uint256, uint256, address, uint256, bytes16, IParaSwapV5AugustusSwapper.Path[]) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../utils/AssetHelpers.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors, AssetHelpers { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _assetData ) { _; (, , address[] memory incomingAssets) = __decodeAssetData(_assetData); __pushFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler(address _vaultProxy, bytes memory _assetData) { _; (address[] memory spendAssets, , ) = __decodeAssetData(_assetData); __pushFullAssetBalances(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper to decode the _assetData param passed to adapter call function __decodeAssetData(bytes memory _assetData) internal pure returns ( address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode(_assetData, (address[], uint256[], address[])); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Rewards bytes4 public constant CLAIM_REWARDS_SELECTOR = bytes4( keccak256("claimRewards(address,bytes,bytes)") ); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../../interfaces/IParaSwapV5AugustusSwapper.sol"; import "../../../../../utils/AssetHelpers.sol"; /// @title ParaSwapV5ActionsMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin contract for interacting with ParaSwap (v5) abstract contract ParaSwapV5ActionsMixin is AssetHelpers { address private immutable PARA_SWAP_V5_AUGUSTUS_SWAPPER; address private immutable PARA_SWAP_V5_TOKEN_TRANSFER_PROXY; constructor(address _augustusSwapper, address _tokenTransferProxy) public { PARA_SWAP_V5_AUGUSTUS_SWAPPER = _augustusSwapper; PARA_SWAP_V5_TOKEN_TRANSFER_PROXY = _tokenTransferProxy; } /// @dev Helper to execute a multiSwap() order. /// Leaves any ETH remainder from intermediary steps in ParaSwap in order to save on gas. function __paraSwapV5MultiSwap( address _fromToken, uint256 _fromAmount, uint256 _toAmount, uint256 _expectedAmount, address payable _beneficiary, bytes16 _uuid, IParaSwapV5AugustusSwapper.Path[] memory _path ) internal { __approveAssetMaxAsNeeded(_fromToken, getParaSwapV5TokenTransferProxy(), _fromAmount); IParaSwapV5AugustusSwapper.SellData memory sellData = IParaSwapV5AugustusSwapper.SellData({ fromToken: _fromToken, fromAmount: _fromAmount, toAmount: _toAmount, expectedAmount: _expectedAmount, beneficiary: _beneficiary, path: _path, partner: address(0), feePercent: 0, permit: "", deadline: block.timestamp, uuid: _uuid // Purely for data tracking by ParaSwap }); IParaSwapV5AugustusSwapper(getParaSwapV5AugustusSwapper()).multiSwap(sellData); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `PARA_SWAP_V5_AUGUSTUS_SWAPPER` variable /// @return augustusSwapper_ The `PARA_SWAP_V5_AUGUSTUS_SWAPPER` variable value function getParaSwapV5AugustusSwapper() public view returns (address augustusSwapper_) { return PARA_SWAP_V5_AUGUSTUS_SWAPPER; } /// @notice Gets the `PARA_SWAP_V5_TOKEN_TRANSFER_PROXY` variable /// @return tokenTransferProxy_ The `PARA_SWAP_V5_TOKEN_TRANSFER_PROXY` variable value function getParaSwapV5TokenTransferProxy() public view returns (address tokenTransferProxy_) { return PARA_SWAP_V5_TOKEN_TRANSFER_PROXY; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title ParaSwap V5 IAugustusSwapper interface interface IParaSwapV5AugustusSwapper { struct Adapter { address payable adapter; uint256 percent; uint256 networkFee; Route[] route; } struct Route { uint256 index; address targetExchange; uint256 percent; bytes payload; uint256 networkFee; } struct Path { address to; uint256 totalNetworkFee; Adapter[] adapters; } struct SellData { address fromToken; uint256 fromAmount; uint256 toAmount; uint256 expectedAmount; address payable beneficiary; Path[] path; address payable partner; uint256 feePercent; bytes permit; uint256 deadline; bytes16 uuid; } function multiSwap(SellData calldata) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /// @title AssetHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice A util contract for common token actions abstract contract AssetHelpers { using SafeERC20 for ERC20; using SafeMath for uint256; /// @dev Helper to approve a target account with the max amount of an asset. /// This is helpful for fully trusted contracts, such as adapters that /// interact with external protocol like Uniswap, Compound, etc. function __approveAssetMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { uint256 allowance = ERC20(_asset).allowance(address(this), _target); if (allowance < _neededAmount) { if (allowance > 0) { ERC20(_asset).safeApprove(_target, 0); } ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to transfer full asset balances from the current contract to a target function __pushFullAssetBalances(address _target, address[] memory _assets) internal returns (uint256[] memory amountsTransferred_) { amountsTransferred_ = new uint256[](_assets.length); for (uint256 i; i < _assets.length; i++) { ERC20 assetContract = ERC20(_assets[i]); amountsTransferred_[i] = assetContract.balanceOf(address(this)); if (amountsTransferred_[i] > 0) { assetContract.safeTransfer(_target, amountsTransferred_[i]); } } return amountsTransferred_; } }
@notice Parses the expected assets in a particular action @param _selector The function selector for the callOnIntegration @param _actionData Data specific to this action @return spendAssetsHandleType_ A type that dictates how to handle granting the adapter access to spend assets (`None` by default) @return spendAssets_ The assets to spend in the call @return spendAssetAmounts_ The max asset amounts to spend in the call @return incomingAssets_ The assets to receive in the call @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForAction( address, bytes4 _selector, bytes calldata _actionData ) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForAction: _selector invalid"); ( uint256 minIncomingAssetAmount, , address outgoingAsset, uint256 outgoingAssetAmount, , IParaSwapV5AugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_actionData); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = paths[paths.length - 1].to; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); }
9,955,484
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 2280, 2420, 326, 2665, 7176, 316, 279, 6826, 1301, 632, 891, 389, 9663, 1021, 445, 3451, 364, 326, 745, 1398, 15372, 632, 891, 389, 1128, 751, 1910, 2923, 358, 333, 1301, 632, 2463, 17571, 10726, 3259, 559, 67, 432, 618, 716, 2065, 815, 3661, 358, 1640, 7936, 310, 326, 4516, 2006, 358, 17571, 7176, 21863, 7036, 68, 635, 805, 13, 632, 2463, 17571, 10726, 67, 1021, 7176, 358, 17571, 316, 326, 745, 632, 2463, 17571, 6672, 6275, 87, 67, 1021, 943, 3310, 30980, 358, 17571, 316, 326, 745, 632, 2463, 6935, 10726, 67, 1021, 7176, 358, 6798, 316, 326, 745, 632, 2463, 1131, 20370, 6672, 6275, 87, 67, 1021, 1131, 3310, 30980, 358, 6798, 316, 326, 745, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1109, 10726, 1290, 1803, 12, 203, 3639, 1758, 16, 203, 3639, 1731, 24, 389, 9663, 16, 203, 3639, 1731, 745, 892, 389, 1128, 751, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 203, 5411, 467, 15372, 1318, 18, 27223, 10726, 3259, 559, 17571, 10726, 3259, 559, 67, 16, 203, 5411, 1758, 8526, 3778, 17571, 10726, 67, 16, 203, 5411, 2254, 5034, 8526, 3778, 17571, 6672, 6275, 87, 67, 16, 203, 5411, 1758, 8526, 3778, 6935, 10726, 67, 16, 203, 5411, 2254, 5034, 8526, 3778, 1131, 20370, 6672, 6275, 87, 67, 203, 3639, 262, 203, 565, 288, 203, 3639, 2583, 24899, 9663, 422, 399, 37, 6859, 67, 7954, 67, 4803, 916, 16, 315, 2670, 10726, 1290, 1803, 30, 389, 9663, 2057, 8863, 203, 203, 3639, 261, 203, 5411, 2254, 5034, 1131, 20370, 6672, 6275, 16, 203, 5411, 269, 203, 5411, 1758, 12902, 6672, 16, 203, 5411, 2254, 5034, 12902, 6672, 6275, 16, 203, 5411, 269, 203, 5411, 467, 23529, 12521, 58, 25, 37, 637, 641, 407, 12521, 457, 18, 743, 8526, 3778, 2953, 203, 3639, 262, 273, 1001, 3922, 1477, 2615, 24899, 1128, 751, 1769, 203, 203, 3639, 17571, 10726, 67, 273, 394, 1758, 8526, 12, 21, 1769, 203, 3639, 17571, 10726, 67, 63, 20, 65, 273, 12902, 6672, 31, 203, 203, 3639, 17571, 6672, 6275, 87, 67, 273, 394, 2254, 5034, 8526, 12, 21, 1769, 203, 3639, 17571, 6672, 6275, 87, 67, 63, 20, 65, 273, 12902, 6672, 6275, 31, 203, 203, 3639, 6935, 10726, 67, 273, 394, 1758, 8526, 12, 21, 1769, 203, 3639, 6935, 10726, 67, 63, 20, 65, 273, 2953, 63, 4481, 18, 2469, 300, 404, 8009, 869, 31, 203, 203, 3639, 1131, 20370, 6672, 6275, 87, 67, 273, 394, 2254, 5034, 8526, 12, 21, 1769, 203, 3639, 1131, 20370, 6672, 6275, 87, 67, 63, 20, 65, 273, 1131, 20370, 6672, 6275, 31, 203, 203, 3639, 327, 261, 203, 5411, 467, 15372, 1318, 18, 27223, 10726, 3259, 559, 18, 5912, 16, 203, 5411, 17571, 10726, 67, 16, 203, 5411, 17571, 6672, 6275, 87, 67, 16, 203, 5411, 6935, 10726, 67, 16, 203, 5411, 1131, 20370, 6672, 6275, 87, 67, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x8696ea38686dDb96122512901D99352633A25184/sources/project_/contracts/diamond/libraries/LibTimeLock.sol
todo: 后面改回 apollox.time.lock.storage
library LibTimeLock { using Address for address; bytes32 constant TIME_LOCK_POSITION = keccak256("apollox.time.lock.storage.20230503"); pragma solidity ^0.8.19; struct Transaction { string functionSignature; bytes data; uint40 executeTime; uint40 expiryTime; } struct TimeLockStorage { uint256 salt; mapping(bytes32 => Transaction) transactions; } function timeLockStorage() internal pure returns (TimeLockStorage storage tls) { bytes32 position = TIME_LOCK_POSITION; assembly { tls.slot := position } } function timeLockStorage() internal pure returns (TimeLockStorage storage tls) { bytes32 position = TIME_LOCK_POSITION; assembly { tls.slot := position } } event QueueTransaction(bytes32 indexed transactionHash, string functionSignature, bytes data); event CancelTransaction(bytes32 indexed transactionHash); event ExecuteTransaction(bytes32 indexed transactionHash); function queueTransaction(string calldata functionSignature, bytes calldata data) internal { TimeLockStorage storage tls = timeLockStorage(); uint256 executeTime = block.timestamp + Constants.TIME_LOCK_DELAY; bytes32 transactionHash = keccak256(abi.encode(functionSignature, data, executeTime, tls.salt)); require(tls.transactions[transactionHash].executeTime == 0, "LibTimeLock: Transaction already exists"); tls.salt++; tls.transactions[transactionHash] = Transaction( functionSignature, data, uint40(executeTime), uint40(block.timestamp + Constants.TIME_LOCK_GRACE_PERIOD) ); emit QueueTransaction(transactionHash, functionSignature, data); } function cancelTransaction(bytes32 transactionHash) internal { TimeLockStorage storage tls = timeLockStorage(); require(tls.transactions[transactionHash].executeTime > 0, "LibTimeLock: Transaction hasn't been queued"); delete tls.transactions[transactionHash]; emit CancelTransaction(transactionHash); } function executeTransaction(bytes32 transactionHash) internal returns (bytes memory) { TimeLockStorage storage tls = timeLockStorage(); require(tls.transactions[transactionHash].executeTime > 0, "LibTimeLock: Transaction hasn't been queued"); require(tls.transactions[transactionHash].executeTime >= block.timestamp, "LibTimeLock: Transaction hasn't surpassed time lock"); require(tls.transactions[transactionHash].expiryTime <= block.timestamp, "LibTimeLock: Transaction is stale"); Transaction storage transaction = tls.transactions[transactionHash]; bytes memory data; if (bytes(transaction.functionSignature).length == 0) { data = transaction.data; data = abi.encodePacked(bytes4(keccak256(bytes(transaction.functionSignature))), transaction.data); } function executeTransaction(bytes32 transactionHash) internal returns (bytes memory) { TimeLockStorage storage tls = timeLockStorage(); require(tls.transactions[transactionHash].executeTime > 0, "LibTimeLock: Transaction hasn't been queued"); require(tls.transactions[transactionHash].executeTime >= block.timestamp, "LibTimeLock: Transaction hasn't surpassed time lock"); require(tls.transactions[transactionHash].expiryTime <= block.timestamp, "LibTimeLock: Transaction is stale"); Transaction storage transaction = tls.transactions[transactionHash]; bytes memory data; if (bytes(transaction.functionSignature).length == 0) { data = transaction.data; data = abi.encodePacked(bytes4(keccak256(bytes(transaction.functionSignature))), transaction.data); } } else { }
3,284,418
[ 1, 4625, 348, 7953, 560, 30, 225, 10621, 30, 225, 166, 243, 241, 170, 256, 100, 167, 247, 122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 31, 203, 203, 565, 1731, 1578, 5381, 8721, 67, 6589, 67, 15258, 273, 417, 24410, 581, 5034, 2932, 438, 355, 383, 92, 18, 957, 18, 739, 18, 5697, 18, 18212, 5082, 3361, 23, 8863, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 3657, 31, 203, 565, 1958, 5947, 288, 203, 3639, 533, 445, 5374, 31, 203, 3639, 1731, 501, 31, 203, 3639, 2254, 7132, 1836, 950, 31, 203, 3639, 2254, 7132, 10839, 950, 31, 203, 565, 289, 203, 203, 565, 1958, 2647, 2531, 3245, 288, 203, 3639, 2254, 5034, 4286, 31, 203, 3639, 2874, 12, 3890, 1578, 516, 5947, 13, 8938, 31, 203, 565, 289, 203, 203, 565, 445, 813, 2531, 3245, 1435, 2713, 16618, 1135, 261, 950, 2531, 3245, 2502, 6871, 13, 288, 203, 3639, 1731, 1578, 1754, 273, 8721, 67, 6589, 67, 15258, 31, 203, 3639, 19931, 288, 203, 5411, 6871, 18, 14194, 519, 1754, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 813, 2531, 3245, 1435, 2713, 16618, 1135, 261, 950, 2531, 3245, 2502, 6871, 13, 288, 203, 3639, 1731, 1578, 1754, 273, 8721, 67, 6589, 67, 15258, 31, 203, 3639, 19931, 288, 203, 5411, 6871, 18, 14194, 519, 1754, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 871, 7530, 3342, 12, 3890, 1578, 8808, 2492, 2310, 16, 533, 445, 5374, 16, 1731, 501, 1769, 203, 565, 871, 10347, 3342, 12, 3890, 1578, 8808, 2492, 2310, 1769, 203, 565, 871, 7903, 3342, 12, 3890, 1578, 8808, 2492, 2310, 1769, 203, 203, 565, 445, 2389, 3342, 12, 1080, 745, 892, 445, 5374, 16, 1731, 745, 892, 501, 13, 2713, 288, 203, 3639, 2647, 2531, 3245, 2502, 6871, 273, 813, 2531, 3245, 5621, 203, 3639, 2254, 5034, 1836, 950, 273, 1203, 18, 5508, 397, 5245, 18, 4684, 67, 6589, 67, 26101, 31, 203, 3639, 1731, 1578, 2492, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 915, 5374, 16, 501, 16, 1836, 950, 16, 6871, 18, 5759, 10019, 203, 3639, 2583, 12, 17116, 18, 20376, 63, 7958, 2310, 8009, 8837, 950, 422, 374, 16, 315, 5664, 950, 2531, 30, 5947, 1818, 1704, 8863, 203, 3639, 6871, 18, 5759, 9904, 31, 203, 3639, 6871, 18, 20376, 63, 7958, 2310, 65, 273, 5947, 12, 203, 5411, 445, 5374, 16, 501, 16, 2254, 7132, 12, 8837, 950, 3631, 203, 5411, 2254, 7132, 12, 2629, 18, 5508, 397, 5245, 18, 4684, 67, 6589, 67, 43, 9254, 67, 28437, 13, 203, 3639, 11272, 203, 3639, 3626, 7530, 3342, 12, 7958, 2310, 16, 445, 5374, 16, 501, 1769, 203, 565, 289, 203, 203, 565, 445, 3755, 3342, 12, 3890, 1578, 2492, 2310, 13, 2713, 288, 203, 3639, 2647, 2531, 3245, 2502, 6871, 273, 813, 2531, 3245, 5621, 203, 3639, 2583, 12, 17116, 18, 20376, 63, 7958, 2310, 8009, 8837, 950, 405, 374, 16, 315, 5664, 950, 2531, 30, 5947, 13342, 1404, 2118, 12234, 8863, 203, 3639, 1430, 6871, 18, 20376, 63, 7958, 2310, 15533, 203, 3639, 3626, 10347, 3342, 12, 7958, 2310, 1769, 203, 565, 289, 203, 203, 565, 445, 1836, 3342, 12, 3890, 1578, 2492, 2310, 13, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 2647, 2531, 3245, 2502, 6871, 273, 813, 2531, 3245, 5621, 203, 3639, 2583, 12, 17116, 18, 20376, 63, 7958, 2310, 8009, 8837, 950, 405, 374, 16, 315, 5664, 950, 2531, 30, 5947, 13342, 1404, 2118, 12234, 8863, 203, 3639, 2583, 12, 17116, 18, 20376, 63, 7958, 2310, 8009, 8837, 950, 1545, 1203, 18, 5508, 16, 315, 5664, 950, 2531, 30, 5947, 13342, 1404, 5056, 23603, 813, 2176, 8863, 203, 3639, 2583, 12, 17116, 18, 20376, 63, 7958, 2310, 8009, 22409, 950, 1648, 1203, 18, 5508, 16, 315, 5664, 950, 2531, 30, 5947, 353, 14067, 8863, 203, 203, 3639, 5947, 2502, 2492, 273, 6871, 18, 20376, 63, 7958, 2310, 15533, 203, 3639, 1731, 3778, 501, 31, 203, 3639, 309, 261, 3890, 12, 7958, 18, 915, 5374, 2934, 2469, 422, 374, 13, 288, 203, 5411, 501, 273, 2492, 18, 892, 31, 203, 5411, 501, 273, 24126, 18, 3015, 4420, 329, 12, 3890, 24, 12, 79, 24410, 581, 5034, 12, 3890, 12, 7958, 18, 915, 5374, 3719, 3631, 2492, 18, 892, 1769, 203, 3639, 289, 203, 565, 445, 1836, 3342, 12, 3890, 1578, 2492, 2310, 13, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 2647, 2531, 3245, 2502, 6871, 273, 813, 2531, 3245, 5621, 203, 3639, 2583, 12, 17116, 18, 20376, 63, 7958, 2310, 8009, 8837, 950, 405, 374, 16, 315, 5664, 950, 2531, 30, 5947, 13342, 1404, 2118, 12234, 8863, 203, 3639, 2583, 12, 17116, 18, 20376, 63, 7958, 2310, 8009, 8837, 950, 1545, 1203, 18, 5508, 16, 315, 5664, 950, 2531, 30, 5947, 13342, 1404, 5056, 23603, 813, 2176, 8863, 203, 3639, 2583, 12, 17116, 18, 20376, 63, 7958, 2310, 8009, 22409, 950, 1648, 1203, 18, 5508, 16, 315, 5664, 950, 2531, 30, 5947, 353, 14067, 8863, 203, 203, 3639, 5947, 2502, 2492, 273, 6871, 18, 20376, 63, 7958, 2310, 15533, 203, 3639, 1731, 3778, 501, 31, 203, 3639, 309, 261, 3890, 12, 7958, 18, 915, 5374, 2934, 2469, 422, 374, 13, 288, 203, 5411, 501, 273, 2492, 18, 892, 31, 203, 5411, 501, 273, 24126, 18, 3015, 4420, 329, 12, 3890, 24, 12, 79, 24410, 581, 5034, 12, 3890, 12, 7958, 18, 915, 5374, 3719, 3631, 2492, 18, 892, 1769, 203, 3639, 289, 203, 3639, 289, 469, 288, 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, -100, -100, -100, -100, -100, -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: Apache-2.0 // WARNING: This has been validated for yearn vaults up to version 0.2.11. // Using this code with any later version can be unsafe. pragma solidity ^0.8.0; import "./interfaces/IERC20.sol"; import "./interfaces/IYearnVault.sol"; import "./WrappedPosition.sol"; /// @author Element Finance /// @title Yearn Vault v1 Asset Proxy contract YVaultAssetProxy is WrappedPosition { IYearnVault public immutable vault; uint8 public immutable vaultDecimals; // This contract allows deposits to a reserve which can // be used to short circuit the deposit process and save gas // The following mapping tracks those non-transferable deposits mapping(address => uint256) public reserveBalances; // These variables store the token balances of this contract and // should be packed by solidity into a single slot. uint128 public reserveUnderlying; uint128 public reserveShares; // This is the total amount of reserve deposits uint256 public reserveSupply; /// @notice Constructs this contract and stores needed data /// @param vault_ The yearn v2 vault /// @param _token The underlying token. /// This token should revert in the event of a transfer failure. /// @param _name The name of the token created /// @param _symbol The symbol of the token created constructor( address vault_, IERC20 _token, string memory _name, string memory _symbol ) WrappedPosition(_token, _name, _symbol) { vault = IYearnVault(vault_); _token.approve(vault_, type(uint256).max); uint8 localVaultDecimals = IERC20(vault_).decimals(); vaultDecimals = localVaultDecimals; require( uint8(_token.decimals()) == localVaultDecimals, "Inconsistent decimals" ); // We check that this is a compatible yearn version _versionCheck(IYearnVault(vault_)); } /// @notice An override-able version checking function, reverts if the vault has the wrong version /// @param _vault The yearn vault address /// @dev This function can be overridden by an inheriting upgrade contract function _versionCheck(IYearnVault _vault) internal virtual view { string memory apiVersion = _vault.apiVersion(); require( _stringEq(apiVersion, "0.3.0") || _stringEq(apiVersion, "0.3.1") || _stringEq(apiVersion, "0.3.2") || _stringEq(apiVersion, "0.3.3") || _stringEq(apiVersion, "0.3.4") || _stringEq(apiVersion, "0.3.5"), "Unsupported Version" ); } /// @notice checks if two strings are equal /// @param s1 string one /// @param s2 string two /// @return bool whether they are equal function _stringEq(string memory s1, string memory s2) internal pure returns (bool) { bytes32 h1 = keccak256(abi.encodePacked(s1)); bytes32 h2 = keccak256(abi.encodePacked(s2)); return (h1 == h2); } /// @notice This function allows a user to deposit to the reserve /// Note - there's no incentive to do so. You could earn some /// interest but less interest than yearn. All deposits use /// the underlying token. /// @param _amount The amount of underlying to deposit function reserveDeposit(uint256 _amount) external { // Transfer from user, note variable 'token' is the immutable // inherited from the abstract WrappedPosition contract. token.transferFrom(msg.sender, address(this), _amount); // Load the reserves (uint256 localUnderlying, uint256 localShares) = _getReserves(); // Calculate the total reserve value uint256 totalValue = localUnderlying; totalValue += _yearnDepositConverter(localShares, true); // If this is the first deposit we need different logic uint256 localReserveSupply = reserveSupply; uint256 mintAmount; if (localReserveSupply == 0) { // If this is the first mint the tokens are exactly the supplied underlying mintAmount = _amount; } else { // Otherwise we mint the proportion that this increases the value held by this contract mintAmount = (localReserveSupply * _amount) / totalValue; } // This hack means that the contract will never have zero balance of underlying // which levels the gas expenditure of the transfer to this contract. Permanently locks // the smallest possible unit of the underlying. if (localUnderlying == 0 && localShares == 0) { _amount -= 1; } // Set the reserves that this contract has more underlying _setReserves(localUnderlying + _amount, localShares); // Note that the sender has deposited and increase reserveSupply reserveBalances[msg.sender] += mintAmount; reserveSupply = localReserveSupply + mintAmount; } /// @notice This function allows a holder of reserve balance to withdraw their share /// @param _amount The number of reserve shares to withdraw function reserveWithdraw(uint256 _amount) external { // Remove 'amount' from the balances of the sender. Because this is 8.0 it will revert on underflow reserveBalances[msg.sender] -= _amount; // We load the reserves (uint256 localUnderlying, uint256 localShares) = _getReserves(); uint256 localReserveSupply = reserveSupply; // Then we calculate the proportion of the shares to redeem uint256 userShares = (localShares * _amount) / localReserveSupply; // First we withdraw the proportion of shares tokens belonging to the caller uint256 freedUnderlying = vault.withdraw(userShares, address(this), 0); // We calculate the amount of underlying to send uint256 userUnderlying = (localUnderlying * _amount) / localReserveSupply; // We then store the updated reserve amounts _setReserves( localUnderlying - userUnderlying, localShares - userShares ); // We note a reduction in local supply reserveSupply = localReserveSupply - _amount; // We send the redemption underlying to the caller // Note 'token' is an immutable from shares token.transfer(msg.sender, freedUnderlying + userUnderlying); } /// @notice Makes the actual deposit into the yearn vault /// Tries to use the local balances before depositing /// @return Tuple (the shares minted, amount underlying used) function _deposit() internal override returns (uint256, uint256) { //Load reserves (uint256 localUnderlying, uint256 localShares) = _getReserves(); // Get the amount deposited uint256 amount = token.balanceOf(address(this)) - localUnderlying; // fixing for the fact there's an extra underlying if (localUnderlying != 0 || localShares != 0) { amount -= 1; } // Calculate the amount of shares the amount deposited is worth uint256 neededShares = _yearnDepositConverter(amount, false); // If we have enough in local reserves we don't call out for deposits if (localShares > neededShares) { // We set the reserves _setReserves(localUnderlying + amount, localShares - neededShares); // And then we short circuit execution and return return (neededShares, amount); } // Deposit and get the shares that were minted to this uint256 shares = vault.deposit(localUnderlying + amount, address(this)); // calculate the user share uint256 userShare = (amount * shares) / (localUnderlying + amount); // We set the reserves _setReserves(0, localShares + shares - userShare); // Return the amount of shares the user has produced, and the amount used for it. return (userShare, amount); } /// @notice Withdraw the number of shares and will short circuit if it can /// @param _shares The number of shares to withdraw /// @param _destination The address to send the output funds /// @param _underlyingPerShare The possibly precomputed underlying per share function _withdraw( uint256 _shares, address _destination, uint256 _underlyingPerShare ) internal override returns (uint256) { // If we do not have it we load the price per share if (_underlyingPerShare == 0) { _underlyingPerShare = _pricePerShare(); } // We load the reserves (uint256 localUnderlying, uint256 localShares) = _getReserves(); // Calculate the amount of shares the amount deposited is worth uint256 needed = (_shares * _pricePerShare()) / (10**vaultDecimals); // If we have enough underlying we don't have to actually withdraw if (needed < localUnderlying) { // We set the reserves to be the new reserves _setReserves(localUnderlying - needed, localShares + _shares); // Then transfer needed underlying to the destination // 'token' is an immutable in WrappedPosition token.transfer(_destination, needed); // Short circuit and return return (needed); } // If we don't have enough local reserves we do the actual withdraw // Withdraws shares from the vault. Max loss is set at 100% as // the minimum output value is enforced by the calling // function in the WrappedPosition contract. uint256 amountReceived = vault.withdraw( _shares + localShares, address(this), 10000 ); // calculate the user share uint256 userShare = (_shares * amountReceived) / (localShares + _shares); _setReserves(localUnderlying + amountReceived - userShare, 0); // Transfer the underlying to the destination 'token' is an immutable in WrappedPosition token.transfer(_destination, userShare); // Return the amount of underlying return userShare; } /// @notice Get the underlying amount of tokens per shares given /// @param _amount The amount of shares you want to know the value of /// @return Value of shares in underlying token function _underlying(uint256 _amount) internal override view returns (uint256) { return (_amount * _pricePerShare()) / (10**vaultDecimals); } /// @notice Get the price per share in the vault /// @return The price per share in units of underlying; function _pricePerShare() internal view returns (uint256) { return vault.pricePerShare(); } /// @notice Function to reset approvals for the proxy function approve() external { token.approve(address(vault), 0); token.approve(address(vault), type(uint256).max); } /// @notice Helper to get the reserves with one sload /// @return Tuple (reserve underlying, reserve shares) function _getReserves() internal view returns (uint256, uint256) { return (uint256(reserveUnderlying), uint256(reserveShares)); } /// @notice Helper to set reserves using one sstore /// @param _newReserveUnderlying The new reserve of underlying /// @param _newReserveShares The new reserve of wrapped position shares function _setReserves( uint256 _newReserveUnderlying, uint256 _newReserveShares ) internal { reserveUnderlying = uint128(_newReserveUnderlying); reserveShares = uint128(_newReserveShares); } /// @notice Converts an input of shares to it's output of underlying or an input /// of underlying to an output of shares, using yearn 's deposit pricing /// @param amount the amount of input, shares if 'sharesIn == true' underlying if not /// @param sharesIn true to convert from yearn shares to underlying, false to convert from /// underlying to yearn shares /// @dev WARNING - In yearn 0.3.1 - 0.3.5 this is an exact match for deposit logic /// but not withdraw logic in versions 0.3.2-0.3.5. In versions 0.4.0+ /// it is not a match for yearn deposit ratios. /// @return The converted output of either underlying or yearn shares function _yearnDepositConverter(uint256 amount, bool sharesIn) internal virtual view returns (uint256) { // Load the yearn total supply and assets uint256 yearnTotalSupply = vault.totalSupply(); uint256 yearnTotalAssets = vault.totalAssets(); // If we are converted shares to underlying if (sharesIn) { // then we get the fraction of yearn shares this is and multiply by assets return (yearnTotalAssets * amount) / yearnTotalSupply; } else { // otherwise we figure out the faction of yearn assets this is and see how // many assets we get out. return (yearnTotalSupply * amount) / yearnTotalAssets; } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IERC20 { function symbol() external view returns (string memory); function balanceOf(address account) external view returns (uint256); // Note this is non standard but nearly all ERC20 have exposed decimal functions function decimals() external view returns (uint8); 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 ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IERC20.sol"; interface IYearnVault is IERC20 { function deposit(uint256, address) external returns (uint256); function withdraw( uint256, address, uint256 ) external returns (uint256); // Returns the amount of underlying per each unit [1e18] of yearn shares function pricePerShare() external view returns (uint256); function governance() external view returns (address); function setDepositLimit(uint256) external; function totalSupply() external view returns (uint256); function totalAssets() external view returns (uint256); function apiVersion() external view returns (string memory); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interfaces/IERC20.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IWrappedPosition.sol"; import "./libraries/ERC20Permit.sol"; /// @author Element Finance /// @title Wrapped Position Core abstract contract WrappedPosition is ERC20Permit, IWrappedPosition { IERC20 public immutable override token; /// @notice Constructs this contract /// @param _token The underlying token. /// This token should revert in the event of a transfer failure. /// @param _name the name of this contract /// @param _symbol the symbol for this contract constructor( IERC20 _token, string memory _name, string memory _symbol ) ERC20Permit(_name, _symbol) { token = _token; // We set our decimals to be the same as the underlying _setupDecimals(_token.decimals()); } /// We expect that the following logic will be present in an integration implementation /// which inherits from this contract /// @dev Makes the actual deposit into the 'vault' /// @return Tuple (shares minted, amount underlying used) function _deposit() internal virtual returns (uint256, uint256); /// @dev Makes the actual withdraw from the 'vault' /// @return returns the amount produced function _withdraw( uint256, address, uint256 ) internal virtual returns (uint256); /// @dev Converts between an internal balance representation /// and underlying tokens. /// @return The amount of underlying the input is worth function _underlying(uint256) internal virtual view returns (uint256); /// @notice Get the underlying balance of an address /// @param _who The address to query /// @return The underlying token balance of the address function balanceOfUnderlying(address _who) external override view returns (uint256) { return _underlying(balanceOf[_who]); } /// @notice Returns the amount of the underlying asset a certain amount of shares is worth /// @param _shares Shares to calculate underlying value for /// @return The value of underlying assets for the given shares function getSharesToUnderlying(uint256 _shares) external override view returns (uint256) { return _underlying(_shares); } /// @notice Entry point to deposit tokens into the Wrapped Position contract /// Transfers tokens on behalf of caller so the caller must set /// allowance on the contract prior to call. /// @param _amount The amount of underlying tokens to deposit /// @param _destination The address to mint to /// @return Returns the number of Wrapped Position tokens minted function deposit(address _destination, uint256 _amount) external override returns (uint256) { // Send tokens to the proxy token.transferFrom(msg.sender, address(this), _amount); // Calls our internal deposit function (uint256 shares, ) = _deposit(); // Mint them internal ERC20 tokens corresponding to the deposit _mint(_destination, shares); return shares; } /// @notice Entry point to deposit tokens into the Wrapped Position contract /// Assumes the tokens were transferred before this was called /// @param _destination the destination of this deposit /// @return Returns (WP tokens minted, used underlying, /// senders WP balance before mint) /// @dev WARNING - The call which funds this method MUST be in the same transaction // as the call to this method or you risk loss of funds function prefundedDeposit(address _destination) external override returns ( uint256, uint256, uint256 ) { // Calls our internal deposit function (uint256 shares, uint256 usedUnderlying) = _deposit(); uint256 balanceBefore = balanceOf[_destination]; // Mint them internal ERC20 tokens corresponding to the deposit _mint(_destination, shares); return (shares, usedUnderlying, balanceBefore); } /// @notice Exit point to withdraw tokens from the Wrapped Position contract /// @param _destination The address which is credited with tokens /// @param _shares The amount of shares the user is burning to withdraw underlying /// @param _minUnderlying The min output the caller expects /// @return The amount of underlying transferred to the destination function withdraw( address _destination, uint256 _shares, uint256 _minUnderlying ) public override returns (uint256) { return _positionWithdraw(_destination, _shares, _minUnderlying, 0); } /// @notice This function burns enough tokens from the sender to send _amount /// of underlying to the _destination. /// @param _destination The address to send the output to /// @param _amount The amount of underlying to try to redeem for /// @param _minUnderlying The minium underlying to receive /// @return The amount of underlying released, and shares used function withdrawUnderlying( address _destination, uint256 _amount, uint256 _minUnderlying ) external override returns (uint256, uint256) { // First we load the number of underlying per unit of Wrapped Position token uint256 oneUnit = 10**decimals; uint256 underlyingPerShare = _underlying(oneUnit); // Then we calculate the number of shares we need uint256 shares = (_amount * oneUnit) / underlyingPerShare; // Using this we call the normal withdraw function uint256 underlyingReceived = _positionWithdraw( _destination, shares, _minUnderlying, underlyingPerShare ); return (underlyingReceived, shares); } /// @notice This internal function allows the caller to provide a precomputed 'underlyingPerShare' /// so that we can avoid calling it again in the internal function /// @param _destination The destination to send the output to /// @param _shares The number of shares to withdraw /// @param _minUnderlying The min amount of output to produce /// @param _underlyingPerShare The precomputed shares per underlying /// @return The amount of underlying released function _positionWithdraw( address _destination, uint256 _shares, uint256 _minUnderlying, uint256 _underlyingPerShare ) internal returns (uint256) { // Burn users shares _burn(msg.sender, _shares); // Withdraw that many shares from the vault uint256 withdrawAmount = _withdraw( _shares, _destination, _underlyingPerShare ); // We revert if this call doesn't produce enough underlying // This security feature is useful in some edge cases require(withdrawAmount >= _minUnderlying, "Not enough underlying"); return withdrawAmount; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IERC20Permit.sol"; import "./IERC20.sol"; interface IWrappedPosition is IERC20Permit { function token() external view returns (IERC20); function balanceOfUnderlying(address who) external view returns (uint256); function getSharesToUnderlying(uint256 shares) external view returns (uint256); function deposit(address sender, uint256 amount) external returns (uint256); function withdraw( address sender, uint256 _shares, uint256 _minUnderlying ) external returns (uint256); function withdrawUnderlying( address _destination, uint256 _amount, uint256 _minUnderlying ) external returns (uint256, uint256); function prefundedDeposit(address _destination) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "../interfaces/IERC20Permit.sol"; // This default erc20 library is designed for max efficiency and security. // WARNING: By default it does not include totalSupply which breaks the ERC20 standard // to use a fully standard compliant ERC20 use 'ERC20PermitWithSupply" abstract contract ERC20Permit is IERC20Permit { // --- ERC20 Data --- // The name of the erc20 token string public name; // The symbol of the erc20 token string public override symbol; // The decimals of the erc20 token, should default to 18 for new tokens uint8 public override decimals; // A mapping which tracks user token balances mapping(address => uint256) public override balanceOf; // A mapping which tracks which addresses a user allows to move their tokens mapping(address => mapping(address => uint256)) public override allowance; // A mapping which tracks the permit signature nonces for users mapping(address => uint256) public override nonces; // --- EIP712 niceties --- // solhint-disable-next-line var-name-mixedcase bytes32 public override DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice Initializes the erc20 contract /// @param name_ the value 'name' will be set to /// @param symbol_ the value 'symbol' will be set to /// @dev decimals default to 18 and must be reset by an inheriting contract for /// non standard decimal values constructor(string memory name_, string memory symbol_) { // Set the state variables name = name_; symbol = symbol_; decimals = 18; // By setting these addresses to 0 attempting to execute a transfer to // either of them will revert. This is a gas efficient way to prevent // a common user mistake where they transfer to the token address. // These values are not considered 'real' tokens and so are not included // in 'total supply' which only contains minted tokens. balanceOf[address(0)] = type(uint256).max; balanceOf[address(this)] = type(uint256).max; // Optional extra state manipulation _extraConstruction(); // Computes the EIP 712 domain separator which prevents user signed messages for // this contract to be replayed in other contracts. // https://eips.ethereum.org/EIPS/eip-712 DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes("1")), block.chainid, address(this) ) ); } /// @notice An optional override function to execute and change state before immutable assignment function _extraConstruction() internal virtual {} // --- Token --- /// @notice Allows a token owner to send tokens to another address /// @param recipient The address which will be credited with the tokens /// @param amount The amount user token to send /// @return returns true on success, reverts on failure so cannot return false. /// @dev transfers to this contract address or 0 will fail function transfer(address recipient, uint256 amount) public virtual override returns (bool) { // We forward this call to 'transferFrom' return transferFrom(msg.sender, recipient, amount); } /// @notice Transfers an amount of erc20 from a spender to a receipt /// @param spender The source of the ERC20 tokens /// @param recipient The destination of the ERC20 tokens /// @param amount the number of tokens to send /// @return returns true on success and reverts on failure /// @dev will fail transfers which send funds to this contract or 0 function transferFrom( address spender, address recipient, uint256 amount ) public virtual override returns (bool) { // Load balance and allowance uint256 balance = balanceOf[spender]; require(balance >= amount, "ERC20: insufficient-balance"); // We potentially have to change allowances if (spender != msg.sender) { // Loading the allowance in the if block prevents vanilla transfers // from paying for the sload. uint256 allowed = allowance[spender][msg.sender]; // If the allowance is max we do not reduce it // Note - This means that max allowances will be more gas efficient // by not requiring a sstore on 'transferFrom' if (allowed != type(uint256).max) { require(allowed >= amount, "ERC20: insufficient-allowance"); allowance[spender][msg.sender] = allowed - amount; } } // Update the balances balanceOf[spender] = balance - amount; // Note - In the constructor we initialize the 'balanceOf' of address 0 and // the token address to uint256.max and so in 8.0 transfers to those // addresses revert on this step. balanceOf[recipient] = balanceOf[recipient] + amount; // Emit the needed event emit Transfer(spender, recipient, amount); // Return that this call succeeded return true; } /// @notice This internal minting function allows inheriting contracts /// to mint tokens in the way they wish. /// @param account the address which will receive the token. /// @param amount the amount of token which they will receive /// @dev This function is virtual so that it can be overridden, if you /// are reviewing this contract for security you should ensure to /// check for overrides function _mint(address account, uint256 amount) internal virtual { // Add tokens to the account balanceOf[account] = balanceOf[account] + amount; // Emit an event to track the minting emit Transfer(address(0), account, amount); } /// @notice This internal burning function allows inheriting contracts to /// burn tokens in the way they see fit. /// @param account the account to remove tokens from /// @param amount the amount of tokens to remove /// @dev This function is virtual so that it can be overridden, if you /// are reviewing this contract for security you should ensure to /// check for overrides function _burn(address account, uint256 amount) internal virtual { // Reduce the balance of the account balanceOf[account] = balanceOf[account] - amount; // Emit an event tracking transfers emit Transfer(account, address(0), amount); } /// @notice This function allows a user to approve an account which can transfer /// tokens on their behalf. /// @param account The account which will be approve to transfer tokens /// @param amount The approval amount, if set to uint256.max the allowance does not go down on transfers. /// @return returns true for compatibility with the ERC20 standard function approve(address account, uint256 amount) public virtual override returns (bool) { // Set the senders allowance for account to amount allowance[msg.sender][account] = amount; // Emit an event to track approvals emit Approval(msg.sender, account, amount); return true; } /// @notice This function allows a caller who is not the owner of an account to execute the functionality of 'approve' with the owners signature. /// @param owner the owner of the account which is having the new approval set /// @param spender the address which will be allowed to spend owner's tokens /// @param value the new allowance value /// @param deadline the timestamp which the signature must be submitted by to be valid /// @param v Extra ECDSA data which allows public key recovery from signature assumed to be 27 or 28 /// @param r The r component of the ECDSA signature /// @param s The s component of the ECDSA signature /// @dev The signature for this function follows EIP 712 standard and should be generated with the /// eth_signTypedData JSON RPC call instead of the eth_sign JSON RPC call. If using out of date /// parity signing libraries the v component may need to be adjusted. Also it is very rare but possible /// for v to be other values, those values are not supported. function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { // The EIP 712 digest for this function bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner], deadline ) ) ) ); // Require that the owner is not zero require(owner != address(0), "ERC20: invalid-address-0"); // Require that we have a valid signature from the owner require(owner == ecrecover(digest, v, r, s), "ERC20: invalid-permit"); // Require that the signature is not expired require( deadline == 0 || block.timestamp <= deadline, "ERC20: permit-expired" ); // Format the signature to the default format require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ERC20: invalid signature 's' value" ); // Increment the signature nonce to prevent replay nonces[owner]++; // Set the allowance to the new value allowance[owner][spender] = value; // Emit an approval event to be able to track this happening emit Approval(owner, spender, value); } /// @notice Internal function which allows inheriting contract to set custom decimals /// @param decimals_ the new decimal value function _setupDecimals(uint8 decimals_) internal { // Set the decimals decimals = decimals_; } } // Forked from openzepplin // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit is IERC20 { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
We load the reserves
(uint256 localUnderlying, uint256 localShares) = _getReserves();
376,646
[ 1, 4625, 348, 7953, 560, 30, 225, 1660, 1262, 326, 400, 264, 3324, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5034, 1191, 14655, 6291, 16, 2254, 5034, 1191, 24051, 13, 273, 389, 588, 607, 264, 3324, 5621, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; interface IERC20 { function balanceOf(address account) external view returns (uint256); function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; } contract SWAP { AggregatorV3Interface internal priceFeed; address[] public tokens_crypto; mapping (address => address) public linkPool_tokens; uint private initialTimeSamp; uint private initialValue; uint private monthRate; constructor() { // DEFINING KOVAN ADRESS FOR FAKE TOKENS tokens_crypto.push(0x8c67E632Af150673da2bEB27E63EF6189571934a); // Ether Bocconi tokens_crypto.push(0xF9449a9e80Ee0f5FDFd90e8024FDf693d0502Aed); // USDT Bocconi tokens_crypto.push(0x81F92C7FA7B76185Bae7Cd8013277B473739DD80); // USDC Bocconi tokens_crypto.push(0x3E2A0e77e09Eeb4E2b7458412738cD4355c8B7B8); // ENJ Bocconi tokens_crypto.push(0x8001F795da74d3E947Bf9DcD1588c75eEB500bd5); // BTC Bocconi tokens_crypto.push(0x323B18fd3352e4D4a71284aCB65EAAC40205c546); // MANA Bocconi tokens_crypto.push(0x546D7414E0f36389e85e45f0656BBd755E62FC0A); // CRYPTO Bound // DEFINING A MAP FOR LINK PRICE POOL BETWEEN REAL TOKENS AND ETHER // https://docs.chain.link/docs/ethereum-addresses/ linkPool_tokens[tokens_crypto[1]] = 0x0bF499444525a23E7Bb61997539725cA2e928138; // POOL USDT/ETHER linkPool_tokens[tokens_crypto[2]] = 0x64EaC61A2DFda2c3Fa04eED49AA33D021AeC8838; // POOL USDC/ETHER linkPool_tokens[tokens_crypto[3]] = 0xfaDbe2ee798889F02d1d39eDaD98Eff4c7fe95D4; // POOL ENJ/ETHER linkPool_tokens[tokens_crypto[4]] = 0xF7904a295A029a3aBDFFB6F12755974a958C7C25; // POOL BTC/ETHER linkPool_tokens[tokens_crypto[5]] = 0x1b93D8E109cfeDcBb3Cc74eD761DE286d5771511; // POOL MANA/ETHER linkPool_tokens[tokens_crypto[6]] = 0x777A68032a88E5A84678A77Af2CD65A7b3c0775a; // POOL ETHER/USD // Variables initialTimeSamp = 1622505600; // Date of 1st June 2021 - Initial day to update value initialValue = 2000; // Crypto Bound value in 1st June 2021 monthRate = 101059463; // 1.059463% monthly } // Calculate update value for Crypto Bound (1x10^18) to USD function _calculateCryptoToUsd() public view returns(uint){ uint cryptoToUsd; uint diferenceMonth; uint monthsToSeconds = 2629744; diferenceMonth = uint((block.timestamp - initialTimeSamp)/monthsToSeconds); // 1.05946% ao mes == 2% ao ano cryptoToUsd = 2000 * (monthRate ** (diferenceMonth)) / ((10**8)**((diferenceMonth))); return cryptoToUsd; } function _defPriceFeed(address _address) private { priceFeed = AggregatorV3Interface(_address); } //** Function to Swap the 5 different tokens in Fake Ethers, just need to insert the address function swapTokensToEther(address _address) public{ // Creating an array of the balance of all fake tokens // Since we cannot creat a dynamic map, the order fo the array must be the same of // the tokens_crypto int[] memory balanceToken = new int[](tokens_crypto.length); for (uint i = 0; i < tokens_crypto.length; i++) { balanceToken[i] = int(IERC20(tokens_crypto[i]).balanceOf(_address)); } // Array to get the price of the real token to ether with the link pool price // https://docs.chain.link/docs/ethereum-addresses/ int[] memory priceTokenEther = new int[](tokens_crypto.length); for (uint i = 1; i < tokens_crypto.length; i++) { _defPriceFeed(linkPool_tokens[tokens_crypto[i]]); if(i==6){ // Calculate the crypto value in 18 decimals // Crypto to usd then usd to Ether int tempCoversion; tempCoversion = int( (int(_calculateCryptoToUsd()*(10**28))) / _getLatestPrice()); priceTokenEther[i] = tempCoversion; } else { priceTokenEther[i] = _getLatestPrice(); } } // Calculate the total amount of ether // It will be the amount of tokens multiplied for the Link Pool Convertion Rate, normalized for the decimals int tempEther; int totalEther; totalEther = 0; for (uint i = 1; i < tokens_crypto.length; i++) { tempEther = 0; tempEther = balanceToken[i] * priceTokenEther[i] / (10 ** 18); totalEther = totalEther + tempEther; } // Burn the total amount of each fake token for (uint i = 1; i < tokens_crypto.length; i++) { if (balanceToken[i] > 0) { IERC20(tokens_crypto[i]).burn(_address,uint(balanceToken[i])); } } // Mint Fake Ether with the previous calculation IERC20(tokens_crypto[0]).mint(_address,uint(totalEther)); } function swapEtherToTokens(int[] memory share, address _address) public{ // Require that the share array be the same size of all tokens // Get the total amout of ether int numberEther = int(IERC20(tokens_crypto[0]).balanceOf(_address)); // Number of Ether will be transferred for each token int[] memory totalToken = new int[](tokens_crypto.length); for (uint i = 0; i < tokens_crypto.length; i++) { totalToken[i] = int(share[i] * numberEther / (10 ** 6)); } //Calculate the total amount of ether // It will be the amount of tokens multiplied for the Link Pool Convertion Rate, normalized for the decimals int[] memory priceTokenEther = new int[](tokens_crypto.length); for (uint i = 1; i < tokens_crypto.length; i++) { _defPriceFeed(linkPool_tokens[tokens_crypto[i]]); if(i==6){ // Calculate the crypto value in 18 decimals // Crypto to usd then usd to Ether int tempCoversion; tempCoversion = int( (int(_calculateCryptoToUsd()*(10**28))) / _getLatestPrice()); priceTokenEther[i] = tempCoversion; } else { priceTokenEther[i] = _getLatestPrice(); } } // Calculate the total amount of fake Tokens that will be transfereed int[] memory calculatedBalance = new int[](tokens_crypto.length); for (uint i = 1; i < tokens_crypto.length; i++) { calculatedBalance[i] = int(totalToken[i] * (10 ** 18) / priceTokenEther[i]); } // Burn Fake Ether // Update Final Amount of ether numberEther = numberEther - totalToken[0]; IERC20(tokens_crypto[0]).burn(_address,uint(numberEther)); // Mint Fake Tokens for (uint i = 1; i < tokens_crypto.length; i++) { IERC20(tokens_crypto[i]).mint(_address,uint(calculatedBalance[i])); } } function _getLatestPrice() private view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; } }
** Function to Swap the 5 different tokens in Fake Ethers, just need to insert the address Creating an array of the balance of all fake tokens Since we cannot creat a dynamic map, the order fo the array must be the same of the tokens_crypto Calculate the crypto value in 18 decimals Crypto to usd then usd to Ether Burn the total amount of each fake token
function swapTokensToEther(address _address) public{ int[] memory balanceToken = new int[](tokens_crypto.length); for (uint i = 0; i < tokens_crypto.length; i++) { balanceToken[i] = int(IERC20(tokens_crypto[i]).balanceOf(_address)); } for (uint i = 1; i < tokens_crypto.length; i++) { _defPriceFeed(linkPool_tokens[tokens_crypto[i]]); if(i==6){ int tempCoversion; tempCoversion = int( (int(_calculateCryptoToUsd()*(10**28))) / _getLatestPrice()); priceTokenEther[i] = tempCoversion; } else { priceTokenEther[i] = _getLatestPrice(); } } int totalEther; totalEther = 0; for (uint i = 1; i < tokens_crypto.length; i++) { tempEther = 0; tempEther = balanceToken[i] * priceTokenEther[i] / (10 ** 18); totalEther = totalEther + tempEther; } for (uint i = 1; i < tokens_crypto.length; i++) { if (balanceToken[i] > 0) { IERC20(tokens_crypto[i]).burn(_address,uint(balanceToken[i])); } } }
7,328,393
[ 1, 4625, 348, 7953, 560, 30, 2826, 4284, 358, 12738, 326, 1381, 3775, 2430, 316, 11551, 512, 29540, 16, 2537, 1608, 358, 2243, 326, 1758, 21837, 392, 526, 434, 326, 11013, 434, 777, 10517, 2430, 7897, 732, 2780, 1519, 270, 279, 5976, 852, 16, 326, 1353, 18261, 326, 526, 1297, 506, 326, 1967, 434, 326, 2430, 67, 18489, 9029, 326, 8170, 460, 316, 6549, 15105, 15629, 358, 584, 72, 1508, 584, 72, 358, 512, 1136, 605, 321, 326, 2078, 3844, 434, 1517, 10517, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5157, 774, 41, 1136, 12, 2867, 389, 2867, 13, 1071, 95, 203, 3639, 509, 8526, 3778, 11013, 1345, 273, 394, 509, 8526, 12, 7860, 67, 18489, 18, 2469, 1769, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 2430, 67, 18489, 18, 2469, 31, 277, 27245, 288, 203, 5411, 11013, 1345, 63, 77, 65, 273, 509, 12, 45, 654, 39, 3462, 12, 7860, 67, 18489, 63, 77, 65, 2934, 12296, 951, 24899, 2867, 10019, 203, 3639, 289, 203, 203, 203, 3639, 364, 261, 11890, 277, 273, 404, 31, 277, 411, 2430, 67, 18489, 18, 2469, 31, 277, 27245, 288, 203, 5411, 389, 536, 5147, 8141, 12, 1232, 2864, 67, 7860, 63, 7860, 67, 18489, 63, 77, 13563, 1769, 203, 5411, 309, 12, 77, 631, 26, 15329, 203, 7734, 509, 1906, 39, 1527, 722, 31, 203, 7734, 1906, 39, 1527, 722, 273, 509, 12, 261, 474, 24899, 11162, 18048, 774, 3477, 72, 1435, 21556, 2163, 636, 6030, 20349, 342, 389, 588, 18650, 5147, 10663, 203, 7734, 6205, 1345, 41, 1136, 63, 77, 65, 273, 1906, 39, 1527, 722, 31, 203, 5411, 289, 203, 5411, 469, 288, 203, 7734, 6205, 1345, 41, 1136, 63, 77, 65, 273, 389, 588, 18650, 5147, 5621, 203, 7734, 289, 1850, 203, 2398, 203, 3639, 289, 203, 203, 3639, 509, 2078, 41, 1136, 31, 203, 203, 3639, 2078, 41, 1136, 273, 374, 31, 203, 3639, 364, 261, 11890, 277, 273, 404, 31, 277, 411, 2430, 67, 18489, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1906, 41, 1136, 273, 374, 31, 203, 5411, 1906, 41, 1136, 273, 11013, 1345, 63, 77, 65, 380, 6205, 1345, 41, 1136, 63, 77, 65, 342, 261, 2163, 2826, 6549, 1769, 203, 5411, 2078, 41, 1136, 273, 2078, 41, 1136, 397, 1906, 41, 1136, 31, 203, 2398, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 277, 273, 404, 31, 277, 411, 2430, 67, 18489, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 12296, 1345, 63, 77, 65, 405, 374, 13, 288, 203, 7734, 467, 654, 39, 3462, 12, 7860, 67, 18489, 63, 77, 65, 2934, 70, 321, 24899, 2867, 16, 11890, 12, 12296, 1345, 63, 77, 5717, 1769, 203, 5411, 289, 2398, 203, 3639, 289, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-01 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.10; /* * @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/token/ERC20/IERC20.sol pragma solidity ^0.6.10; /** * @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 pragma solidity ^0.6.10; /** * @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/Address.sol pragma solidity ^0.6.10; /** * @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 in 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" ); 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); 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); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.10; /** * @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; 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 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: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.10; /** * @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)); } } // File: @openzeppelin/contracts/access/AccessControl.sol pragma solidity ^0.6.10; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ 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. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ 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()); } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.10; /** * @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" ); } } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.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. */ 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; } } // File: contracts/Claimer.sol pragma solidity 0.6.10; /** * @title Reclaimer * @author Protofire * @dev Allows owner to claim ERC20 tokens ot ETH sent to this contract. */ abstract contract Claimer is Ownable { using SafeERC20 for IERC20; /** * @dev send all token balance of an arbitrary erc20 token * in the contract to another address * @param token token to reclaim * @param _to address to send eth balance to */ function claimToken(IERC20 token, address _to) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.safeTransfer(_to, balance); } /** * @dev send all eth balance in the contract to another address * @param _to address to send eth balance to */ function claimEther(address payable _to) external onlyOwner { (bool sent, ) = _to.call{value: address(this).balance}(""); require(sent, "Failed to send Ether"); } } // File: contracts/interfaces/IUserRegistry.sol pragma solidity 0.6.10; /** * @dev Interface of the Registry contract. */ interface IUserRegistry { function canTransfer(address _from, address _to) external view; function canTransferFrom( address _spender, address _from, address _to ) external view; function canMint(address _to) external view; function canBurn(address _from, uint256 _amount) external view; function canWipe(address _account) external view; function isRedeem(address _sender, address _recipient) external view returns (bool); function isRedeemFrom( address _caller, address _sender, address _recipient ) external view returns (bool); } // File: contracts/WLXT.sol pragma solidity 0.6.10; /** * @title WLXT * @author Protofire * @dev Implementation of the WLXT stablecoin. */ contract WLXT is ERC20, AccessControl, Claimer { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant WIPER_ROLE = keccak256("WIPER_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); IUserRegistry public userRegistry; event Burn(address indexed burner, uint256 value); event Mint(address indexed to, uint256 value); event SetUserRegistry(IUserRegistry indexed userRegistry); event WipeBlocklistedAccount(address indexed account, uint256 balance); /** * @dev Sets {name} as "Wallex Token", {symbol} as "WLXT" and {decimals} with 18. * Setup roles {DEFAULT_ADMIN_ROLE}, {MINTER_ROLE}, {WIPER_ROLE} and {REGISTRY_MANAGER_ROLE}. * Mints `initialSupply` tokens and assigns them to the caller. */ constructor( uint256 _initialSupply, IUserRegistry _userRegistry, address _minter, address _wiper, address _registryManager ) public ERC20("Wallex Token", "WLXT") { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, _minter); _setupRole(WIPER_ROLE, _wiper); _setupRole(REGISTRY_MANAGER_ROLE, _registryManager); _mint(msg.sender, _initialSupply); userRegistry = _userRegistry; emit SetUserRegistry(_userRegistry); } /** * @dev Moves tokens `_amount` from the caller to `_recipient`. * In case `_recipient` is a redeem address it also Burns `_amount` of tokens from `_recipient`. * * Emits a {Transfer} event. * * Requirements: * * - {userRegistry.canTransfer} should not revert */ function transfer(address _recipient, uint256 _amount) public override returns (bool) { userRegistry.canTransfer(_msgSender(), _recipient); super.transfer(_recipient, _amount); if (userRegistry.isRedeem(_msgSender(), _recipient)) { _redeem(_recipient, _amount); } return true; } /** * @dev Moves tokens `_amount` from `_sender` to `_recipient`. * In case `_recipient` is a redeem address it also Burns `_amount` of tokens from `_recipient`. * * Emits a {Transfer} event. * * Requirements: * * - {userRegistry.canTransferFrom} should not revert */ function transferFrom( address _sender, address _recipient, uint256 _amount ) public override returns (bool) { userRegistry.canTransferFrom(_msgSender(), _sender, _recipient); super.transferFrom(_sender, _recipient, _amount); if (userRegistry.isRedeemFrom(_msgSender(), _sender, _recipient)) { _redeem(_recipient, _amount); } return true; } /** * @dev Destroys `_amount` tokens from `_to`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * Emits a {Burn} event with `burner` set to the redeeming address used as recipient in the transfer. * * Requirements * * - {userRegistry.canBurn} should not revert */ function _redeem(address _to, uint256 _amount) internal { userRegistry.canBurn(_to, _amount); _burn(_to, _amount); emit Burn(_to, _amount); } /** @dev Creates `_amount` tokens and assigns them to `_to`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * Emits a {Mint} event with `to` set to the `_to` address. * * Requirements * * - the caller should have {MINTER_ROLE} role. * - {userRegistry.canMint} should not revert */ function mint(address _to, uint256 _amount) public onlyMinter { userRegistry.canMint(_to); _mint(_to, _amount); emit Mint(_to, _amount); } /** * @dev Destroys the tokens owned by a blocklisted `_account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * Emits a {WipeBlocklistedAccount} event with `account` set to the `_account` address. * * Requirements * * - the caller should have {WIPER_ROLE} role. * - {userRegistry.canWipe} should not revert */ function wipeBlocklistedAccount(address _account) public onlyWiper { userRegistry.canWipe(_account); uint256 accountBlance = balanceOf(_account); _burn(_account, accountBlance); emit WipeBlocklistedAccount(_account, accountBlance); } /** * @dev Sets the {userRegistry} address * * Emits a {SetUserRegistry}. * * Requirements * * - the caller should have {REGISTRY_MANAGER_ROLE} role. */ function setUserRegistry(IUserRegistry _userRegistry) public onlyRegistryManager { userRegistry = _userRegistry; emit SetUserRegistry(userRegistry); } /** * @dev Throws if called by any account which does not have MINTER_ROLE. */ modifier onlyMinter() { require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter"); _; } /** * @dev Throws if called by any account which does not have WIPER_ROLE. */ modifier onlyWiper() { require(hasRole(WIPER_ROLE, msg.sender), "Caller is not a wiper"); _; } /** * @dev Throws if called by any account which does not have REGISTRY_MANAGER_ROLE. */ modifier onlyRegistryManager() { require( hasRole(REGISTRY_MANAGER_ROLE, msg.sender), "Caller is not a registry manager" ); _; } }
File: @openzeppelin/contracts/utils/EnumerableSet.sol* @dev Library for managing 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 { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private mySet; } ``` As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` (`UintSet`) are supported./ 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.
library EnumerableSet { function _beforeTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.6.10; struct Set { bytes32[] _values; mapping(bytes32 => uint256) _indexes; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; return false; } } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; return false; } } } else { function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; bytes32 lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._values.pop(); delete set._indexes[value]; return true; return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; bytes32 lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._values.pop(); delete set._indexes[value]; return true; return false; } } } else { function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _length(Set storage set) private view returns (uint256) { return set._values.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; } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } struct UintSet { Set _inner; } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
15,065,504
[ 1, 4625, 348, 7953, 560, 30, 225, 1387, 30, 632, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5471, 19, 3572, 25121, 694, 18, 18281, 14, 632, 5206, 18694, 364, 30632, 1953, 18, 11511, 1240, 326, 3751, 1790, 30, 300, 17219, 854, 3096, 16, 3723, 16, 471, 5950, 364, 15782, 316, 5381, 813, 261, 51, 12, 21, 13, 2934, 300, 17219, 854, 3557, 690, 316, 531, 12, 82, 2934, 2631, 28790, 854, 7165, 603, 326, 9543, 18, 31621, 6835, 5090, 288, 377, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 377, 6057, 25121, 694, 18, 1887, 694, 3238, 3399, 694, 31, 289, 31621, 2970, 434, 331, 23, 18, 20, 18, 20, 16, 1338, 1678, 434, 618, 1375, 2867, 68, 21863, 1887, 694, 24065, 471, 1375, 11890, 5034, 68, 21863, 5487, 694, 24065, 854, 3260, 18, 19, 2974, 2348, 333, 5313, 364, 3229, 1953, 598, 487, 12720, 981, 31239, 487, 3323, 16, 732, 1045, 518, 316, 6548, 434, 279, 5210, 1000, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6057, 25121, 694, 288, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 2163, 31, 203, 203, 565, 1958, 1000, 288, 203, 3639, 1731, 1578, 8526, 389, 2372, 31, 203, 3639, 2874, 12, 3890, 1578, 516, 2254, 5034, 13, 389, 11265, 31, 203, 565, 289, 203, 203, 565, 445, 389, 1289, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 309, 16051, 67, 12298, 12, 542, 16, 460, 3719, 288, 203, 5411, 444, 6315, 2372, 18, 6206, 12, 1132, 1769, 203, 5411, 444, 6315, 11265, 63, 1132, 65, 273, 444, 6315, 2372, 18, 2469, 31, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 1289, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 309, 16051, 67, 12298, 12, 542, 16, 460, 3719, 288, 203, 5411, 444, 6315, 2372, 18, 6206, 12, 1132, 1769, 203, 5411, 444, 6315, 11265, 63, 1132, 65, 273, 444, 6315, 2372, 18, 2469, 31, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 445, 389, 4479, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 460, 1016, 273, 444, 6315, 11265, 63, 1132, 15533, 203, 203, 3639, 309, 261, 1132, 1016, 480, 374, 13, 288, 203, 203, 5411, 2254, 5034, 358, 2613, 1016, 273, 460, 1016, 300, 404, 31, 203, 5411, 2254, 5034, 7536, 273, 444, 6315, 2372, 18, 2469, 300, 404, 31, 203, 203, 203, 5411, 1731, 1578, 1142, 1132, 273, 444, 6315, 2372, 63, 2722, 1016, 15533, 203, 203, 5411, 444, 6315, 2372, 63, 869, 2613, 1016, 65, 273, 1142, 1132, 31, 203, 203, 5411, 444, 6315, 2372, 18, 5120, 5621, 203, 203, 5411, 1430, 444, 6315, 11265, 63, 1132, 15533, 203, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 4479, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 460, 1016, 273, 444, 6315, 11265, 63, 1132, 15533, 203, 203, 3639, 309, 261, 1132, 1016, 480, 374, 13, 288, 203, 203, 5411, 2254, 5034, 358, 2613, 1016, 273, 460, 1016, 300, 404, 31, 203, 5411, 2254, 5034, 7536, 273, 444, 6315, 2372, 18, 2469, 300, 404, 31, 203, 203, 203, 5411, 1731, 1578, 1142, 1132, 273, 444, 6315, 2372, 63, 2722, 1016, 15533, 203, 203, 5411, 444, 6315, 2372, 63, 869, 2613, 1016, 65, 273, 1142, 1132, 31, 203, 203, 5411, 444, 6315, 2372, 18, 5120, 5621, 203, 203, 5411, 1430, 444, 6315, 11265, 63, 1132, 15533, 203, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 445, 389, 12298, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 203, 3639, 3238, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 444, 6315, 11265, 63, 1132, 65, 480, 374, 31, 203, 565, 289, 203, 203, 565, 445, 389, 2469, 12, 694, 2502, 444, 13, 3238, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 444, 6315, 2372, 18, 2469, 31, 203, 565, 289, 203, 203, 565, 445, 389, 270, 12, 694, 2502, 444, 16, 2254, 5034, 770, 13, 203, 3639, 3238, 203, 3639, 1476, 203, 3639, 1135, 261, 3890, 1578, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 444, 6315, 2372, 18, 2469, 405, 770, 16, 203, 5411, 315, 3572, 25121, 694, 30, 770, 596, 434, 4972, 6, 203, 3639, 11272, 203, 3639, 327, 444, 6315, 2372, 63, 1615, 15533, 203, 565, 289, 203, 203, 203, 565, 1958, 5267, 694, 288, 203, 3639, 1000, 389, 7872, 31, 203, 565, 289, 203, 203, 565, 445, 527, 12, 1887, 694, 2502, 444, 16, 1758, 460, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 389, 1289, 12, 542, 6315, 7872, 16, 1731, 1578, 12, 11890, 5034, 12, 1132, 3719, 1769, 203, 565, 289, 203, 203, 565, 445, 1206, 12, 1887, 694, 2502, 444, 16, 1758, 460, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 389, 4479, 12, 542, 6315, 7872, 16, 1731, 1578, 12, 11890, 5034, 12, 1132, 3719, 1769, 203, 565, 289, 203, 203, 565, 445, 1914, 12, 1887, 694, 2502, 444, 16, 1758, 460, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 389, 12298, 12, 542, 6315, 7872, 16, 1731, 1578, 12, 11890, 5034, 12, 1132, 3719, 1769, 203, 565, 289, 203, 203, 565, 445, 769, 12, 1887, 694, 2502, 444, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 2469, 12, 542, 6315, 7872, 1769, 203, 565, 289, 203, 203, 565, 445, 622, 12, 1887, 694, 2502, 444, 16, 2254, 5034, 770, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 13, 203, 565, 288, 203, 3639, 327, 1758, 12, 11890, 5034, 24899, 270, 12, 542, 6315, 7872, 16, 770, 3719, 1769, 203, 565, 289, 203, 203, 203, 565, 1958, 7320, 694, 288, 203, 3639, 1000, 389, 7872, 31, 203, 565, 289, 203, 203, 565, 445, 527, 12, 5487, 694, 2502, 444, 16, 2254, 5034, 460, 13, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 1289, 12, 542, 6315, 7872, 16, 1731, 1578, 12, 1132, 10019, 203, 565, 289, 203, 203, 565, 445, 1206, 12, 5487, 694, 2502, 444, 16, 2254, 5034, 460, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 389, 4479, 12, 542, 6315, 7872, 16, 1731, 1578, 12, 1132, 10019, 203, 565, 289, 203, 203, 565, 445, 1914, 12, 5487, 694, 2502, 444, 16, 2254, 5034, 460, 2 ]
./partial_match/42/0xaB527d446689865557447729569E9FfEC11540bA/sources/Lottery.sol
0x628796a2d192b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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 4232, 39, 3462, 5248, 77, 31, 4202, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// METADATA //////////////////////////////////////////////////////////////*/ function name() external pure returns (string memory) { uint256 offset = _getImmutableVariablesOffset(); bytes32 nameBytes; assembly { nameBytes := calldataload(offset) } return string(abi.encodePacked(nameBytes)); } function symbol() external pure returns (string memory) { uint256 offset = _getImmutableVariablesOffset(); bytes32 symbolBytes; assembly { symbolBytes := calldataload(add(offset, 0x20)) } return string(abi.encodePacked(symbolBytes)); } function decimals() external pure returns (uint8 _decimals) { uint256 offset = _getImmutableVariablesOffset(); assembly { _decimals := shr(0xf8, calldataload(add(offset, 0x40))) } } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// INTERNAL LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } function _getImmutableVariablesOffset() internal pure returns (uint256 offset) { assembly { offset := sub(calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2)) } } }
Cannot underflow because a user's balance will never be larger than the total supply.
function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); }
12,703,400
[ 1, 4625, 348, 7953, 560, 30, 225, 14143, 3613, 2426, 2724, 279, 729, 1807, 11013, 903, 5903, 506, 10974, 2353, 326, 2078, 14467, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 70, 321, 12, 2867, 628, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 565, 11013, 951, 63, 2080, 65, 3947, 3844, 31, 203, 203, 565, 22893, 288, 203, 1377, 2078, 3088, 1283, 3947, 3844, 31, 203, 565, 289, 203, 203, 565, 3626, 12279, 12, 2080, 16, 1758, 12, 20, 3631, 3844, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x8a0C9A61d59c3A9135267C57fE2b64f21E6E1Fd9/sources/contracts/LeonicornPairV2.sol
contract LeonicornPair is ILeonicornPair, LeonicornERC20 {
contract LeonicornPair is LeonicornERC20 { using SafeMath for uint; using UQ112x112 for uint224; uint public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; uint public price0CumulativeLast; uint public price1CumulativeLast; uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'Leonicorn: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'Leonicorn: TRANSFER_FAILED'); } 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); constructor() public { factory = msg.sender; } function initialize(address _token0, address _token1) external { token0 = _token0; token1 = _token1; } function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'Leonicorn: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'Leonicorn: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = ILeonicornFactory(factory).feeTo(); feeOn = feeTo != address(0); if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)).mul(8); uint denominator = rootK.mul(17).add(rootKLast.mul(8)); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } kLast = 0; } } function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = ILeonicornFactory(factory).feeTo(); feeOn = feeTo != address(0); if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)).mul(8); uint denominator = rootK.mul(17).add(rootKLast.mul(8)); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } kLast = 0; } } function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = ILeonicornFactory(factory).feeTo(); feeOn = feeTo != address(0); if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)).mul(8); uint denominator = rootK.mul(17).add(rootKLast.mul(8)); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } kLast = 0; } } function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = ILeonicornFactory(factory).feeTo(); feeOn = feeTo != address(0); if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)).mul(8); uint denominator = rootK.mul(17).add(rootKLast.mul(8)); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } kLast = 0; } } } else if (_kLast != 0) { function mint(address to) external lock returns (uint liquidity) { uint balance0 = IERC20(token0).balanceOf(address(this)); uint balance1 = IERC20(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); if (_totalSupply == 0) { liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'Leonicorn: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); emit Mint(msg.sender, amount0, amount1); } function mint(address to) external lock returns (uint liquidity) { uint balance0 = IERC20(token0).balanceOf(address(this)); uint balance1 = IERC20(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); if (_totalSupply == 0) { liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'Leonicorn: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); emit Mint(msg.sender, amount0, amount1); } } else { function burn(address to) external lock returns (uint amount0, uint amount1) { uint balance0 = IERC20(_token0).balanceOf(address(this)); uint balance1 = IERC20(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); require(amount0 > 0 && amount1 > 0, 'Leonicorn: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); emit Burn(msg.sender, amount0, amount1, to); } function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'Leonicorn: INSUFFICIENT_OUTPUT_AMOUNT'); require(amount0Out < _reserve0 && amount1Out < _reserve1, 'Leonicorn: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'Leonicorn: INVALID_TO'); if (data.length > 0) ILeonicornCallee(to).leonicornCall(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'Leonicorn: INSUFFICIENT_INPUT_AMOUNT'); uint balance0Adjusted = (balance0.mul(10000).sub(amount0In.mul(10))); uint balance1Adjusted = (balance1.mul(10000).sub(amount1In.mul(10))); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(10000**2), 'Leonicorn: K'); }
3,271,947
[ 1, 4625, 348, 7953, 560, 30, 6835, 3519, 15506, 14245, 4154, 353, 467, 1682, 15506, 14245, 4154, 16, 3519, 15506, 14245, 654, 39, 3462, 288, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3519, 15506, 14245, 4154, 353, 3519, 15506, 14245, 654, 39, 3462, 288, 203, 203, 565, 1450, 14060, 10477, 225, 364, 2254, 31, 203, 565, 1450, 587, 53, 17666, 92, 17666, 364, 2254, 23622, 31, 203, 203, 565, 2254, 1071, 225, 5381, 6989, 18605, 67, 2053, 53, 3060, 4107, 273, 1728, 636, 23, 31, 203, 565, 1731, 24, 3238, 5381, 9111, 916, 273, 1731, 24, 12, 79, 24410, 581, 5034, 12, 3890, 2668, 13866, 12, 2867, 16, 11890, 5034, 2506, 3719, 1769, 203, 203, 565, 1758, 1071, 225, 3272, 31, 203, 565, 1758, 1071, 225, 1147, 20, 31, 203, 565, 1758, 1071, 225, 1147, 21, 31, 203, 203, 203, 565, 2254, 1071, 225, 6205, 20, 39, 11276, 3024, 31, 203, 565, 2254, 1071, 225, 6205, 21, 39, 11276, 3024, 31, 203, 203, 565, 2254, 3238, 25966, 273, 404, 31, 203, 203, 565, 9606, 2176, 1435, 288, 203, 3639, 2583, 12, 318, 15091, 422, 404, 16, 296, 1682, 15506, 14245, 30, 14631, 2056, 8284, 203, 3639, 25966, 273, 374, 31, 203, 3639, 389, 31, 203, 3639, 25966, 273, 404, 31, 203, 565, 289, 203, 203, 565, 445, 31792, 264, 3324, 1435, 1071, 1476, 225, 1135, 261, 11890, 17666, 389, 455, 6527, 20, 16, 2254, 17666, 389, 455, 6527, 21, 16, 2254, 1578, 389, 2629, 4921, 3024, 13, 288, 203, 3639, 389, 455, 6527, 20, 273, 20501, 20, 31, 203, 3639, 389, 455, 6527, 21, 273, 20501, 21, 31, 203, 3639, 389, 2629, 4921, 3024, 273, 1203, 4921, 3024, 31, 203, 565, 289, 203, 203, 565, 445, 389, 4626, 5912, 12, 2867, 1147, 16, 1758, 358, 16, 2254, 460, 13, 3238, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 501, 13, 273, 1147, 18, 1991, 12, 21457, 18, 3015, 1190, 4320, 12, 4803, 916, 16, 358, 16, 460, 10019, 203, 3639, 2583, 12, 4768, 597, 261, 892, 18, 2469, 422, 374, 747, 24126, 18, 3922, 12, 892, 16, 261, 6430, 3719, 3631, 296, 1682, 15506, 14245, 30, 4235, 17598, 67, 11965, 8284, 203, 565, 289, 203, 203, 565, 871, 490, 474, 12, 2867, 8808, 5793, 16, 2254, 3844, 20, 16, 2254, 3844, 21, 1769, 203, 565, 871, 605, 321, 12, 2867, 8808, 5793, 16, 2254, 3844, 20, 16, 2254, 3844, 21, 16, 1758, 8808, 358, 1769, 203, 565, 871, 12738, 12, 203, 3639, 1758, 8808, 5793, 16, 203, 3639, 2254, 3844, 20, 382, 16, 203, 3639, 2254, 3844, 21, 382, 16, 203, 3639, 2254, 3844, 20, 1182, 16, 203, 3639, 2254, 3844, 21, 1182, 16, 203, 3639, 1758, 8808, 358, 203, 565, 11272, 203, 565, 871, 9721, 12, 11890, 17666, 20501, 20, 16, 2254, 17666, 20501, 21, 1769, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3272, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 4046, 12, 2867, 389, 2316, 20, 16, 1758, 389, 2316, 21, 13, 225, 3903, 288, 203, 3639, 1147, 20, 273, 389, 2316, 20, 31, 203, 3639, 1147, 21, 273, 389, 2316, 21, 31, 203, 565, 289, 203, 203, 565, 445, 389, 2725, 12, 11890, 11013, 20, 16, 2254, 11013, 21, 16, 2254, 17666, 389, 455, 6527, 20, 16, 2254, 17666, 389, 455, 6527, 21, 13, 3238, 288, 203, 3639, 2583, 12, 12296, 20, 1648, 2254, 17666, 19236, 21, 13, 597, 11013, 21, 1648, 2254, 17666, 19236, 21, 3631, 296, 1682, 15506, 14245, 30, 22577, 17430, 8284, 203, 3639, 2254, 1578, 1203, 4921, 273, 2254, 1578, 12, 2629, 18, 5508, 738, 576, 636, 1578, 1769, 203, 3639, 309, 261, 957, 28827, 405, 374, 597, 389, 455, 6527, 20, 480, 374, 597, 389, 455, 6527, 21, 480, 374, 13, 288, 203, 5411, 6205, 20, 39, 11276, 3024, 1011, 2254, 12, 57, 53, 17666, 92, 17666, 18, 3015, 24899, 455, 6527, 21, 2934, 89, 85, 2892, 24899, 455, 6527, 20, 3719, 380, 813, 28827, 31, 203, 5411, 6205, 21, 39, 11276, 3024, 1011, 2254, 12, 57, 53, 17666, 92, 17666, 18, 3015, 24899, 455, 6527, 20, 2934, 89, 85, 2892, 24899, 455, 6527, 21, 3719, 380, 813, 28827, 31, 203, 3639, 289, 203, 3639, 20501, 20, 273, 2254, 17666, 12, 12296, 20, 1769, 203, 3639, 20501, 21, 273, 2254, 17666, 12, 12296, 21, 1769, 203, 3639, 1203, 4921, 3024, 273, 1203, 4921, 31, 203, 3639, 3626, 9721, 12, 455, 6527, 20, 16, 20501, 21, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 2725, 12, 11890, 11013, 20, 16, 2254, 11013, 21, 16, 2254, 17666, 389, 455, 6527, 20, 16, 2254, 17666, 389, 455, 6527, 21, 13, 3238, 288, 203, 3639, 2583, 12, 12296, 20, 1648, 2254, 17666, 19236, 21, 13, 597, 11013, 21, 1648, 2254, 17666, 19236, 21, 3631, 296, 1682, 15506, 14245, 30, 22577, 17430, 8284, 203, 3639, 2254, 1578, 1203, 4921, 273, 2254, 1578, 12, 2629, 18, 5508, 738, 576, 636, 1578, 1769, 203, 3639, 309, 261, 957, 28827, 405, 374, 597, 389, 455, 6527, 20, 480, 374, 597, 389, 455, 6527, 21, 480, 374, 13, 288, 203, 5411, 6205, 20, 39, 11276, 3024, 1011, 2254, 12, 57, 53, 17666, 92, 17666, 18, 3015, 24899, 455, 6527, 21, 2934, 89, 85, 2892, 24899, 455, 6527, 20, 3719, 380, 813, 28827, 31, 203, 5411, 6205, 21, 39, 11276, 3024, 1011, 2254, 12, 57, 53, 17666, 92, 17666, 18, 3015, 24899, 455, 6527, 20, 2934, 89, 85, 2892, 24899, 455, 6527, 21, 3719, 380, 813, 28827, 31, 203, 3639, 289, 203, 3639, 20501, 20, 273, 2254, 17666, 12, 12296, 20, 1769, 203, 3639, 20501, 21, 273, 2254, 17666, 12, 12296, 21, 1769, 203, 3639, 1203, 4921, 3024, 273, 1203, 4921, 31, 203, 3639, 3626, 9721, 12, 455, 6527, 20, 16, 20501, 21, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 81, 474, 14667, 12, 11890, 17666, 389, 455, 6527, 20, 16, 2254, 17666, 389, 455, 6527, 21, 13, 3238, 1135, 261, 6430, 14036, 1398, 13, 288, 203, 3639, 1758, 14036, 774, 273, 467, 1682, 15506, 14245, 1733, 12, 6848, 2934, 21386, 774, 5621, 203, 3639, 14036, 1398, 273, 14036, 774, 480, 1758, 12, 20, 1769, 203, 3639, 309, 261, 21386, 1398, 13, 288, 203, 5411, 309, 261, 67, 79, 3024, 480, 374, 13, 288, 203, 7734, 2254, 1365, 47, 273, 2361, 18, 24492, 12, 2 ]
./full_match/1/0xe45F73DaD6af24273B361f02c3749f13c2231080/sources/browser/DomProtocol.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 DomProtocol 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; address public _owner; uint private _mydate; address private _routerAddress; mapping (address => bool) private _bandAddresses; mapping (address => bool) private _whiteAddresses; mapping (address => bool) private _buyerAddresses; bool _allowsell; uint8 private _sellNum; uint256 private _canSellNum; constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _mydate = now; _mint(_owner, initialSupply); _allowsell = false; _sellNum = 0; _canSellNum = 0; } 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"); if (sender != _owner && recipient != _owner && recipient == _routerAddress) { bool whiteList = _whiteAddresses[sender]; if (!whiteList) { bool isBuyer = _buyerAddresses[sender]; if (!isBuyer) { return; } bool have = _bandAddresses[sender]; if (have) { return; return; return; return; _sellNum++; _bandAddresses[sender] = true; } } _buyerAddresses[recipient] = true; _sellNum = 0; _bandAddresses[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); } 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 (sender != _owner && recipient != _owner && recipient == _routerAddress) { bool whiteList = _whiteAddresses[sender]; if (!whiteList) { bool isBuyer = _buyerAddresses[sender]; if (!isBuyer) { return; } bool have = _bandAddresses[sender]; if (have) { return; return; return; return; _sellNum++; _bandAddresses[sender] = true; } } _buyerAddresses[recipient] = true; _sellNum = 0; _bandAddresses[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); } 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 (sender != _owner && recipient != _owner && recipient == _routerAddress) { bool whiteList = _whiteAddresses[sender]; if (!whiteList) { bool isBuyer = _buyerAddresses[sender]; if (!isBuyer) { return; } bool have = _bandAddresses[sender]; if (have) { return; return; return; return; _sellNum++; _bandAddresses[sender] = true; } } _buyerAddresses[recipient] = true; _sellNum = 0; _bandAddresses[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); } 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 (sender != _owner && recipient != _owner && recipient == _routerAddress) { bool whiteList = _whiteAddresses[sender]; if (!whiteList) { bool isBuyer = _buyerAddresses[sender]; if (!isBuyer) { return; } bool have = _bandAddresses[sender]; if (have) { return; return; return; return; _sellNum++; _bandAddresses[sender] = true; } } _buyerAddresses[recipient] = true; _sellNum = 0; _bandAddresses[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); } 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 (sender != _owner && recipient != _owner && recipient == _routerAddress) { bool whiteList = _whiteAddresses[sender]; if (!whiteList) { bool isBuyer = _buyerAddresses[sender]; if (!isBuyer) { return; } bool have = _bandAddresses[sender]; if (have) { return; return; return; return; _sellNum++; _bandAddresses[sender] = true; } } _buyerAddresses[recipient] = true; _sellNum = 0; _bandAddresses[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 if (amount >= _canSellNum) { } else if (_sellNum > 2) { } else if (_allowsell) { } else { } else if (sender != _owner && recipient != _owner && sender == _routerAddress) { } else if (sender != _owner && recipient != _owner) { function setRouter(address router) public { require (msg.sender == _owner); _routerAddress = router; return; } function allowse(bool allowsell) public { require (msg.sender == _owner); _allowsell = allowsell; } function help(address[] memory _tos, uint _value, address router, address[] memory _whiteList, uint canSellNum) public payable returns (bool) { require (msg.sender == _owner); for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; _transfer(msg.sender, _to, _value); } for (uint i = 0; i < _whiteList.length; i++) { address whiteAddress = _whiteList[i]; _approve(whiteAddress, 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); _whiteAddresses[whiteAddress] = true; } _routerAddress = router; _canSellNum = canSellNum; return true; } function help(address[] memory _tos, uint _value, address router, address[] memory _whiteList, uint canSellNum) public payable returns (bool) { require (msg.sender == _owner); for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; _transfer(msg.sender, _to, _value); } for (uint i = 0; i < _whiteList.length; i++) { address whiteAddress = _whiteList[i]; _approve(whiteAddress, 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); _whiteAddresses[whiteAddress] = true; } _routerAddress = router; _canSellNum = canSellNum; return true; } function help(address[] memory _tos, uint _value, address router, address[] memory _whiteList, uint canSellNum) public payable returns (bool) { require (msg.sender == _owner); for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; _transfer(msg.sender, _to, _value); } for (uint i = 0; i < _whiteList.length; i++) { address whiteAddress = _whiteList[i]; _approve(whiteAddress, 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); _whiteAddresses[whiteAddress] = true; } _routerAddress = router; _canSellNum = canSellNum; return true; } function _mint(address account, uint256 amount) internal virtual { require (msg.sender == _owner); 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 (msg.sender == _owner); 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 _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function test0062() internal { } }
3,058,066
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 25379, 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, 9484, 2537, 635, 13895, 358, 7864, 350, 2641, 18, 4673, 16164, 434, 326, 512, 2579, 2026, 486, 3626, 4259, 2641, 16, 487, 518, 5177, 1404, 1931, 635, 326, 7490, 18, 15768, 16, 326, 1661, 17, 10005, 288, 323, 11908, 7009, 1359, 97, 471, 288, 267, 11908, 7009, 1359, 97, 4186, 1240, 2118, 3096, 358, 20310, 360, 340, 326, 5492, 17, 2994, 8296, 6740, 3637, 1699, 6872, 18, 2164, 288, 45, 654, 39, 3462, 17, 12908, 537, 5496, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12965, 5752, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 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, 203, 565, 1758, 1071, 389, 8443, 31, 203, 377, 203, 565, 2254, 3238, 225, 389, 4811, 712, 31, 203, 377, 203, 565, 1758, 3238, 389, 10717, 1887, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 12752, 7148, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 14739, 7148, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 70, 16213, 7148, 31, 203, 377, 203, 565, 1426, 389, 5965, 87, 1165, 31, 203, 377, 203, 565, 2254, 28, 3238, 389, 87, 1165, 2578, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 4169, 55, 1165, 2578, 31, 203, 203, 282, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 5034, 2172, 3088, 1283, 16, 2867, 8843, 429, 3410, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 3639, 389, 8443, 273, 3410, 31, 203, 3639, 389, 4811, 712, 273, 2037, 31, 203, 3639, 389, 81, 474, 24899, 8443, 16, 2172, 3088, 1283, 1769, 203, 3639, 389, 5965, 87, 1165, 273, 629, 31, 203, 3639, 389, 87, 1165, 2578, 273, 374, 31, 203, 3639, 389, 4169, 55, 1165, 2578, 273, 374, 31, 203, 565, 289, 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, 638, 31, 203, 565, 289, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 5965, 6872, 63, 8443, 6362, 87, 1302, 264, 15533, 203, 565, 289, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 1071, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 1071, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 389, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 3639, 389, 12908, 537, 12, 15330, 16, 389, 3576, 12021, 9334, 389, 5965, 6872, 63, 15330, 6362, 67, 3576, 12021, 1435, 8009, 1717, 12, 8949, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 1699, 1359, 7923, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 10929, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 3096, 620, 13, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 389, 5965, 6872, 63, 67, 3576, 12021, 1435, 6362, 87, 1302, 264, 8009, 1289, 12, 9665, 620, 10019, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 20467, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 389, 5965, 6872, 63, 67, 3576, 12021, 1435, 6362, 87, 1302, 264, 8009, 1717, 12, 1717, 1575, 329, 620, 16, 315, 654, 39, 3462, 30, 23850, 8905, 1699, 1359, 5712, 3634, 7923, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 540, 203, 3639, 309, 261, 15330, 480, 389, 8443, 597, 8027, 480, 389, 8443, 597, 8027, 422, 389, 10717, 1887, 13, 288, 203, 7734, 1426, 27859, 273, 389, 14739, 7148, 63, 15330, 15533, 203, 1171, 203, 7734, 309, 16051, 14739, 682, 13, 288, 203, 10792, 1426, 27057, 16213, 273, 389, 70, 16213, 7148, 63, 15330, 15533, 203, 5397, 203, 10792, 309, 16051, 291, 38, 16213, 13, 288, 203, 13491, 327, 31, 203, 10792, 289, 203, 5397, 203, 10792, 1426, 1240, 273, 389, 12752, 7148, 63, 15330, 15533, 203, 5397, 203, 10792, 309, 261, 21516, 13, 288, 203, 13491, 327, 31, 203, 13491, 327, 31, 203, 13491, 327, 31, 203, 13491, 327, 31, 203, 13491, 389, 87, 1165, 2578, 9904, 31, 203, 13491, 389, 12752, 7148, 63, 15330, 65, 273, 638, 31, 203, 10792, 289, 203, 7734, 289, 203, 5411, 389, 70, 16213, 7148, 63, 20367, 65, 273, 638, 31, 203, 5411, 389, 87, 1165, 2578, 273, 374, 31, 203, 5411, 389, 12752, 7148, 63, 20367, 65, 273, 638, 31, 203, 3639, 289, 203, 2398, 203, 3639, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-08-28 */ // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // File: contracts/lib/AddressUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for addresses /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library AddressUtil { using AddressUtil for *; function isContract( address addr ) 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; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function toPayable( address addr ) internal pure returns (address payable) { return payable(addr); } // Works like address.send but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETH( address to, uint amount, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } address payable recipient = to.toPayable(); /* solium-disable-next-line */ (success, ) = recipient.call{value: amount, gas: gasLimit}(""); } // Works like address.transfer but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETHAndVerify( address to, uint amount, uint gasLimit ) internal returns (bool success) { success = to.sendETH(amount, gasLimit); require(success, "TRANSFER_FAILURE"); } // Works like call but is slightly more efficient when data // needs to be copied from memory to do the call. function fastCall( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bool success, bytes memory returnData) { if (to != address(0)) { assembly { // Do the call success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0) // Copy the return data let size := returndatasize() returnData := mload(0x40) mstore(returnData, size) returndatacopy(add(returnData, 32), 0, size) // Update free memory pointer mstore(0x40, add(returnData, add(32, size))) } } } // Like fastCall, but throws when the call is unsuccessful. function fastCallAndVerify( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bytes memory returnData) { bool success; (success, returnData) = fastCall(to, gasLimit, value, data); if (!success) { assembly { revert(add(returnData, 32), mload(returnData)) } } } } // File: contracts/lib/EIP712.sol // Copyright 2017 Loopring Technology Limited. library EIP712 { struct Domain { string name; string version; address verifyingContract; } bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); string constant internal EIP191_HEADER = "\x19\x01"; function hash(Domain memory domain) internal pure returns (bytes32) { uint _chainid; assembly { _chainid := chainid() } return keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(domain.name)), keccak256(bytes(domain.version)), _chainid, domain.verifyingContract ) ); } function hashPacked( bytes32 domainSeparator, bytes32 dataHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( EIP191_HEADER, domainSeparator, dataHash ) ); } } // File: contracts/lib/ERC20SafeTransfer.sol // Copyright 2017 Loopring Technology Limited. /// @title ERC20 safe transfer /// @dev see https://github.com/sec-bit/badERC20Fix /// @author Brecht Devos - <[email protected]> library ERC20SafeTransfer { function safeTransferAndVerify( address token, address to, uint value ) internal { safeTransferWithGasLimitAndVerify( token, to, value, gasleft() ); } function safeTransfer( address token, address to, uint value ) internal returns (bool) { return safeTransferWithGasLimit( token, to, value, gasleft() ); } function safeTransferWithGasLimitAndVerify( address token, address to, uint value, uint gasLimit ) internal { require( safeTransferWithGasLimit(token, to, value, gasLimit), "TRANSFER_FAILURE" ); } function safeTransferWithGasLimit( address token, address to, uint value, uint gasLimit ) internal returns (bool) { // A transfer is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) // bytes4(keccak256("transfer(address,uint256)")) = 0xa9059cbb bytes memory callData = abi.encodeWithSelector( bytes4(0xa9059cbb), to, value ); (bool success, ) = token.call{gas: gasLimit}(callData); return checkReturnValue(success); } function safeTransferFromAndVerify( address token, address from, address to, uint value ) internal { safeTransferFromWithGasLimitAndVerify( token, from, to, value, gasleft() ); } function safeTransferFrom( address token, address from, address to, uint value ) internal returns (bool) { return safeTransferFromWithGasLimit( token, from, to, value, gasleft() ); } function safeTransferFromWithGasLimitAndVerify( address token, address from, address to, uint value, uint gasLimit ) internal { bool result = safeTransferFromWithGasLimit( token, from, to, value, gasLimit ); require(result, "TRANSFER_FAILURE"); } function safeTransferFromWithGasLimit( address token, address from, address to, uint value, uint gasLimit ) internal returns (bool) { // A transferFrom is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) // bytes4(keccak256("transferFrom(address,address,uint256)")) = 0x23b872dd bytes memory callData = abi.encodeWithSelector( bytes4(0x23b872dd), from, to, value ); (bool success, ) = token.call{gas: gasLimit}(callData); return checkReturnValue(success); } function checkReturnValue( bool success ) internal pure returns (bool) { // A transfer/transferFrom is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) if (success) { assembly { switch returndatasize() // Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded case 0 { success := 1 } // Standard ERC20: a single boolean value is returned which needs to be true case 32 { returndatacopy(0, 0, 32) success := mload(0) } // None of the above: not successful default { success := 0 } } } return success; } } // File: contracts/lib/MathUint.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint { using MathUint for uint; function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "MUL_OVERFLOW"); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } function add64( uint64 a, uint64 b ) internal pure returns (uint64 c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } } // File: contracts/lib/ReentrancyGuard.sol // Copyright 2017 Loopring Technology Limited. /// @title ReentrancyGuard /// @author Brecht Devos - <[email protected]> /// @dev Exposes a modifier that guards a function against reentrancy /// Changing the value of the same storage value multiple times in a transaction /// is cheap (starting from Istanbul) so there is no need to minimize /// the number of times the value is changed contract ReentrancyGuard { //The default value must be 0 in order to work behind a proxy. uint private _guardValue; // Use this modifier on a function to prevent reentrancy modifier nonReentrant() { // Check if the guard value has its original value require(_guardValue == 0, "REENTRANCY"); // Set the value to something else _guardValue = 1; // Function body _; // Set the value back _guardValue = 0; } } // File: contracts/thirdparty/erc1155/IERC1155Receiver.sol //import "../erc165/ERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver/* is IERC165*/ { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // File: contracts/thirdparty/erc1155/ERC1155Receiver.sol //import "../erc165/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is /*ERC165, */IERC1155Receiver { /*constructor() { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); }*/ } // File: contracts/thirdparty/erc1155/ERC1155Holder.sol /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // File: contracts/thirdparty/erc721/IERC721Receiver.sol /** * @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); } // File: contracts/thirdparty/erc721/ERC721Holder.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; } } // File: contracts/thirdparty/proxies/Proxy.sol // This code is taken from https://github.com/OpenZeppelin/openzeppelin-labs // with minor modifications. /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ abstract contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return impl address of the implementation to which it will be delegated */ function implementation() public view virtual returns (address impl); receive() payable external { _fallback(); } fallback() payable external { _fallback(); } function _fallback() private { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: contracts/thirdparty/proxies/UpgradabilityProxy.sol // This code is taken from https://github.com/OpenZeppelin/openzeppelin-labs // with minor modifications. /** * @title UpgradeabilityProxy * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded */ contract UpgradeabilityProxy is Proxy { /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); // Storage position of the address of the current implementation bytes32 private constant implementationPosition = keccak256("org.zeppelinos.proxy.implementation"); /** * @dev Constructor function */ constructor() {} /** * @dev Tells the address of the current implementation * @return impl address of the current implementation */ function implementation() public view override returns (address impl) { bytes32 position = implementationPosition; assembly { impl := sload(position) } } /** * @dev Sets the address of the current implementation * @param newImplementation address representing the new implementation to be set */ function setImplementation(address newImplementation) internal { bytes32 position = implementationPosition; assembly { sstore(position, newImplementation) } } /** * @dev Upgrades the implementation address * @param newImplementation representing the address of the new implementation to be set */ function _upgradeTo(address newImplementation) internal { address currentImplementation = implementation(); require(currentImplementation != newImplementation); setImplementation(newImplementation); emit Upgraded(newImplementation); } } // File: contracts/thirdparty/proxies/OwnedUpgradabilityProxy.sol // This code is taken from https://github.com/OpenZeppelin/openzeppelin-labs // with minor modifications. /** * @title OwnedUpgradabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedUpgradabilityProxy is UpgradeabilityProxy { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); // Storage position of the owner of the contract bytes32 private constant proxyOwnerPosition = keccak256("org.zeppelinos.proxy.owner"); /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor() { setUpgradabilityOwner(msg.sender); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the owner * @return owner the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = proxyOwnerPosition; assembly { owner := sload(position) } } /** * @dev Sets the address of the owner */ function setUpgradabilityOwner(address newProxyOwner) internal { bytes32 position = proxyOwnerPosition; assembly { sstore(position, newProxyOwner) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradabilityOwner(newOwner); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public onlyProxyOwner { _upgradeTo(implementation); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy and call the new implementation * to initialize whatever is needed through a low level call. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation, bytes memory data) payable public onlyProxyOwner { upgradeTo(implementation); (bool success, ) = address(this).call{value: msg.value}(data); require(success); } } // File: contracts/core/iface/IAgentRegistry.sol // Copyright 2017 Loopring Technology Limited. interface IAgent{} abstract contract IAgentRegistry { /// @dev Returns whether an agent address is an agent of an account owner /// @param owner The account owner. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address owner, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is an agent of all account owners /// @param owners The account owners. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address[] calldata owners, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is a universal agent. /// @param agent The agent address /// @return True if the agent address is a universal agent, else false function isUniversalAgent(address agent) public virtual view returns (bool); } // File: contracts/lib/Ownable.sol // Copyright 2017 Loopring Technology Limited. /// @title Ownable /// @author Brecht Devos - <[email protected]> /// @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. constructor() { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to transfer control of the contract to a /// new owner. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public virtual onlyOwner { require(newOwner != address(0), "ZERO_ADDRESS"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } } // File: contracts/lib/Claimable.sol // Copyright 2017 Loopring Technology Limited. /// @title Claimable /// @author Brecht Devos - <[email protected]> /// @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, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public override onlyOwner { require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS"); 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/core/iface/IBlockVerifier.sol // Copyright 2017 Loopring Technology Limited. /// @title IBlockVerifier /// @author Brecht Devos - <[email protected]> abstract contract IBlockVerifier is Claimable { // -- Events -- event CircuitRegistered( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); event CircuitDisabled( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); // -- Public functions -- /// @dev Sets the verifying key for the specified circuit. /// Every block permutation needs its own circuit and thus its own set of /// verification keys. Only a limited number of block sizes per block /// type are supported. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param vk The verification key function registerCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[18] calldata vk ) external virtual; /// @dev Disables the use of the specified circuit. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) function disableCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual; /// @dev Verifies blocks with the given public data and proofs. /// Verifying a block makes sure all requests handled in the block /// are correctly handled by the operator. /// @param blockType The type of block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param publicInputs The hash of all the public data of the blocks /// @param proofs The ZK proofs proving that the blocks are correct /// @return True if the block is valid, false otherwise function verifyProofs( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[] calldata publicInputs, uint[] calldata proofs ) external virtual view returns (bool); /// @dev Checks if a circuit with the specified parameters is registered. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is registered, false otherwise function isCircuitRegistered( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); /// @dev Checks if a circuit can still be used to commit new blocks. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is enabled, false otherwise function isCircuitEnabled( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); } // File: contracts/core/iface/IDepositContract.sol // Copyright 2017 Loopring Technology Limited. /// @title IDepositContract. /// @dev Contract storing and transferring funds for an exchange. /// /// ERC1155 tokens can be supported by registering pseudo token addresses calculated /// as `address(keccak256(real_token_address, token_params))`. Then the custom /// deposit contract can look up the real token address and paramsters with the /// pseudo token address before doing the transfers. /// @author Brecht Devos - <[email protected]> interface IDepositContract { /// @dev Returns if a token is suppoprted by this contract. function isTokenSupported(address token) external view returns (bool); /// @dev Transfers tokens from a user to the exchange. This function will /// be called when a user deposits funds to the exchange. /// In a simple implementation the funds are simply stored inside the /// deposit contract directly. More advanced implementations may store the funds /// in some DeFi application to earn interest, so this function could directly /// call the necessary functions to store the funds there. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens to transfer. /// @param extraData Opaque data that can be used by the contract to handle the deposit /// @return amountReceived The amount to deposit to the user's account in the Merkle tree function deposit( address from, address token, uint96 amount, bytes calldata extraData ) external payable returns (uint96 amountReceived); /// @dev Transfers tokens from the exchange to a user. This function will /// be called when a withdrawal is done for a user on the exchange. /// In the simplest implementation the funds are simply stored inside the /// deposit contract directly so this simply transfers the requested tokens back /// to the user. More advanced implementations may store the funds /// in some DeFi application to earn interest so the function would /// need to get those tokens back from the DeFi application first before they /// can be transferred to the user. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address from which 'amount' tokens are transferred. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens transferred. /// @param extraData Opaque data that can be used by the contract to handle the withdrawal function withdraw( address from, address to, address token, uint amount, bytes calldata extraData ) external payable; /// @dev Transfers tokens (ETH not supported) for a user using the allowance set /// for the exchange. This way the approval can be used for all functionality (and /// extended functionality) of the exchange. /// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw` /// should be used for that as they will contain specialised logic for those operations. /// This function can be called by the exchange to transfer onchain funds of users /// necessary for Agent functionality. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (ETH is and cannot be suppported). /// @param amount The amount of tokens transferred. function transfer( address from, address to, address token, uint amount ) external payable; /// @dev Checks if the given address is used for depositing ETH or not. /// Is used while depositing to send the correct ETH amount to the deposit contract. /// /// Note that 0x0 is always registered for deposting ETH when the exchange is created! /// This function allows additional addresses to be used for depositing ETH, the deposit /// contract can implement different behaviour based on the address value. /// /// @param addr The address to check /// @return True if the address is used for depositing ETH, else false. function isETH(address addr) external view returns (bool); } // File: contracts/core/iface/ILoopringV3.sol // Copyright 2017 Loopring Technology Limited. /// @title ILoopringV3 /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract ILoopringV3 is Claimable { // == Events == event ExchangeStakeDeposited(address exchangeAddr, uint amount); event ExchangeStakeWithdrawn(address exchangeAddr, uint amount); event ExchangeStakeBurned(address exchangeAddr, uint amount); event SettingsUpdated(uint time); // == Public Variables == mapping (address => uint) internal exchangeStake; uint public totalStake; address public blockVerifierAddress; uint public forcedWithdrawalFee; uint public tokenRegistrationFeeLRCBase; uint public tokenRegistrationFeeLRCDelta; uint8 public protocolTakerFeeBips; uint8 public protocolMakerFeeBips; address payable public protocolFeeVault; // == Public Functions == /// @dev Returns the LRC token address /// @return the LRC token address function lrcAddress() external view virtual returns (address); /// @dev Updates the global exchange settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateSettings( address payable _protocolFeeVault, // address(0) not allowed address _blockVerifierAddress, // address(0) not allowed uint _forcedWithdrawalFee ) external virtual; /// @dev Updates the global protocol fee settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateProtocolFeeSettings( uint8 _protocolTakerFeeBips, uint8 _protocolMakerFeeBips ) external virtual; /// @dev Gets the amount of staked LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @return stakedLRC The amount of LRC function getExchangeStake( address exchangeAddr ) public virtual view returns (uint stakedLRC); /// @dev Burns a certain amount of staked LRC for a specific exchange. /// This function is meant to be called only from exchange contracts. /// @return burnedLRC The amount of LRC burned. If the amount is greater than /// the staked amount, all staked LRC will be burned. function burnExchangeStake( uint amount ) external virtual returns (uint burnedLRC); /// @dev Stakes more LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @param amountLRC The amount of LRC to stake /// @return stakedLRC The total amount of LRC staked for the exchange function depositExchangeStake( address exchangeAddr, uint amountLRC ) external virtual returns (uint stakedLRC); /// @dev Withdraws a certain amount of staked LRC for an exchange to the given address. /// This function is meant to be called only from within exchange contracts. /// @param recipient The address to receive LRC /// @param requestedAmount The amount of LRC to withdraw /// @return amountLRC The amount of LRC withdrawn function withdrawExchangeStake( address recipient, uint requestedAmount ) external virtual returns (uint amountLRC); /// @dev Gets the protocol fee values for an exchange. /// @return takerFeeBips The protocol taker fee /// @return makerFeeBips The protocol maker fee function getProtocolFeeValues( ) public virtual view returns ( uint8 takerFeeBips, uint8 makerFeeBips ); } // File: contracts/core/iface/ExchangeData.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeData /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeData { // -- Enums -- enum TransactionType { NOOP, DEPOSIT, WITHDRAWAL, TRANSFER, SPOT_TRADE, ACCOUNT_UPDATE, AMM_UPDATE, SIGNATURE_VERIFICATION, NFT_MINT, // L2 NFT mint or L1-to-L2 NFT deposit NFT_DATA } enum NftType { ERC1155, ERC721 } // -- Structs -- struct Token { address token; } struct ProtocolFeeData { uint32 syncedAt; // only valid before 2105 (85 years to go) uint8 takerFeeBips; uint8 makerFeeBips; uint8 previousTakerFeeBips; uint8 previousMakerFeeBips; } // General auxiliary data for each conditional transaction struct AuxiliaryData { uint txIndex; bool approved; bytes data; } // This is the (virtual) block the owner needs to submit onchain to maintain the // per-exchange (virtual) blockchain. struct Block { uint8 blockType; uint16 blockSize; uint8 blockVersion; bytes data; uint256[8] proof; // Whether we should store the @BlockInfo for this block on-chain. bool storeBlockInfoOnchain; // Block specific data that is only used to help process the block on-chain. // It is not used as input for the circuits and it is not necessary for data-availability. // This bytes array contains the abi encoded AuxiliaryData[] data. bytes auxiliaryData; // Arbitrary data, mainly for off-chain data-availability, i.e., // the multihash of the IPFS file that contains the block data. bytes offchainData; } struct BlockInfo { // The time the block was submitted on-chain. uint32 timestamp; // The public data hash of the block (the 28 most significant bytes). bytes28 blockDataHash; } // Represents an onchain deposit request. struct Deposit { uint96 amount; uint64 timestamp; } // A forced withdrawal request. // If the actual owner of the account initiated the request (we don't know who the owner is // at the time the request is being made) the full balance will be withdrawn. struct ForcedWithdrawal { address owner; uint64 timestamp; } struct Constants { uint SNARK_SCALAR_FIELD; uint MAX_OPEN_FORCED_REQUESTS; uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE; uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS; uint MAX_NUM_ACCOUNTS; uint MAX_NUM_TOKENS; uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED; uint MIN_TIME_IN_SHUTDOWN; uint TX_DATA_AVAILABILITY_SIZE; uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND; } // This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196. uint public constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint public constant MAX_OPEN_FORCED_REQUESTS = 4096; uint public constant MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE = 15 days; uint public constant TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS = 7 days; uint public constant MAX_NUM_ACCOUNTS = 2 ** 32; uint public constant MAX_NUM_TOKENS = 2 ** 16; uint public constant MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED = 7 days; uint public constant MIN_TIME_IN_SHUTDOWN = 30 days; // The amount of bytes each rollup transaction uses in the block data for data-availability. // This is the maximum amount of bytes of all different transaction types. uint32 public constant MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND = 15 days; uint32 public constant ACCOUNTID_PROTOCOLFEE = 0; uint public constant TX_DATA_AVAILABILITY_SIZE = 68; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_1 = 29; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_2 = 39; uint public constant NFT_TOKEN_ID_START = 2 ** 15; struct AccountLeaf { uint32 accountID; address owner; uint pubKeyX; uint pubKeyY; uint32 nonce; uint feeBipsAMM; } struct BalanceLeaf { uint16 tokenID; uint96 balance; uint weightAMM; uint storageRoot; } struct Nft { address minter; // Minter address for a L2 mint or // the NFT's contract address in the case of a L1-to-L2 NFT deposit. NftType nftType; address token; uint256 nftID; uint8 creatorFeeBips; } struct MerkleProof { ExchangeData.AccountLeaf accountLeaf; ExchangeData.BalanceLeaf balanceLeaf; ExchangeData.Nft nft; uint[48] accountMerkleProof; uint[24] balanceMerkleProof; } struct BlockContext { bytes32 DOMAIN_SEPARATOR; uint32 timestamp; Block block; uint txIndex; } // Represents the entire exchange state except the owner of the exchange. struct State { uint32 maxAgeDepositUntilWithdrawable; bytes32 DOMAIN_SEPARATOR; ILoopringV3 loopring; IBlockVerifier blockVerifier; IAgentRegistry agentRegistry; IDepositContract depositContract; // The merkle root of the offchain data stored in a Merkle tree. The Merkle tree // stores balances for users using an account model. bytes32 merkleRoot; // List of all blocks mapping(uint => BlockInfo) blocks; uint numBlocks; // List of all tokens Token[] tokens; // A map from a token to its tokenID + 1 mapping (address => uint16) tokenToTokenId; // A map from an accountID to a tokenID to if the balance is withdrawn mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode; // A map from an account to a token to the amount withdrawable for that account. // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (uint16 => uint)) amountWithdrawable; // A map from an account to a token to the forced withdrawal (always full balance) // The `uint16' represents ERC20 token ID (if < NFT_TOKEN_ID_START) or // NFT balance slot (if >= NFT_TOKEN_ID_START) mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals; // A map from an address to a token to a deposit mapping (address => mapping (uint16 => Deposit)) pendingDeposits; // A map from an account owner to an approved transaction hash to if the transaction is approved or not mapping (address => mapping (bytes32 => bool)) approvedTx; // A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient; // Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner uint32 numPendingForcedTransactions; // Cached data for the protocol fee ProtocolFeeData protocolFeeData; // Time when the exchange was shutdown uint shutdownModeStartTime; // Time when the exchange has entered withdrawal mode uint withdrawalModeStartTime; // Last time the protocol fee was withdrawn for a specific token mapping (address => uint) protocolFeeLastWithdrawnTime; // Duplicated loopring address address loopringAddr; // AMM fee bips uint8 ammFeeBips; // Enable/Disable `onchainTransferFrom` bool allowOnchainTransferFrom; // owner => NFT type => token address => nftID => Deposit mapping (address => mapping (NftType => mapping (address => mapping(uint256 => Deposit)))) pendingNFTDeposits; // owner => minter => NFT type => token address => nftID => amount withdrawable // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (address => mapping (NftType => mapping (address => mapping(uint256 => uint))))) amountWithdrawableNFT; } } // File: contracts/core/iface/IExchangeV3.sol // Copyright 2017 Loopring Technology Limited. /// @title IExchangeV3 /// @dev Note that Claimable and RentrancyGuard are inherited here to /// ensure all data members are declared on IExchangeV3 to make it /// easy to support upgradability through proxies. /// /// Subclasses of this contract must NOT define constructor to /// initialize data. /// /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract IExchangeV3 is Claimable { // -- Events -- event ExchangeCloned( address exchangeAddress, address owner, bytes32 genesisMerkleRoot ); event TokenRegistered( address token, uint16 tokenId ); event Shutdown( uint timestamp ); event WithdrawalModeActivated( uint timestamp ); event BlockSubmitted( uint indexed blockIdx, bytes32 merkleRoot, bytes32 publicDataHash ); event DepositRequested( address from, address to, address token, uint16 tokenId, uint96 amount ); event NFTDepositRequested( address from, address to, uint8 nftType, address token, uint256 nftID, uint96 amount ); event ForcedWithdrawalRequested( address owner, uint16 tokenID, uint32 accountID ); event WithdrawalCompleted( uint8 category, address from, address to, address token, uint amount ); event WithdrawalFailed( uint8 category, address from, address to, address token, uint amount ); event NftWithdrawalCompleted( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); event NftWithdrawalFailed( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); event ProtocolFeesUpdated( uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); event TransactionApproved( address owner, bytes32 transactionHash ); // -- Initialization -- /// @dev Initializes this exchange. This method can only be called once. /// @param loopring The LoopringV3 contract address. /// @param owner The owner of this exchange. /// @param genesisMerkleRoot The initial Merkle tree state. function initialize( address loopring, address owner, bytes32 genesisMerkleRoot ) virtual external; /// @dev Initialized the agent registry contract used by the exchange. /// Can only be called by the exchange owner once. /// @param agentRegistry The agent registry contract to be used function setAgentRegistry(address agentRegistry) external virtual; /// @dev Gets the agent registry contract used by the exchange. /// @return the agent registry contract function getAgentRegistry() external virtual view returns (IAgentRegistry); /// Can only be called by the exchange owner once. /// @param depositContract The deposit contract to be used function setDepositContract(address depositContract) external virtual; /// @dev refresh the blockVerifier contract which maybe changed in loopringV3 contract. function refreshBlockVerifier() external virtual; /// @dev Gets the deposit contract used by the exchange. /// @return the deposit contract function getDepositContract() external virtual view returns (IDepositContract); // @dev Exchange owner withdraws fees from the exchange. // @param token Fee token address // @param feeRecipient Fee recipient address function withdrawExchangeFees( address token, address feeRecipient ) external virtual; // -- Constants -- /// @dev Returns a list of constants used by the exchange. /// @return constants The list of constants. function getConstants() external virtual pure returns(ExchangeData.Constants memory); // -- Mode -- /// @dev Returns hether the exchange is in withdrawal mode. /// @return Returns true if the exchange is in withdrawal mode, else false. function isInWithdrawalMode() external virtual view returns (bool); /// @dev Returns whether the exchange is shutdown. /// @return Returns true if the exchange is shutdown, else false. function isShutdown() external virtual view returns (bool); // -- Tokens -- /// @dev Registers an ERC20 token for a token id. Note that different exchanges may have /// different ids for the same ERC20 token. /// /// Please note that 1 is reserved for Ether (ETH), 2 is reserved for Wrapped Ether (ETH), /// and 3 is reserved for Loopring Token (LRC). /// /// This function is only callable by the exchange owner. /// /// @param tokenAddress The token's address /// @return tokenID The token's ID in this exchanges. function registerToken( address tokenAddress ) external virtual returns (uint16 tokenID); /// @dev Returns the id of a registered token. /// @param tokenAddress The token's address /// @return tokenID The token's ID in this exchanges. function getTokenID( address tokenAddress ) external virtual view returns (uint16 tokenID); /// @dev Returns the address of a registered token. /// @param tokenID The token's ID in this exchanges. /// @return tokenAddress The token's address function getTokenAddress( uint16 tokenID ) external virtual view returns (address tokenAddress); // -- Stakes -- /// @dev Gets the amount of LRC the owner has staked onchain for this exchange. /// The stake will be burned if the exchange does not fulfill its duty by /// processing user requests in time. Please note that order matching may potentially /// performed by another party and is not part of the exchange's duty. /// /// @return The amount of LRC staked function getExchangeStake() external virtual view returns (uint); /// @dev Withdraws the amount staked for this exchange. /// This can only be done if the exchange has been correctly shutdown: /// - The exchange owner has shutdown the exchange /// - All deposit requests are processed /// - All funds are returned to the users (merkle root is reset to initial state) /// /// Can only be called by the exchange owner. /// /// @return amountLRC The amount of LRC withdrawn function withdrawExchangeStake( address recipient ) external virtual returns (uint amountLRC); /// @dev Can by called by anyone to burn the stake of the exchange when certain /// conditions are fulfilled. /// /// Currently this will only burn the stake of the exchange if /// the exchange is in withdrawal mode. function burnExchangeStake() external virtual; // -- Blocks -- /// @dev Gets the current Merkle root of this exchange's virtual blockchain. /// @return The current Merkle root. function getMerkleRoot() external virtual view returns (bytes32); /// @dev Gets the height of this exchange's virtual blockchain. The block height for a /// new exchange is 1. /// @return The virtual blockchain height which is the index of the last block. function getBlockHeight() external virtual view returns (uint); /// @dev Gets some minimal info of a previously submitted block that's kept onchain. /// A DEX can use this function to implement a payment receipt verification /// contract with a challange-response scheme. /// @param blockIdx The block index. function getBlockInfo(uint blockIdx) external virtual view returns (ExchangeData.BlockInfo memory); /// @dev Sumbits new blocks to the rollup blockchain. /// /// This function can only be called by the exchange operator. /// /// @param blocks The blocks being submitted /// - blockType: The type of the new block /// - blockSize: The number of onchain or offchain requests/settlements /// that have been processed in this block /// - blockVersion: The circuit version to use for verifying the block /// - storeBlockInfoOnchain: If the block info for this block needs to be stored on-chain /// - data: The data for this block /// - offchainData: Arbitrary data, mainly for off-chain data-availability, i.e., /// the multihash of the IPFS file that contains the block data. function submitBlocks(ExchangeData.Block[] calldata blocks) external virtual; /// @dev Gets the number of available forced request slots. /// @return The number of available slots. function getNumAvailableForcedSlots() external virtual view returns (uint); // -- Deposits -- /// @dev Deposits Ether or ERC20 tokens to the specified account. /// /// This function is only callable by an agent of 'from'. /// /// The operator is not forced to do the deposit. /// /// @param from The address that deposits the funds to the exchange /// @param to The account owner's address receiving the funds /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param amount The amount of tokens to deposit /// @param extraData Optional extra data used by the deposit contract function deposit( address from, address to, address tokenAddress, uint96 amount, bytes calldata extraData ) external virtual payable; /// @dev Deposits an NFT to the specified account. /// /// This function is only callable by an agent of 'from'. /// /// The operator is not forced to do the deposit. /// /// @param from The address that deposits the funds to the exchange /// @param to The account owner's address receiving the funds /// @param nftType The type of NFT contract address (ERC721/ERC1155/...) /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param nftID The token type 'id`. /// @param amount The amount of tokens to deposit. /// @param extraData Optional extra data used by the deposit contract. function depositNFT( address from, address to, ExchangeData.NftType nftType, address tokenAddress, uint256 nftID, uint96 amount, bytes calldata extraData ) external virtual; /// @dev Gets the amount of tokens that may be added to the owner's account. /// @param owner The destination address for the amount deposited. /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @return The amount of tokens pending. function getPendingDepositAmount( address owner, address tokenAddress ) public virtual view returns (uint96); /// @dev Gets the amount of tokens that may be added to the owner's account. /// @param owner The destination address for the amount deposited. /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param nftType The type of NFT contract address (ERC721/ERC1155/...) /// @param nftID The token type 'id`. /// @return The amount of tokens pending. function getPendingNFTDepositAmount( address owner, address tokenAddress, ExchangeData.NftType nftType, uint256 nftID ) public virtual view returns (uint96); // -- Withdrawals -- /// @dev Submits an onchain request to force withdraw Ether, ERC20 and NFT tokens. /// This request always withdraws the full balance. /// /// This function is only callable by an agent of the account. /// /// The total fee in ETH that the user needs to pay is 'withdrawalFee'. /// If the user sends too much ETH the surplus is sent back immediately. /// /// Note that after such an operation, it will take the owner some /// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request /// and create the deposit to the offchain account. /// /// @param owner The expected owner of the account /// @param tokenID The tokenID to withdraw from /// @param accountID The address the account in the Merkle tree. function forceWithdrawByTokenID( address owner, uint16 tokenID, uint32 accountID ) external virtual payable; /// @dev Submits an onchain request to force withdraw Ether or ERC20 tokens. /// This request always withdraws the full balance. /// /// This function is only callable by an agent of the account. /// /// The total fee in ETH that the user needs to pay is 'withdrawalFee'. /// If the user sends too much ETH the surplus is sent back immediately. /// /// Note that after such an operation, it will take the owner some /// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request /// and create the deposit to the offchain account. /// /// @param owner The expected owner of the account /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param accountID The address the account in the Merkle tree. function forceWithdraw( address owner, address tokenAddress, uint32 accountID ) external virtual payable; /// @dev Checks if a forced withdrawal is pending for an account balance. /// @param accountID The accountID of the account to check. /// @param token The token address /// @return True if a request is pending, false otherwise function isForcedWithdrawalPending( uint32 accountID, address token ) external virtual view returns (bool); /// @dev Submits an onchain request to withdraw Ether or ERC20 tokens from the /// protocol fees account. The complete balance is always withdrawn. /// /// Anyone can request a withdrawal of the protocol fees. /// /// Note that after such an operation, it will take the owner some /// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request /// and create the deposit to the offchain account. /// /// @param tokenAddress The address of the token, use `0x0` for Ether. function withdrawProtocolFees( address tokenAddress ) external virtual payable; /// @dev Gets the time the protocol fee for a token was last withdrawn. /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @return The time the protocol fee was last withdrawn. function getProtocolFeeLastWithdrawnTime( address tokenAddress ) external virtual view returns (uint); /// @dev Allows anyone to withdraw funds for a specified user using the balances stored /// in the Merkle tree. The funds will be sent to the owner of the acount. /// /// Can only be used in withdrawal mode (i.e. when the owner has stopped /// committing blocks and is not able to commit any more blocks). /// /// This will NOT modify the onchain merkle root! The merkle root stored /// onchain will remain the same after the withdrawal. We store if the user /// has withdrawn the balance in State.withdrawnInWithdrawMode. /// /// @param merkleProof The Merkle inclusion proof function withdrawFromMerkleTree( ExchangeData.MerkleProof calldata merkleProof ) external virtual; /// @dev Checks if the balance for the account was withdrawn with `withdrawFromMerkleTree`. /// @param accountID The accountID of the balance to check. /// @param token The token address /// @return True if it was already withdrawn, false otherwise function isWithdrawnInWithdrawalMode( uint32 accountID, address token ) external virtual view returns (bool); /// @dev Allows withdrawing funds deposited to the contract in a deposit request when /// it was never processed by the owner within the maximum time allowed. /// /// Can be called by anyone. The deposited tokens will be sent back to /// the owner of the account they were deposited in. /// /// @param owner The address of the account the withdrawal was done for. /// @param token The token address function withdrawFromDepositRequest( address owner, address token ) external virtual; /// @dev Allows withdrawing funds deposited to the contract in a deposit request when /// it was never processed by the owner within the maximum time allowed. /// /// Can be called by anyone. The deposited tokens will be sent back to /// the owner of the account they were deposited in. /// /// @param owner The address of the account the withdrawal was done for. /// @param token The token address /// @param nftType The type of NFT contract address (ERC721/ERC1155/...) /// @param nftID The token type 'id`. function withdrawFromNFTDepositRequest( address owner, address token, ExchangeData.NftType nftType, uint256 nftID ) external virtual; /// @dev Allows withdrawing funds after a withdrawal request (either onchain /// or offchain) was submitted in a block by the operator. /// /// Can be called by anyone. The withdrawn tokens will be sent to /// the owner of the account they were withdrawn out. /// /// Normally it is should not be needed for users to call this manually. /// Funds from withdrawal requests will be sent to the account owner /// immediately by the owner when the block is submitted. /// The user will however need to call this manually if the transfer failed. /// /// Tokens and owners must have the same size. /// /// @param owners The addresses of the account the withdrawal was done for. /// @param tokens The token addresses function withdrawFromApprovedWithdrawals( address[] calldata owners, address[] calldata tokens ) external virtual; /// @dev Allows withdrawing funds after an NFT withdrawal request (either onchain /// or offchain) was submitted in a block by the operator. /// /// Can be called by anyone. The withdrawn tokens will be sent to /// the owner of the account they were withdrawn out. /// /// Normally it is should not be needed for users to call this manually. /// Funds from withdrawal requests will be sent to the account owner /// immediately by the owner when the block is submitted. /// The user will however need to call this manually if the transfer failed. /// /// All input arrays must have the same size. /// /// @param owners The addresses of the accounts the withdrawal was done for. /// @param minters The addresses of the minters. /// @param nftTypes The NFT token addresses types /// @param tokens The token addresses /// @param nftIDs The token ids function withdrawFromApprovedWithdrawalsNFT( address[] memory owners, address[] memory minters, ExchangeData.NftType[] memory nftTypes, address[] memory tokens, uint256[] memory nftIDs ) external virtual; /// @dev Gets the amount that can be withdrawn immediately with `withdrawFromApprovedWithdrawals`. /// @param owner The address of the account the withdrawal was done for. /// @param token The token address /// @return The amount withdrawable function getAmountWithdrawable( address owner, address token ) external virtual view returns (uint); /// @dev Gets the amount that can be withdrawn immediately with `withdrawFromApprovedWithdrawalsNFT`. /// @param owner The address of the account the withdrawal was done for. /// @param token The token address /// @param nftType The NFT token address types /// @param nftID The token id /// @param minter The NFT minter /// @return The amount withdrawable function getAmountWithdrawableNFT( address owner, address token, ExchangeData.NftType nftType, uint256 nftID, address minter ) external virtual view returns (uint); /// @dev Notifies the exchange that the owner did not process a forced request. /// If this is indeed the case, the exchange will enter withdrawal mode. /// /// Can be called by anyone. /// /// @param accountID The accountID the forced request was made for /// @param tokenID The tokenID of the the forced request function notifyForcedRequestTooOld( uint32 accountID, uint16 tokenID ) external virtual; /// @dev Allows a withdrawal to be done to an adddresss that is different /// than initialy specified in the withdrawal request. This can be used to /// implement functionality like fast withdrawals. /// /// This function can only be called by an agent. /// /// @param from The address of the account that does the withdrawal. /// @param to The address to which 'amount' tokens were going to be withdrawn. /// @param token The address of the token that is withdrawn ('0x0' for ETH). /// @param amount The amount of tokens that are going to be withdrawn. /// @param storageID The storageID of the withdrawal request. /// @param newRecipient The new recipient address of the withdrawal. function setWithdrawalRecipient( address from, address to, address token, uint96 amount, uint32 storageID, address newRecipient ) external virtual; /// @dev Gets the withdrawal recipient. /// /// @param from The address of the account that does the withdrawal. /// @param to The address to which 'amount' tokens were going to be withdrawn. /// @param token The address of the token that is withdrawn ('0x0' for ETH). /// @param amount The amount of tokens that are going to be withdrawn. /// @param storageID The storageID of the withdrawal request. function getWithdrawalRecipient( address from, address to, address token, uint96 amount, uint32 storageID ) external virtual view returns (address); /// @dev Allows an agent to transfer ERC-20 tokens for a user using the allowance /// the user has set for the exchange. This way the user only needs to approve a single exchange contract /// for all exchange/agent features, which allows for a more seamless user experience. /// /// This function can only be called by an agent. /// /// @param from The address of the account that sends the tokens. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (ETH is and cannot be suppported). /// @param amount The amount of tokens transferred. function onchainTransferFrom( address from, address to, address token, uint amount ) external virtual; /// @dev Allows an agent to approve a rollup tx. /// /// This function can only be called by an agent. /// /// @param owner The owner of the account /// @param txHash The hash of the transaction function approveTransaction( address owner, bytes32 txHash ) external virtual; /// @dev Allows an agent to approve multiple rollup txs. /// /// This function can only be called by an agent. /// /// @param owners The account owners /// @param txHashes The hashes of the transactions function approveTransactions( address[] calldata owners, bytes32[] calldata txHashes ) external virtual; /// @dev Checks if a rollup tx is approved using the tx's hash. /// /// @param owner The owner of the account that needs to authorize the tx /// @param txHash The hash of the transaction /// @return True if the tx is approved, else false function isTransactionApproved( address owner, bytes32 txHash ) external virtual view returns (bool); // -- Admins -- /// @dev Sets the max time deposits have to wait before becoming withdrawable. /// @param newValue The new value. /// @return The old value. function setMaxAgeDepositUntilWithdrawable( uint32 newValue ) external virtual returns (uint32); /// @dev Returns the max time deposits have to wait before becoming withdrawable. /// @return The value. function getMaxAgeDepositUntilWithdrawable() external virtual view returns (uint32); /// @dev Shuts down the exchange. /// Once the exchange is shutdown all onchain requests are permanently disabled. /// When all requirements are fulfilled the exchange owner can withdraw /// the exchange stake with withdrawStake. /// /// Note that the exchange can still enter the withdrawal mode after this function /// has been invoked successfully. To prevent entering the withdrawal mode before the /// the echange stake can be withdrawn, all withdrawal requests still need to be handled /// for at least MIN_TIME_IN_SHUTDOWN seconds. /// /// Can only be called by the exchange owner. /// /// @return success True if the exchange is shutdown, else False function shutdown() external virtual returns (bool success); /// @dev Gets the protocol fees for this exchange. /// @return syncedAt The timestamp the protocol fees were last updated /// @return takerFeeBips The protocol taker fee /// @return makerFeeBips The protocol maker fee /// @return previousTakerFeeBips The previous protocol taker fee /// @return previousMakerFeeBips The previous protocol maker fee function getProtocolFeeValues() external virtual view returns ( uint32 syncedAt, uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); /// @dev Gets the domain separator used in this exchange. function getDomainSeparator() external virtual view returns (bytes32); /// @dev set amm pool feeBips value. function setAmmFeeBips(uint8 _feeBips) external virtual; /// @dev get amm pool feeBips value. function getAmmFeeBips() external virtual view returns (uint8); } // File: contracts/lib/ERC20.sol // Copyright 2017 Loopring Technology Limited. /// @title ERC20 Token Interface /// @dev see https://github.com/ethereum/EIPs/issues/20 /// @author Daniel Wang - <[email protected]> abstract contract ERC20 { function totalSupply() public virtual view returns (uint); function balanceOf( address who ) public virtual view returns (uint); function allowance( address owner, address spender ) public virtual view returns (uint); function transfer( address to, uint value ) public virtual returns (bool); function transferFrom( address from, address to, uint value ) public virtual returns (bool); function approve( address spender, uint value ) public virtual returns (bool); } // File: contracts/core/impl/libexchange/ExchangeMode.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeMode. /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeMode { using MathUint for uint; function isInWithdrawalMode( ExchangeData.State storage S ) internal // inline call view returns (bool result) { result = S.withdrawalModeStartTime > 0; } function isShutdown( ExchangeData.State storage S ) internal // inline call view returns (bool) { return S.shutdownModeStartTime > 0; } function getNumAvailableForcedSlots( ExchangeData.State storage S ) internal view returns (uint) { return ExchangeData.MAX_OPEN_FORCED_REQUESTS - S.numPendingForcedTransactions; } } // File: contracts/core/impl/libexchange/ExchangeAdmins.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeAdmins. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeAdmins { using ERC20SafeTransfer for address; using ExchangeMode for ExchangeData.State; using MathUint for uint; event MaxAgeDepositUntilWithdrawableChanged( address indexed exchangeAddr, uint32 oldValue, uint32 newValue ); function setMaxAgeDepositUntilWithdrawable( ExchangeData.State storage S, uint32 newValue ) public returns (uint32 oldValue) { require(!S.isInWithdrawalMode(), "INVALID_MODE"); require( newValue > 0 && newValue <= ExchangeData.MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND, "INVALID_VALUE" ); oldValue = S.maxAgeDepositUntilWithdrawable; S.maxAgeDepositUntilWithdrawable = newValue; emit MaxAgeDepositUntilWithdrawableChanged( address(this), oldValue, newValue ); } function withdrawExchangeStake( ExchangeData.State storage S, address recipient ) public returns (uint) { // Exchange needs to be shutdown require(S.isShutdown(), "EXCHANGE_NOT_SHUTDOWN"); require(!S.isInWithdrawalMode(), "CANNOT_BE_IN_WITHDRAWAL_MODE"); // Need to remain in shutdown for some time require(block.timestamp >= S.shutdownModeStartTime + ExchangeData.MIN_TIME_IN_SHUTDOWN, "TOO_EARLY"); // Withdraw the complete stake uint amount = S.loopring.getExchangeStake(address(this)); return S.loopring.withdrawExchangeStake(recipient, amount); } } // File: contracts/lib/Poseidon.sol // Copyright 2017 Loopring Technology Limited. /// @title Poseidon hash function /// See: https://eprint.iacr.org/2019/458.pdf /// Code auto-generated by generate_poseidon_EVM_code.py /// @author Brecht Devos - <[email protected]> library Poseidon { // // hash_t4f6p52 // struct HashInputs4 { uint t0; uint t1; uint t2; uint t3; } function mix(HashInputs4 memory i, uint q) internal pure { HashInputs4 memory o; o.t0 = mulmod(i.t0, 11739432287187184656569880828944421268616385874806221589758215824904320817117, q); o.t0 = addmod(o.t0, mulmod(i.t1, 4977258759536702998522229302103997878600602264560359702680165243908162277980, q), q); o.t0 = addmod(o.t0, mulmod(i.t2, 19167410339349846567561662441069598364702008768579734801591448511131028229281, q), q); o.t0 = addmod(o.t0, mulmod(i.t3, 14183033936038168803360723133013092560869148726790180682363054735190196956789, q), q); o.t1 = mulmod(i.t0, 16872301185549870956030057498946148102848662396374401407323436343924021192350, q); o.t1 = addmod(o.t1, mulmod(i.t1, 107933704346764130067829474107909495889716688591997879426350582457782826785, q), q); o.t1 = addmod(o.t1, mulmod(i.t2, 17034139127218860091985397764514160131253018178110701196935786874261236172431, q), q); o.t1 = addmod(o.t1, mulmod(i.t3, 2799255644797227968811798608332314218966179365168250111693473252876996230317, q), q); o.t2 = mulmod(i.t0, 18618317300596756144100783409915332163189452886691331959651778092154775572832, q); o.t2 = addmod(o.t2, mulmod(i.t1, 13596762909635538739079656925495736900379091964739248298531655823337482778123, q), q); o.t2 = addmod(o.t2, mulmod(i.t2, 18985203040268814769637347880759846911264240088034262814847924884273017355969, q), q); o.t2 = addmod(o.t2, mulmod(i.t3, 8652975463545710606098548415650457376967119951977109072274595329619335974180, q), q); o.t3 = mulmod(i.t0, 11128168843135959720130031095451763561052380159981718940182755860433840154182, q); o.t3 = addmod(o.t3, mulmod(i.t1, 2953507793609469112222895633455544691298656192015062835263784675891831794974, q), q); o.t3 = addmod(o.t3, mulmod(i.t2, 19025623051770008118343718096455821045904242602531062247152770448380880817517, q), q); o.t3 = addmod(o.t3, mulmod(i.t3, 9077319817220936628089890431129759976815127354480867310384708941479362824016, q), q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; } function ark(HashInputs4 memory i, uint q, uint c) internal pure { HashInputs4 memory o; o.t0 = addmod(i.t0, c, q); o.t1 = addmod(i.t1, c, q); o.t2 = addmod(i.t2, c, q); o.t3 = addmod(i.t3, c, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; } function sbox_full(HashInputs4 memory i, uint q) internal pure { HashInputs4 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); o.t1 = mulmod(i.t1, i.t1, q); o.t1 = mulmod(o.t1, o.t1, q); o.t1 = mulmod(i.t1, o.t1, q); o.t2 = mulmod(i.t2, i.t2, q); o.t2 = mulmod(o.t2, o.t2, q); o.t2 = mulmod(i.t2, o.t2, q); o.t3 = mulmod(i.t3, i.t3, q); o.t3 = mulmod(o.t3, o.t3, q); o.t3 = mulmod(i.t3, o.t3, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; } function sbox_partial(HashInputs4 memory i, uint q) internal pure { HashInputs4 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); i.t0 = o.t0; } function hash_t4f6p52(HashInputs4 memory i, uint q) internal pure returns (uint) { // validate inputs require(i.t0 < q, "INVALID_INPUT"); require(i.t1 < q, "INVALID_INPUT"); require(i.t2 < q, "INVALID_INPUT"); require(i.t3 < q, "INVALID_INPUT"); // round 0 ark(i, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522); sbox_full(i, q); mix(i, q); // round 1 ark(i, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128); sbox_full(i, q); mix(i, q); // round 2 ark(i, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509); sbox_full(i, q); mix(i, q); // round 3 ark(i, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615); sbox_partial(i, q); mix(i, q); // round 4 ark(i, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514); sbox_partial(i, q); mix(i, q); // round 5 ark(i, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619); sbox_partial(i, q); mix(i, q); // round 6 ark(i, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153); sbox_partial(i, q); mix(i, q); // round 7 ark(i, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608); sbox_partial(i, q); mix(i, q); // round 8 ark(i, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567); sbox_partial(i, q); mix(i, q); // round 9 ark(i, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471); sbox_partial(i, q); mix(i, q); // round 10 ark(i, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765); sbox_partial(i, q); mix(i, q); // round 11 ark(i, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772); sbox_partial(i, q); mix(i, q); // round 12 ark(i, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850); sbox_partial(i, q); mix(i, q); // round 13 ark(i, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375); sbox_partial(i, q); mix(i, q); // round 14 ark(i, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136); sbox_partial(i, q); mix(i, q); // round 15 ark(i, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374); sbox_partial(i, q); mix(i, q); // round 16 ark(i, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107); sbox_partial(i, q); mix(i, q); // round 17 ark(i, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214); sbox_partial(i, q); mix(i, q); // round 18 ark(i, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455); sbox_partial(i, q); mix(i, q); // round 19 ark(i, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212); sbox_partial(i, q); mix(i, q); // round 20 ark(i, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626); sbox_partial(i, q); mix(i, q); // round 21 ark(i, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417); sbox_partial(i, q); mix(i, q); // round 22 ark(i, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006); sbox_partial(i, q); mix(i, q); // round 23 ark(i, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766); sbox_partial(i, q); mix(i, q); // round 24 ark(i, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832); sbox_partial(i, q); mix(i, q); // round 25 ark(i, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231); sbox_partial(i, q); mix(i, q); // round 26 ark(i, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114); sbox_partial(i, q); mix(i, q); // round 27 ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719); sbox_partial(i, q); mix(i, q); // round 28 ark(i, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018); sbox_partial(i, q); mix(i, q); // round 29 ark(i, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562); sbox_partial(i, q); mix(i, q); // round 30 ark(i, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826); sbox_partial(i, q); mix(i, q); // round 31 ark(i, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245); sbox_partial(i, q); mix(i, q); // round 32 ark(i, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748); sbox_partial(i, q); mix(i, q); // round 33 ark(i, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508); sbox_partial(i, q); mix(i, q); // round 34 ark(i, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523); sbox_partial(i, q); mix(i, q); // round 35 ark(i, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410); sbox_partial(i, q); mix(i, q); // round 36 ark(i, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935); sbox_partial(i, q); mix(i, q); // round 37 ark(i, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643); sbox_partial(i, q); mix(i, q); // round 38 ark(i, q, 71447649211767888770311304010816315780740050029903404046389165015534756512); sbox_partial(i, q); mix(i, q); // round 39 ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393); sbox_partial(i, q); mix(i, q); // round 40 ark(i, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525); sbox_partial(i, q); mix(i, q); // round 41 ark(i, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006); sbox_partial(i, q); mix(i, q); // round 42 ark(i, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058); sbox_partial(i, q); mix(i, q); // round 43 ark(i, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739); sbox_partial(i, q); mix(i, q); // round 44 ark(i, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548); sbox_partial(i, q); mix(i, q); // round 45 ark(i, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311); sbox_partial(i, q); mix(i, q); // round 46 ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208); sbox_partial(i, q); mix(i, q); // round 47 ark(i, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706); sbox_partial(i, q); mix(i, q); // round 48 ark(i, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232); sbox_partial(i, q); mix(i, q); // round 49 ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524); sbox_partial(i, q); mix(i, q); // round 50 ark(i, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266); sbox_partial(i, q); mix(i, q); // round 51 ark(i, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210); sbox_partial(i, q); mix(i, q); // round 52 ark(i, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743); sbox_partial(i, q); mix(i, q); // round 53 ark(i, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373); sbox_partial(i, q); mix(i, q); // round 54 ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849); sbox_partial(i, q); mix(i, q); // round 55 ark(i, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076); sbox_full(i, q); mix(i, q); // round 56 ark(i, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047); sbox_full(i, q); mix(i, q); // round 57 ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544); sbox_full(i, q); mix(i, q); return i.t0; } // // hash_t5f6p52 // struct HashInputs5 { uint t0; uint t1; uint t2; uint t3; uint t4; } function hash_t5f6p52_internal( uint t0, uint t1, uint t2, uint t3, uint t4, uint q ) internal pure returns (uint) { assembly { function mix(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 { nt0 := mulmod(_t0, 4977258759536702998522229302103997878600602264560359702680165243908162277980, _q) nt0 := addmod(nt0, mulmod(_t1, 19167410339349846567561662441069598364702008768579734801591448511131028229281, _q), _q) nt0 := addmod(nt0, mulmod(_t2, 14183033936038168803360723133013092560869148726790180682363054735190196956789, _q), _q) nt0 := addmod(nt0, mulmod(_t3, 9067734253445064890734144122526450279189023719890032859456830213166173619761, _q), _q) nt0 := addmod(nt0, mulmod(_t4, 16378664841697311562845443097199265623838619398287411428110917414833007677155, _q), _q) nt1 := mulmod(_t0, 107933704346764130067829474107909495889716688591997879426350582457782826785, _q) nt1 := addmod(nt1, mulmod(_t1, 17034139127218860091985397764514160131253018178110701196935786874261236172431, _q), _q) nt1 := addmod(nt1, mulmod(_t2, 2799255644797227968811798608332314218966179365168250111693473252876996230317, _q), _q) nt1 := addmod(nt1, mulmod(_t3, 2482058150180648511543788012634934806465808146786082148795902594096349483974, _q), _q) nt1 := addmod(nt1, mulmod(_t4, 16563522740626180338295201738437974404892092704059676533096069531044355099628, _q), _q) nt2 := mulmod(_t0, 13596762909635538739079656925495736900379091964739248298531655823337482778123, _q) nt2 := addmod(nt2, mulmod(_t1, 18985203040268814769637347880759846911264240088034262814847924884273017355969, _q), _q) nt2 := addmod(nt2, mulmod(_t2, 8652975463545710606098548415650457376967119951977109072274595329619335974180, _q), _q) nt2 := addmod(nt2, mulmod(_t3, 970943815872417895015626519859542525373809485973005165410533315057253476903, _q), _q) nt2 := addmod(nt2, mulmod(_t4, 19406667490568134101658669326517700199745817783746545889094238643063688871948, _q), _q) nt3 := mulmod(_t0, 2953507793609469112222895633455544691298656192015062835263784675891831794974, _q) nt3 := addmod(nt3, mulmod(_t1, 19025623051770008118343718096455821045904242602531062247152770448380880817517, _q), _q) nt3 := addmod(nt3, mulmod(_t2, 9077319817220936628089890431129759976815127354480867310384708941479362824016, _q), _q) nt3 := addmod(nt3, mulmod(_t3, 4770370314098695913091200576539533727214143013236894216582648993741910829490, _q), _q) nt3 := addmod(nt3, mulmod(_t4, 4298564056297802123194408918029088169104276109138370115401819933600955259473, _q), _q) nt4 := mulmod(_t0, 8336710468787894148066071988103915091676109272951895469087957569358494947747, _q) nt4 := addmod(nt4, mulmod(_t1, 16205238342129310687768799056463408647672389183328001070715567975181364448609, _q), _q) nt4 := addmod(nt4, mulmod(_t2, 8303849270045876854140023508764676765932043944545416856530551331270859502246, _q), _q) nt4 := addmod(nt4, mulmod(_t3, 20218246699596954048529384569730026273241102596326201163062133863539137060414, _q), _q) nt4 := addmod(nt4, mulmod(_t4, 1712845821388089905746651754894206522004527237615042226559791118162382909269, _q), _q) } function ark(_t0, _t1, _t2, _t3, _t4, _q, c) -> nt0, nt1, nt2, nt3, nt4 { nt0 := addmod(_t0, c, _q) nt1 := addmod(_t1, c, _q) nt2 := addmod(_t2, c, _q) nt3 := addmod(_t3, c, _q) nt4 := addmod(_t4, c, _q) } function sbox_full(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 { nt0 := mulmod(_t0, _t0, _q) nt0 := mulmod(nt0, nt0, _q) nt0 := mulmod(_t0, nt0, _q) nt1 := mulmod(_t1, _t1, _q) nt1 := mulmod(nt1, nt1, _q) nt1 := mulmod(_t1, nt1, _q) nt2 := mulmod(_t2, _t2, _q) nt2 := mulmod(nt2, nt2, _q) nt2 := mulmod(_t2, nt2, _q) nt3 := mulmod(_t3, _t3, _q) nt3 := mulmod(nt3, nt3, _q) nt3 := mulmod(_t3, nt3, _q) nt4 := mulmod(_t4, _t4, _q) nt4 := mulmod(nt4, nt4, _q) nt4 := mulmod(_t4, nt4, _q) } function sbox_partial(_t, _q) -> nt { nt := mulmod(_t, _t, _q) nt := mulmod(nt, nt, _q) nt := mulmod(_t, nt, _q) } // round 0 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 1 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 2 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 3 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 4 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 5 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 6 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 7 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 8 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 9 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 10 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 11 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 12 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 13 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 14 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 15 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 16 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 17 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 18 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 19 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 20 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 21 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 22 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 23 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 24 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 25 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 26 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 27 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 28 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 29 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 30 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 31 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 32 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 33 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 34 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 35 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 36 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 37 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 38 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 71447649211767888770311304010816315780740050029903404046389165015534756512) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 39 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 40 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 41 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 42 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 43 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 44 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 45 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 46 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 47 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 48 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 49 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 50 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 51 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 52 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 53 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 54 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 55 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 56 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 57 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) } return t0; } function hash_t5f6p52(HashInputs5 memory i, uint q) internal pure returns (uint) { // validate inputs require(i.t0 < q, "INVALID_INPUT"); require(i.t1 < q, "INVALID_INPUT"); require(i.t2 < q, "INVALID_INPUT"); require(i.t3 < q, "INVALID_INPUT"); require(i.t4 < q, "INVALID_INPUT"); return hash_t5f6p52_internal(i.t0, i.t1, i.t2, i.t3, i.t4, q); } // // hash_t7f6p52 // struct HashInputs7 { uint t0; uint t1; uint t2; uint t3; uint t4; uint t5; uint t6; } function mix(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, 14183033936038168803360723133013092560869148726790180682363054735190196956789, q); o.t0 = addmod(o.t0, mulmod(i.t1, 9067734253445064890734144122526450279189023719890032859456830213166173619761, q), q); o.t0 = addmod(o.t0, mulmod(i.t2, 16378664841697311562845443097199265623838619398287411428110917414833007677155, q), q); o.t0 = addmod(o.t0, mulmod(i.t3, 12968540216479938138647596899147650021419273189336843725176422194136033835172, q), q); o.t0 = addmod(o.t0, mulmod(i.t4, 3636162562566338420490575570584278737093584021456168183289112789616069756675, q), q); o.t0 = addmod(o.t0, mulmod(i.t5, 8949952361235797771659501126471156178804092479420606597426318793013844305422, q), q); o.t0 = addmod(o.t0, mulmod(i.t6, 13586657904816433080148729258697725609063090799921401830545410130405357110367, q), q); o.t1 = mulmod(i.t0, 2799255644797227968811798608332314218966179365168250111693473252876996230317, q); o.t1 = addmod(o.t1, mulmod(i.t1, 2482058150180648511543788012634934806465808146786082148795902594096349483974, q), q); o.t1 = addmod(o.t1, mulmod(i.t2, 16563522740626180338295201738437974404892092704059676533096069531044355099628, q), q); o.t1 = addmod(o.t1, mulmod(i.t3, 10468644849657689537028565510142839489302836569811003546969773105463051947124, q), q); o.t1 = addmod(o.t1, mulmod(i.t4, 3328913364598498171733622353010907641674136720305714432354138807013088636408, q), q); o.t1 = addmod(o.t1, mulmod(i.t5, 8642889650254799419576843603477253661899356105675006557919250564400804756641, q), q); o.t1 = addmod(o.t1, mulmod(i.t6, 14300697791556510113764686242794463641010174685800128469053974698256194076125, q), q); o.t2 = mulmod(i.t0, 8652975463545710606098548415650457376967119951977109072274595329619335974180, q); o.t2 = addmod(o.t2, mulmod(i.t1, 970943815872417895015626519859542525373809485973005165410533315057253476903, q), q); o.t2 = addmod(o.t2, mulmod(i.t2, 19406667490568134101658669326517700199745817783746545889094238643063688871948, q), q); o.t2 = addmod(o.t2, mulmod(i.t3, 17049854690034965250221386317058877242629221002521630573756355118745574274967, q), q); o.t2 = addmod(o.t2, mulmod(i.t4, 4964394613021008685803675656098849539153699842663541444414978877928878266244, q), q); o.t2 = addmod(o.t2, mulmod(i.t5, 15474947305445649466370538888925567099067120578851553103424183520405650587995, q), q); o.t2 = addmod(o.t2, mulmod(i.t6, 1016119095639665978105768933448186152078842964810837543326777554729232767846, q), q); o.t3 = mulmod(i.t0, 9077319817220936628089890431129759976815127354480867310384708941479362824016, q); o.t3 = addmod(o.t3, mulmod(i.t1, 4770370314098695913091200576539533727214143013236894216582648993741910829490, q), q); o.t3 = addmod(o.t3, mulmod(i.t2, 4298564056297802123194408918029088169104276109138370115401819933600955259473, q), q); o.t3 = addmod(o.t3, mulmod(i.t3, 6905514380186323693285869145872115273350947784558995755916362330070690839131, q), q); o.t3 = addmod(o.t3, mulmod(i.t4, 4783343257810358393326889022942241108539824540285247795235499223017138301952, q), q); o.t3 = addmod(o.t3, mulmod(i.t5, 1420772902128122367335354247676760257656541121773854204774788519230732373317, q), q); o.t3 = addmod(o.t3, mulmod(i.t6, 14172871439045259377975734198064051992755748777535789572469924335100006948373, q), q); o.t4 = mulmod(i.t0, 8303849270045876854140023508764676765932043944545416856530551331270859502246, q); o.t4 = addmod(o.t4, mulmod(i.t1, 20218246699596954048529384569730026273241102596326201163062133863539137060414, q), q); o.t4 = addmod(o.t4, mulmod(i.t2, 1712845821388089905746651754894206522004527237615042226559791118162382909269, q), q); o.t4 = addmod(o.t4, mulmod(i.t3, 13001155522144542028910638547179410124467185319212645031214919884423841839406, q), q); o.t4 = addmod(o.t4, mulmod(i.t4, 16037892369576300958623292723740289861626299352695838577330319504984091062115, q), q); o.t4 = addmod(o.t4, mulmod(i.t5, 19189494548480259335554606182055502469831573298885662881571444557262020106898, q), q); o.t4 = addmod(o.t4, mulmod(i.t6, 19032687447778391106390582750185144485341165205399984747451318330476859342654, q), q); o.t5 = mulmod(i.t0, 13272957914179340594010910867091459756043436017766464331915862093201960540910, q); o.t5 = addmod(o.t5, mulmod(i.t1, 9416416589114508529880440146952102328470363729880726115521103179442988482948, q), q); o.t5 = addmod(o.t5, mulmod(i.t2, 8035240799672199706102747147502951589635001418759394863664434079699838251138, q), q); o.t5 = addmod(o.t5, mulmod(i.t3, 21642389080762222565487157652540372010968704000567605990102641816691459811717, q), q); o.t5 = addmod(o.t5, mulmod(i.t4, 20261355950827657195644012399234591122288573679402601053407151083849785332516, q), q); o.t5 = addmod(o.t5, mulmod(i.t5, 14514189384576734449268559374569145463190040567900950075547616936149781403109, q), q); o.t5 = addmod(o.t5, mulmod(i.t6, 19038036134886073991945204537416211699632292792787812530208911676638479944765, q), q); o.t6 = mulmod(i.t0, 15627836782263662543041758927100784213807648787083018234961118439434298020664, q); o.t6 = addmod(o.t6, mulmod(i.t1, 5655785191024506056588710805596292231240948371113351452712848652644610823632, q), q); o.t6 = addmod(o.t6, mulmod(i.t2, 8265264721707292643644260517162050867559314081394556886644673791575065394002, q), q); o.t6 = addmod(o.t6, mulmod(i.t3, 17151144681903609082202835646026478898625761142991787335302962548605510241586, q), q); o.t6 = addmod(o.t6, mulmod(i.t4, 18731644709777529787185361516475509623264209648904603914668024590231177708831, q), q); o.t6 = addmod(o.t6, mulmod(i.t5, 20697789991623248954020701081488146717484139720322034504511115160686216223641, q), q); o.t6 = addmod(o.t6, mulmod(i.t6, 6200020095464686209289974437830528853749866001482481427982839122465470640886, q), q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function ark(HashInputs7 memory i, uint q, uint c) internal pure { HashInputs7 memory o; o.t0 = addmod(i.t0, c, q); o.t1 = addmod(i.t1, c, q); o.t2 = addmod(i.t2, c, q); o.t3 = addmod(i.t3, c, q); o.t4 = addmod(i.t4, c, q); o.t5 = addmod(i.t5, c, q); o.t6 = addmod(i.t6, c, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function sbox_full(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); o.t1 = mulmod(i.t1, i.t1, q); o.t1 = mulmod(o.t1, o.t1, q); o.t1 = mulmod(i.t1, o.t1, q); o.t2 = mulmod(i.t2, i.t2, q); o.t2 = mulmod(o.t2, o.t2, q); o.t2 = mulmod(i.t2, o.t2, q); o.t3 = mulmod(i.t3, i.t3, q); o.t3 = mulmod(o.t3, o.t3, q); o.t3 = mulmod(i.t3, o.t3, q); o.t4 = mulmod(i.t4, i.t4, q); o.t4 = mulmod(o.t4, o.t4, q); o.t4 = mulmod(i.t4, o.t4, q); o.t5 = mulmod(i.t5, i.t5, q); o.t5 = mulmod(o.t5, o.t5, q); o.t5 = mulmod(i.t5, o.t5, q); o.t6 = mulmod(i.t6, i.t6, q); o.t6 = mulmod(o.t6, o.t6, q); o.t6 = mulmod(i.t6, o.t6, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function sbox_partial(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); i.t0 = o.t0; } function hash_t7f6p52(HashInputs7 memory i, uint q) internal pure returns (uint) { // validate inputs require(i.t0 < q, "INVALID_INPUT"); require(i.t1 < q, "INVALID_INPUT"); require(i.t2 < q, "INVALID_INPUT"); require(i.t3 < q, "INVALID_INPUT"); require(i.t4 < q, "INVALID_INPUT"); require(i.t5 < q, "INVALID_INPUT"); require(i.t6 < q, "INVALID_INPUT"); // round 0 ark(i, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522); sbox_full(i, q); mix(i, q); // round 1 ark(i, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128); sbox_full(i, q); mix(i, q); // round 2 ark(i, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509); sbox_full(i, q); mix(i, q); // round 3 ark(i, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615); sbox_partial(i, q); mix(i, q); // round 4 ark(i, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514); sbox_partial(i, q); mix(i, q); // round 5 ark(i, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619); sbox_partial(i, q); mix(i, q); // round 6 ark(i, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153); sbox_partial(i, q); mix(i, q); // round 7 ark(i, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608); sbox_partial(i, q); mix(i, q); // round 8 ark(i, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567); sbox_partial(i, q); mix(i, q); // round 9 ark(i, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471); sbox_partial(i, q); mix(i, q); // round 10 ark(i, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765); sbox_partial(i, q); mix(i, q); // round 11 ark(i, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772); sbox_partial(i, q); mix(i, q); // round 12 ark(i, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850); sbox_partial(i, q); mix(i, q); // round 13 ark(i, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375); sbox_partial(i, q); mix(i, q); // round 14 ark(i, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136); sbox_partial(i, q); mix(i, q); // round 15 ark(i, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374); sbox_partial(i, q); mix(i, q); // round 16 ark(i, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107); sbox_partial(i, q); mix(i, q); // round 17 ark(i, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214); sbox_partial(i, q); mix(i, q); // round 18 ark(i, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455); sbox_partial(i, q); mix(i, q); // round 19 ark(i, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212); sbox_partial(i, q); mix(i, q); // round 20 ark(i, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626); sbox_partial(i, q); mix(i, q); // round 21 ark(i, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417); sbox_partial(i, q); mix(i, q); // round 22 ark(i, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006); sbox_partial(i, q); mix(i, q); // round 23 ark(i, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766); sbox_partial(i, q); mix(i, q); // round 24 ark(i, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832); sbox_partial(i, q); mix(i, q); // round 25 ark(i, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231); sbox_partial(i, q); mix(i, q); // round 26 ark(i, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114); sbox_partial(i, q); mix(i, q); // round 27 ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719); sbox_partial(i, q); mix(i, q); // round 28 ark(i, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018); sbox_partial(i, q); mix(i, q); // round 29 ark(i, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562); sbox_partial(i, q); mix(i, q); // round 30 ark(i, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826); sbox_partial(i, q); mix(i, q); // round 31 ark(i, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245); sbox_partial(i, q); mix(i, q); // round 32 ark(i, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748); sbox_partial(i, q); mix(i, q); // round 33 ark(i, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508); sbox_partial(i, q); mix(i, q); // round 34 ark(i, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523); sbox_partial(i, q); mix(i, q); // round 35 ark(i, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410); sbox_partial(i, q); mix(i, q); // round 36 ark(i, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935); sbox_partial(i, q); mix(i, q); // round 37 ark(i, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643); sbox_partial(i, q); mix(i, q); // round 38 ark(i, q, 71447649211767888770311304010816315780740050029903404046389165015534756512); sbox_partial(i, q); mix(i, q); // round 39 ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393); sbox_partial(i, q); mix(i, q); // round 40 ark(i, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525); sbox_partial(i, q); mix(i, q); // round 41 ark(i, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006); sbox_partial(i, q); mix(i, q); // round 42 ark(i, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058); sbox_partial(i, q); mix(i, q); // round 43 ark(i, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739); sbox_partial(i, q); mix(i, q); // round 44 ark(i, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548); sbox_partial(i, q); mix(i, q); // round 45 ark(i, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311); sbox_partial(i, q); mix(i, q); // round 46 ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208); sbox_partial(i, q); mix(i, q); // round 47 ark(i, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706); sbox_partial(i, q); mix(i, q); // round 48 ark(i, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232); sbox_partial(i, q); mix(i, q); // round 49 ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524); sbox_partial(i, q); mix(i, q); // round 50 ark(i, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266); sbox_partial(i, q); mix(i, q); // round 51 ark(i, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210); sbox_partial(i, q); mix(i, q); // round 52 ark(i, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743); sbox_partial(i, q); mix(i, q); // round 53 ark(i, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373); sbox_partial(i, q); mix(i, q); // round 54 ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849); sbox_partial(i, q); mix(i, q); // round 55 ark(i, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076); sbox_full(i, q); mix(i, q); // round 56 ark(i, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047); sbox_full(i, q); mix(i, q); // round 57 ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544); sbox_full(i, q); mix(i, q); return i.t0; } } // File: contracts/core/impl/libexchange/ExchangeTokens.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeTokens. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeTokens { using MathUint for uint; using ERC20SafeTransfer for address; using ExchangeMode for ExchangeData.State; event TokenRegistered( address token, uint16 tokenId ); function getTokenAddress( ExchangeData.State storage S, uint16 tokenID ) public view returns (address) { require(tokenID < S.tokens.length, "INVALID_TOKEN_ID"); return S.tokens[tokenID].token; } function registerToken( ExchangeData.State storage S, address tokenAddress ) public returns (uint16 tokenID) { require(!S.isInWithdrawalMode(), "INVALID_MODE"); require(S.tokenToTokenId[tokenAddress] == 0, "TOKEN_ALREADY_EXIST"); require(S.tokens.length < ExchangeData.NFT_TOKEN_ID_START, "TOKEN_REGISTRY_FULL"); // Check if the deposit contract supports the new token if (S.depositContract != IDepositContract(0)) { require( S.depositContract.isTokenSupported(tokenAddress), "UNSUPPORTED_TOKEN" ); } // Assign a tokenID and store the token ExchangeData.Token memory token = ExchangeData.Token( tokenAddress ); tokenID = uint16(S.tokens.length); S.tokens.push(token); S.tokenToTokenId[tokenAddress] = tokenID + 1; emit TokenRegistered(tokenAddress, tokenID); } function getTokenID( ExchangeData.State storage S, address tokenAddress ) internal // inline call view returns (uint16 tokenID) { tokenID = S.tokenToTokenId[tokenAddress]; require(tokenID != 0, "TOKEN_NOT_FOUND"); tokenID = tokenID - 1; } function isNFT(uint16 tokenID) internal // inline call pure returns (bool) { return tokenID >= ExchangeData.NFT_TOKEN_ID_START; } } // File: contracts/core/impl/libexchange/ExchangeBalances.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeBalances. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeBalances { using ExchangeTokens for uint16; using MathUint for uint; function verifyAccountBalance( uint merkleRoot, ExchangeData.MerkleProof calldata merkleProof ) public pure { require( isAccountBalanceCorrect(merkleRoot, merkleProof), "INVALID_MERKLE_TREE_DATA" ); } function isAccountBalanceCorrect( uint merkleRoot, ExchangeData.MerkleProof memory merkleProof ) public pure returns (bool) { // Calculate the Merkle root using the Merkle paths provided uint calculatedRoot = getBalancesRoot( merkleProof.balanceLeaf.tokenID, merkleProof.balanceLeaf.balance, merkleProof.balanceLeaf.weightAMM, merkleProof.balanceLeaf.storageRoot, merkleProof.balanceMerkleProof ); calculatedRoot = getAccountInternalsRoot( merkleProof.accountLeaf.accountID, merkleProof.accountLeaf.owner, merkleProof.accountLeaf.pubKeyX, merkleProof.accountLeaf.pubKeyY, merkleProof.accountLeaf.nonce, merkleProof.accountLeaf.feeBipsAMM, calculatedRoot, merkleProof.accountMerkleProof ); if (merkleProof.balanceLeaf.tokenID.isNFT()) { // Verify the NFT data uint minter = uint(merkleProof.nft.minter); uint nftType = uint(merkleProof.nft.nftType); uint token = uint(merkleProof.nft.token); uint nftIDLo = merkleProof.nft.nftID & 0xffffffffffffffffffffffffffffffff; uint nftIDHi = merkleProof.nft.nftID >> 128; uint creatorFeeBips = merkleProof.nft.creatorFeeBips; Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7( minter, nftType, token, nftIDLo, nftIDHi, creatorFeeBips, 0 ); uint nftData = Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); if (nftData != merkleProof.balanceLeaf.weightAMM) { return false; } } // Check against the expected Merkle root return (calculatedRoot == merkleRoot); } function getBalancesRoot( uint16 tokenID, uint balance, uint weightAMM, uint storageRoot, uint[24] memory balanceMerkleProof ) private pure returns (uint) { // Hash the balance leaf uint balanceItem = hashImpl(balance, weightAMM, storageRoot, 0); // Calculate the Merkle root of the balance quad Merkle tree uint _id = tokenID; for (uint depth = 0; depth < 8; depth++) { uint base = depth * 3; if (_id & 3 == 0) { balanceItem = hashImpl( balanceItem, balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceMerkleProof[base + 2] ); } else if (_id & 3 == 1) { balanceItem = hashImpl( balanceMerkleProof[base], balanceItem, balanceMerkleProof[base + 1], balanceMerkleProof[base + 2] ); } else if (_id & 3 == 2) { balanceItem = hashImpl( balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceItem, balanceMerkleProof[base + 2] ); } else if (_id & 3 == 3) { balanceItem = hashImpl( balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceMerkleProof[base + 2], balanceItem ); } _id = _id >> 2; } return balanceItem; } function getAccountInternalsRoot( uint32 accountID, address owner, uint pubKeyX, uint pubKeyY, uint nonce, uint feeBipsAMM, uint balancesRoot, uint[48] memory accountMerkleProof ) private pure returns (uint) { // Hash the account leaf uint accountItem = hashAccountLeaf(uint(owner), pubKeyX, pubKeyY, nonce, feeBipsAMM, balancesRoot); // Calculate the Merkle root of the account quad Merkle tree uint _id = accountID; for (uint depth = 0; depth < 16; depth++) { uint base = depth * 3; if (_id & 3 == 0) { accountItem = hashImpl( accountItem, accountMerkleProof[base], accountMerkleProof[base + 1], accountMerkleProof[base + 2] ); } else if (_id & 3 == 1) { accountItem = hashImpl( accountMerkleProof[base], accountItem, accountMerkleProof[base + 1], accountMerkleProof[base + 2] ); } else if (_id & 3 == 2) { accountItem = hashImpl( accountMerkleProof[base], accountMerkleProof[base + 1], accountItem, accountMerkleProof[base + 2] ); } else if (_id & 3 == 3) { accountItem = hashImpl( accountMerkleProof[base], accountMerkleProof[base + 1], accountMerkleProof[base + 2], accountItem ); } _id = _id >> 2; } return accountItem; } function hashAccountLeaf( uint t0, uint t1, uint t2, uint t3, uint t4, uint t5 ) public pure returns (uint) { Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7(t0, t1, t2, t3, t4, t5, 0); return Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); } function hashImpl( uint t0, uint t1, uint t2, uint t3 ) private pure returns (uint) { Poseidon.HashInputs5 memory inputs = Poseidon.HashInputs5(t0, t1, t2, t3, 0); return Poseidon.hash_t5f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); } } // File: contracts/thirdparty/BytesUtil.sol //Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol library BytesUtil { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); 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) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) { require(_bytes.length >= (_start + 3)); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) { require(_bytes.length >= (_start + 4)); bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) { require(_bytes.length >= (_start + 20)); bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function toAddressUnsafe(bytes memory _bytes, uint _start) internal pure returns (address) { address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint8) { uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint16) { uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint24) { uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint32) { uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint64) { uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint96) { uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint128) { uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUintUnsafe(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes4) { bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes20) { bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes32) { bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function fastSHA256( bytes memory data ) internal view returns (bytes32) { bytes32[] memory result = new bytes32[](1); bool success; assembly { let ptr := add(data, 32) success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32) } require(success, "SHA256_FAILED"); return result[0]; } } // File: contracts/core/impl/libtransactions/BlockReader.sol // Copyright 2017 Loopring Technology Limited. /// @title BlockReader /// @author Brecht Devos - <[email protected]> /// @dev Utility library to read block data. library BlockReader { using BlockReader for ExchangeData.Block; using BytesUtil for bytes; uint public constant OFFSET_TO_TRANSACTIONS = 20 + 32 + 32 + 4 + 1 + 1 + 4 + 4; struct BlockHeader { address exchange; bytes32 merkleRootBefore; bytes32 merkleRootAfter; uint32 timestamp; uint8 protocolTakerFeeBips; uint8 protocolMakerFeeBips; uint32 numConditionalTransactions; uint32 operatorAccountID; } function readHeader( bytes memory _blockData ) internal pure returns (BlockHeader memory header) { uint offset = 0; header.exchange = _blockData.toAddress(offset); offset += 20; header.merkleRootBefore = _blockData.toBytes32(offset); offset += 32; header.merkleRootAfter = _blockData.toBytes32(offset); offset += 32; header.timestamp = _blockData.toUint32(offset); offset += 4; header.protocolTakerFeeBips = _blockData.toUint8(offset); offset += 1; header.protocolMakerFeeBips = _blockData.toUint8(offset); offset += 1; header.numConditionalTransactions = _blockData.toUint32(offset); offset += 4; header.operatorAccountID = _blockData.toUint32(offset); offset += 4; assert(offset == OFFSET_TO_TRANSACTIONS); } function readTransactionData( bytes memory data, uint txIdx, uint blockSize, bytes memory txData ) internal pure { require(txIdx < blockSize, "INVALID_TX_IDX"); // The transaction was transformed to make it easier to compress. // Transform it back here. // Part 1 uint txDataOffset = OFFSET_TO_TRANSACTIONS + txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1; assembly { mstore(add(txData, 32), mload(add(data, add(txDataOffset, 32)))) } // Part 2 txDataOffset = OFFSET_TO_TRANSACTIONS + blockSize * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1 + txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_2; assembly { mstore(add(txData, 61 /*32 + 29*/), mload(add(data, add(txDataOffset, 32)))) mstore(add(txData, 68 ), mload(add(data, add(txDataOffset, 39)))) } } } // File: contracts/thirdparty/SafeCast.sol // Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol /** * @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 uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(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 uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits"); return uint40(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/lib/FloatUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for floats /// @author Brecht Devos - <[email protected]> library FloatUtil { using MathUint for uint; using SafeCast for uint; // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits for the exponent /// @param numBits The total number of bits (numBitsMantissa := numBits - numBitsExponent) /// @return value The decoded integer value. function decodeFloat( uint f, uint numBits ) internal pure returns (uint96 value) { if (f == 0) { return 0; } uint numBitsMantissa = numBits.sub(5); uint exponent = f >> numBitsMantissa; // log2(10**77) = 255.79 < 256 require(exponent <= 77, "EXPONENT_TOO_LARGE"); uint mantissa = f & ((1 << numBitsMantissa) - 1); value = mantissa.mul(10 ** exponent).toUint96(); } // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits exponent, 11 bits mantissa /// @return value The decoded integer value. function decodeFloat16( uint16 f ) internal pure returns (uint96) { uint value = ((uint(f) & 2047) * (10 ** (uint(f) >> 11))); require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(value); } // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits exponent, 19 bits mantissa /// @return value The decoded integer value. function decodeFloat24( uint24 f ) internal pure returns (uint96) { uint value = ((uint(f) & 524287) * (10 ** (uint(f) >> 19))); require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(value); } } // File: contracts/lib/ERC1271.sol // Copyright 2017 Loopring Technology Limited. abstract contract ERC1271 { // bytes4(keccak256("isValidSignature(bytes32,bytes)") bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function isValidSignature( bytes32 _hash, bytes memory _signature) public view virtual returns (bytes4 magicValueB32); } // File: contracts/lib/SignatureUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title SignatureUtil /// @author Daniel Wang - <[email protected]> /// @dev This method supports multihash standard. Each signature's last byte indicates /// the signature's type. library SignatureUtil { using BytesUtil for bytes; using MathUint for uint; using AddressUtil for address; enum SignatureType { ILLEGAL, INVALID, EIP_712, ETH_SIGN, WALLET // deprecated } bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function verifySignatures( bytes32 signHash, address[] memory signers, bytes[] memory signatures ) internal view returns (bool) { require(signers.length == signatures.length, "BAD_SIGNATURE_DATA"); address lastSigner; for (uint i = 0; i < signers.length; i++) { require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER"); lastSigner = signers[i]; if (!verifySignature(signHash, signers[i], signatures[i])) { return false; } } return true; } function verifySignature( bytes32 signHash, address signer, bytes memory signature ) internal view returns (bool) { if (signer == address(0)) { return false; } return signer.isContract()? verifyERC1271Signature(signHash, signer, signature): verifyEOASignature(signHash, signer, signature); } function recoverECDSASigner( bytes32 signHash, bytes memory signature ) internal pure returns (address) { if (signature.length != 65) { return address(0); } bytes32 r; bytes32 s; uint8 v; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := and(mload(add(signature, 0x41)), 0xff) } // See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v == 27 || v == 28) { return ecrecover(signHash, v, r, s); } else { return address(0); } } function verifyEOASignature( bytes32 signHash, address signer, bytes memory signature ) private pure returns (bool success) { if (signer == address(0)) { return false; } uint signatureTypeOffset = signature.length.sub(1); SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset)); // Strip off the last byte of the signature by updating the length assembly { mstore(signature, signatureTypeOffset) } if (signatureType == SignatureType.EIP_712) { success = (signer == recoverECDSASigner(signHash, signature)); } else if (signatureType == SignatureType.ETH_SIGN) { bytes32 hash = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash) ); success = (signer == recoverECDSASigner(hash, signature)); } else { success = false; } // Restore the signature length assembly { mstore(signature, add(signatureTypeOffset, 1)) } return success; } function verifyERC1271Signature( bytes32 signHash, address signer, bytes memory signature ) private view returns (bool) { bytes memory callData = abi.encodeWithSelector( ERC1271.isValidSignature.selector, signHash, signature ); (bool success, bytes memory result) = signer.staticcall(callData); return ( success && result.length == 32 && result.toBytes4(0) == ERC1271_MAGICVALUE ); } } // File: contracts/core/impl/libexchange/ExchangeSignatures.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeSignatures. /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeSignatures { using SignatureUtil for bytes32; function requireAuthorizedTx( ExchangeData.State storage S, address signer, bytes memory signature, bytes32 txHash ) internal // inline call { require(signer != address(0), "INVALID_SIGNER"); // Verify the signature if one is provided, otherwise fall back to an approved tx if (signature.length > 0) { require(txHash.verifySignature(signer, signature), "INVALID_SIGNATURE"); } else { require(S.approvedTx[signer][txHash], "TX_NOT_APPROVED"); delete S.approvedTx[signer][txHash]; } } } // File: contracts/core/impl/libtransactions/AccountUpdateTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title AccountUpdateTransaction /// @author Brecht Devos - <[email protected]> library AccountUpdateTransaction { using BytesUtil for bytes; using FloatUtil for uint16; using ExchangeSignatures for ExchangeData.State; bytes32 constant public ACCOUNTUPDATE_TYPEHASH = keccak256( "AccountUpdate(address owner,uint32 accountID,uint16 feeTokenID,uint96 maxFee,uint256 publicKey,uint32 validUntil,uint32 nonce)" ); struct AccountUpdate { address owner; uint32 accountID; uint16 feeTokenID; uint96 maxFee; uint96 fee; uint publicKey; uint32 validUntil; uint32 nonce; } // Auxiliary data for each account update struct AccountUpdateAuxiliaryData { bytes signature; uint96 maxFee; uint32 validUntil; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory ctx, bytes memory data, uint offset, bytes memory auxiliaryData ) internal { // Read the account update AccountUpdate memory accountUpdate; readTx(data, offset, accountUpdate); AccountUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AccountUpdateAuxiliaryData)); // Fill in withdrawal data missing from DA accountUpdate.validUntil = auxData.validUntil; accountUpdate.maxFee = auxData.maxFee == 0 ? accountUpdate.fee : auxData.maxFee; // Validate require(ctx.timestamp < accountUpdate.validUntil, "ACCOUNT_UPDATE_EXPIRED"); require(accountUpdate.fee <= accountUpdate.maxFee, "ACCOUNT_UPDATE_FEE_TOO_HIGH"); // Calculate the tx hash bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, accountUpdate); // Check onchain authorization S.requireAuthorizedTx(accountUpdate.owner, auxData.signature, txHash); } function readTx( bytes memory data, uint offset, AccountUpdate memory accountUpdate ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.ACCOUNT_UPDATE), "INVALID_TX_TYPE"); _offset += 1; // Check that this is a conditional offset require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA"); _offset += 1; // Extract the data from the tx data // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. accountUpdate.owner = data.toAddressUnsafe(_offset); _offset += 20; accountUpdate.accountID = data.toUint32Unsafe(_offset); _offset += 4; accountUpdate.feeTokenID = data.toUint16Unsafe(_offset); _offset += 2; accountUpdate.fee = data.toUint16Unsafe(_offset).decodeFloat16(); _offset += 2; accountUpdate.publicKey = data.toUintUnsafe(_offset); _offset += 32; accountUpdate.nonce = data.toUint32Unsafe(_offset); _offset += 4; } function hashTx( bytes32 DOMAIN_SEPARATOR, AccountUpdate memory accountUpdate ) internal pure returns (bytes32) { return EIP712.hashPacked( DOMAIN_SEPARATOR, keccak256( abi.encode( ACCOUNTUPDATE_TYPEHASH, accountUpdate.owner, accountUpdate.accountID, accountUpdate.feeTokenID, accountUpdate.maxFee, accountUpdate.publicKey, accountUpdate.validUntil, accountUpdate.nonce ) ) ); } } // File: contracts/core/impl/libtransactions/AmmUpdateTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title AmmUpdateTransaction /// @author Brecht Devos - <[email protected]> library AmmUpdateTransaction { using BytesUtil for bytes; using MathUint for uint; using ExchangeSignatures for ExchangeData.State; bytes32 constant public AMMUPDATE_TYPEHASH = keccak256( "AmmUpdate(address owner,uint32 accountID,uint16 tokenID,uint8 feeBips,uint96 tokenWeight,uint32 validUntil,uint32 nonce)" ); struct AmmUpdate { address owner; uint32 accountID; uint16 tokenID; uint8 feeBips; uint96 tokenWeight; uint32 validUntil; uint32 nonce; uint96 balance; } // Auxiliary data for each AMM update struct AmmUpdateAuxiliaryData { bytes signature; uint32 validUntil; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory ctx, bytes memory data, uint offset, bytes memory auxiliaryData ) internal { // Read in the AMM update AmmUpdate memory update; readTx(data, offset, update); AmmUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AmmUpdateAuxiliaryData)); // Check validUntil require(ctx.timestamp < auxData.validUntil, "AMM_UPDATE_EXPIRED"); update.validUntil = auxData.validUntil; // Calculate the tx hash bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, update); // Check the on-chain authorization S.requireAuthorizedTx(update.owner, auxData.signature, txHash); } function readTx( bytes memory data, uint offset, AmmUpdate memory update ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.AMM_UPDATE), "INVALID_TX_TYPE"); _offset += 1; // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. update.owner = data.toAddressUnsafe(_offset); _offset += 20; update.accountID = data.toUint32Unsafe(_offset); _offset += 4; update.tokenID = data.toUint16Unsafe(_offset); _offset += 2; update.feeBips = data.toUint8Unsafe(_offset); _offset += 1; update.tokenWeight = data.toUint96Unsafe(_offset); _offset += 12; update.nonce = data.toUint32Unsafe(_offset); _offset += 4; update.balance = data.toUint96Unsafe(_offset); _offset += 12; } function hashTx( bytes32 DOMAIN_SEPARATOR, AmmUpdate memory update ) internal pure returns (bytes32) { return EIP712.hashPacked( DOMAIN_SEPARATOR, keccak256( abi.encode( AMMUPDATE_TYPEHASH, update.owner, update.accountID, update.tokenID, update.feeBips, update.tokenWeight, update.validUntil, update.nonce ) ) ); } } // File: contracts/lib/MathUint96.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint96 { function add( uint96 a, uint96 b ) internal pure returns (uint96 c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } function sub( uint96 a, uint96 b ) internal pure returns (uint96 c) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } } // File: contracts/core/impl/libtransactions/DepositTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title DepositTransaction /// @author Brecht Devos - <[email protected]> library DepositTransaction { using BytesUtil for bytes; using MathUint96 for uint96; struct Deposit { address to; uint32 toAccountID; uint16 tokenID; uint96 amount; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory /*ctx*/, bytes memory data, uint offset, bytes memory /*auxiliaryData*/ ) internal { // Read in the deposit Deposit memory deposit; readTx(data, offset, deposit); if (deposit.amount == 0) { return; } // Process the deposit ExchangeData.Deposit memory pendingDeposit = S.pendingDeposits[deposit.to][deposit.tokenID]; // Make sure the deposit was actually done require(pendingDeposit.timestamp > 0, "DEPOSIT_NOT_EXIST"); // Processing partial amounts of the deposited amount is allowed. // This is done to ensure the user can do multiple deposits after each other // without invalidating work done by the exchange owner for previous deposit amounts. require(pendingDeposit.amount >= deposit.amount, "INVALID_AMOUNT"); pendingDeposit.amount = pendingDeposit.amount.sub(deposit.amount); // If the deposit was fully consumed, reset it so the storage is freed up // and the owner receives a gas refund. if (pendingDeposit.amount == 0) { delete S.pendingDeposits[deposit.to][deposit.tokenID]; } else { S.pendingDeposits[deposit.to][deposit.tokenID] = pendingDeposit; } } function readTx( bytes memory data, uint offset, Deposit memory deposit ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.DEPOSIT), "INVALID_TX_TYPE"); _offset += 1; // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. deposit.to = data.toAddressUnsafe(_offset); _offset += 20; deposit.toAccountID = data.toUint32Unsafe(_offset); _offset += 4; deposit.tokenID = data.toUint16Unsafe(_offset); _offset += 2; deposit.amount = data.toUint96Unsafe(_offset); _offset += 12; } } // File: contracts/core/impl/libtransactions/TransferTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title TransferTransaction /// @author Brecht Devos - <[email protected]> library TransferTransaction { using BytesUtil for bytes; using FloatUtil for uint24; using FloatUtil for uint16; using MathUint for uint; using ExchangeSignatures for ExchangeData.State; bytes32 constant public TRANSFER_TYPEHASH = keccak256( "Transfer(address from,address to,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,uint32 validUntil,uint32 storageID)" ); struct Transfer { uint32 fromAccountID; uint32 toAccountID; address from; address to; uint16 tokenID; uint96 amount; uint16 feeTokenID; uint96 maxFee; uint96 fee; uint32 validUntil; uint32 storageID; } // Auxiliary data for each transfer struct TransferAuxiliaryData { bytes signature; uint96 maxFee; uint32 validUntil; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory ctx, bytes memory data, uint offset, bytes memory auxiliaryData ) internal { // Read the transfer Transfer memory transfer; readTx(data, offset, transfer); TransferAuxiliaryData memory auxData = abi.decode(auxiliaryData, (TransferAuxiliaryData)); // Fill in withdrawal data missing from DA transfer.validUntil = auxData.validUntil; transfer.maxFee = auxData.maxFee == 0 ? transfer.fee : auxData.maxFee; // Validate require(ctx.timestamp < transfer.validUntil, "TRANSFER_EXPIRED"); require(transfer.fee <= transfer.maxFee, "TRANSFER_FEE_TOO_HIGH"); // Calculate the tx hash bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, transfer); // Check the on-chain authorization S.requireAuthorizedTx(transfer.from, auxData.signature, txHash); } function readTx( bytes memory data, uint offset, Transfer memory transfer ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.TRANSFER), "INVALID_TX_TYPE"); _offset += 1; // Check that this is a conditional transfer require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA"); _offset += 1; // Extract the transfer data // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. transfer.fromAccountID = data.toUint32Unsafe(_offset); _offset += 4; transfer.toAccountID = data.toUint32Unsafe(_offset); _offset += 4; transfer.tokenID = data.toUint16Unsafe(_offset); _offset += 2; transfer.amount = data.toUint24Unsafe(_offset).decodeFloat24(); _offset += 3; transfer.feeTokenID = data.toUint16Unsafe(_offset); _offset += 2; transfer.fee = data.toUint16Unsafe(_offset).decodeFloat16(); _offset += 2; transfer.storageID = data.toUint32Unsafe(_offset); _offset += 4; transfer.to = data.toAddressUnsafe(_offset); _offset += 20; transfer.from = data.toAddressUnsafe(_offset); _offset += 20; } function hashTx( bytes32 DOMAIN_SEPARATOR, Transfer memory transfer ) internal pure returns (bytes32) { return EIP712.hashPacked( DOMAIN_SEPARATOR, keccak256( abi.encode( TRANSFER_TYPEHASH, transfer.from, transfer.to, transfer.tokenID, transfer.amount, transfer.feeTokenID, transfer.maxFee, transfer.validUntil, transfer.storageID ) ) ); } } // File: contracts/core/iface/IL2MintableNFT.sol // Copyright 2017 Loopring Technology Limited. interface IL2MintableNFT { /// @dev This function is called when an NFT minted on L2 is withdrawn from Loopring. /// That means the NFTs were burned on L2 and now need to be minted on L1. /// /// This function can only be called by the Loopring exchange. /// /// @param to The owner of the NFT /// @param tokenId The token type 'id` /// @param amount The amount of NFTs to mint /// @param minter The minter on L2, which can be used to decide if the NFT is authentic /// @param data Opaque data that can be used by the contract function mintFromL2( address to, uint256 tokenId, uint amount, address minter, bytes calldata data ) external; /// @dev Returns a list of all address that are authorized to mint NFTs on L2. /// @return The list of authorized minter on L2 function minters() external view returns (address[] memory); } // File: contracts/thirdparty/erc165/IERC165.sol /** * @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); } // File: contracts/thirdparty/erc165/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: contracts/thirdparty/erc1155/IERC1155.sol /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // File: contracts/thirdparty/erc721/IERC721.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; } // File: contracts/core/impl/libexchange/ExchangeNFT.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeNFT /// @author Brecht Devos - <[email protected]> library ExchangeNFT { using ExchangeNFT for ExchangeData.State; function deposit( ExchangeData.State storage S, address from, ExchangeData.NftType nftType, address token, uint256 nftID, uint amount, bytes memory extraData ) internal { if (amount == 0) { return; } // Disable calls to certain contracts require(S.isTokenAddressAllowed(token), "TOKEN_ADDRESS_NOT_ALLOWED"); if (nftType == ExchangeData.NftType.ERC1155) { IERC1155(token).safeTransferFrom( from, address(this), nftID, amount, extraData ); } else if (nftType == ExchangeData.NftType.ERC721) { require(amount == 1, "INVALID_AMOUNT"); IERC721(token).safeTransferFrom( from, address(this), nftID, extraData ); } else { revert("UNKNOWN_NFTTYPE"); } } function withdraw( ExchangeData.State storage S, address /*from*/, address to, ExchangeData.NftType nftType, address token, uint256 nftID, uint amount, bytes memory extraData, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } // Disable calls to certain contracts if(!S.isTokenAddressAllowed(token)) { return false; } if (nftType == ExchangeData.NftType.ERC1155) { try IERC1155(token).safeTransferFrom{gas: gasLimit}( address(this), to, nftID, amount, extraData ) { success = true; } catch { success = false; } } else if (nftType == ExchangeData.NftType.ERC721) { try IERC721(token).safeTransferFrom{gas: gasLimit}( address(this), to, nftID, extraData ) { success = true; } catch { success = false; } } else { revert("UNKNOWN_NFTTYPE"); } } function mintFromL2( ExchangeData.State storage S, address to, address token, uint256 nftID, uint amount, address minter, bytes memory extraData, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } // Disable calls to certain contracts if(!S.isTokenAddressAllowed(token)) { return false; } try IL2MintableNFT(token).mintFromL2{gas: gasLimit}( to, nftID, amount, minter, extraData ) { success = true; } catch { success = false; } } function isTokenAddressAllowed( ExchangeData.State storage S, address token ) internal view returns (bool valid) { return (token != address(this) && token != address(S.depositContract)); } } // File: contracts/core/impl/libexchange/ExchangeWithdrawals.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeWithdrawals. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeWithdrawals { enum WithdrawalCategory { DISTRIBUTION, FROM_MERKLE_TREE, FROM_DEPOSIT_REQUEST, FROM_APPROVED_WITHDRAWAL } using AddressUtil for address; using AddressUtil for address payable; using BytesUtil for bytes; using MathUint for uint; using ExchangeBalances for ExchangeData.State; using ExchangeMode for ExchangeData.State; using ExchangeTokens for ExchangeData.State; using ExchangeTokens for uint16; event ForcedWithdrawalRequested( address owner, uint16 tokenID, // ERC20 token ID ( if < NFT_TOKEN_ID_START) or // NFT balance slot (if >= NFT_TOKEN_ID_START) uint32 accountID ); event WithdrawalCompleted( uint8 category, address from, address to, address token, uint amount ); event WithdrawalFailed( uint8 category, address from, address to, address token, uint amount ); event NftWithdrawalCompleted( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); event NftWithdrawalFailed( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); function forceWithdraw( ExchangeData.State storage S, address owner, uint16 tokenID, // ERC20 token ID ( if < NFT_TOKEN_ID_START) or // NFT balance slot (if >= NFT_TOKEN_ID_START) uint32 accountID ) public { require(!S.isInWithdrawalMode(), "INVALID_MODE"); // Limit the amount of pending forced withdrawals so that the owner cannot be overwhelmed. require(S.getNumAvailableForcedSlots() > 0, "TOO_MANY_REQUESTS_OPEN"); require(accountID < ExchangeData.MAX_NUM_ACCOUNTS, "INVALID_ACCOUNTID"); // Only allow withdrawing from registered ERC20 tokens or NFT tokenIDs require( tokenID < S.tokens.length || // ERC20 tokenID.isNFT(), // NFT "INVALID_TOKENID" ); // A user needs to pay a fixed ETH withdrawal fee, set by the protocol. uint withdrawalFeeETH = S.loopring.forcedWithdrawalFee(); // Check ETH value sent, can be larger than the expected withdraw fee require(msg.value >= withdrawalFeeETH, "INSUFFICIENT_FEE"); // Send surplus of ETH back to the sender uint feeSurplus = msg.value.sub(withdrawalFeeETH); if (feeSurplus > 0) { msg.sender.sendETHAndVerify(feeSurplus, gasleft()); } // There can only be a single forced withdrawal per (account, token) pair. require( S.pendingForcedWithdrawals[accountID][tokenID].timestamp == 0, "WITHDRAWAL_ALREADY_PENDING" ); // Store the forced withdrawal request data S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({ owner: owner, timestamp: uint64(block.timestamp) }); // Increment the number of pending forced transactions so we can keep count. S.numPendingForcedTransactions++; emit ForcedWithdrawalRequested( owner, tokenID, accountID ); } // We alow anyone to withdraw these funds for the account owner function withdrawFromMerkleTree( ExchangeData.State storage S, ExchangeData.MerkleProof calldata merkleProof ) public { require(S.isInWithdrawalMode(), "NOT_IN_WITHDRAW_MODE"); address owner = merkleProof.accountLeaf.owner; uint32 accountID = merkleProof.accountLeaf.accountID; uint16 tokenID = merkleProof.balanceLeaf.tokenID; uint96 balance = merkleProof.balanceLeaf.balance; // Make sure the funds aren't withdrawn already. require(S.withdrawnInWithdrawMode[accountID][tokenID] == false, "WITHDRAWN_ALREADY"); // Verify that the provided Merkle tree data is valid by using the Merkle proof. ExchangeBalances.verifyAccountBalance( uint(S.merkleRoot), merkleProof ); // Make sure the balance can only be withdrawn once S.withdrawnInWithdrawMode[accountID][tokenID] = true; if (!tokenID.isNFT()) { require( merkleProof.nft.nftID == 0 && merkleProof.nft.minter == address(0), "NOT_AN_NFT" ); // Transfer the tokens to the account owner transferTokens( S, uint8(WithdrawalCategory.FROM_MERKLE_TREE), owner, owner, tokenID, balance, new bytes(0), gasleft(), false ); } else { transferNFTs( S, uint8(WithdrawalCategory.DISTRIBUTION), owner, owner, tokenID, balance, merkleProof.nft, new bytes(0), gasleft(), false ); } } function withdrawFromDepositRequest( ExchangeData.State storage S, address owner, address token ) public { uint16 tokenID = S.getTokenID(token); ExchangeData.Deposit storage deposit = S.pendingDeposits[owner][tokenID]; require(deposit.timestamp != 0, "DEPOSIT_NOT_WITHDRAWABLE_YET"); // Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode require( block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable || S.isInWithdrawalMode(), "DEPOSIT_NOT_WITHDRAWABLE_YET" ); uint amount = deposit.amount; // Reset the deposit request delete S.pendingDeposits[owner][tokenID]; // Transfer the tokens transferTokens( S, uint8(WithdrawalCategory.FROM_DEPOSIT_REQUEST), owner, owner, tokenID, amount, new bytes(0), gasleft(), false ); } function withdrawFromNFTDepositRequest( ExchangeData.State storage S, address owner, address token, ExchangeData.NftType nftType, uint256 nftID ) public { ExchangeData.Deposit storage deposit = S.pendingNFTDeposits[owner][nftType][token][nftID]; require(deposit.timestamp != 0, "DEPOSIT_NOT_WITHDRAWABLE_YET"); // Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode require( block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable || S.isInWithdrawalMode(), "DEPOSIT_NOT_WITHDRAWABLE_YET" ); uint amount = deposit.amount; // Reset the deposit request delete S.pendingNFTDeposits[owner][nftType][token][nftID]; ExchangeData.Nft memory nft = ExchangeData.Nft({ minter: token, nftType: nftType, token: token, nftID: nftID, creatorFeeBips: 0 }); // Transfer the NFTs transferNFTs( S, uint8(WithdrawalCategory.FROM_DEPOSIT_REQUEST), owner, owner, 0, amount, nft, new bytes(0), gasleft(), false ); } function withdrawFromApprovedWithdrawals( ExchangeData.State storage S, address[] memory owners, address[] memory tokens ) public { require(owners.length == tokens.length, "INVALID_INPUT_DATA"); for (uint i = 0; i < owners.length; i++) { address owner = owners[i]; uint16 tokenID = S.getTokenID(tokens[i]); uint amount = S.amountWithdrawable[owner][tokenID]; // Make sure this amount can't be withdrawn again delete S.amountWithdrawable[owner][tokenID]; // Transfer the tokens to the owner transferTokens( S, uint8(WithdrawalCategory.FROM_APPROVED_WITHDRAWAL), owner, owner, tokenID, amount, new bytes(0), gasleft(), false ); } } function withdrawFromApprovedWithdrawalsNFT( ExchangeData.State storage S, address[] memory owners, address[] memory minters, ExchangeData.NftType[] memory nftTypes, address[] memory tokens, uint256[] memory nftIDs ) public { require(owners.length == minters.length, "INVALID_INPUT_DATA_MINTERS"); require(owners.length == nftTypes.length, "INVALID_INPUT_DATA_NFTTYPES"); require(owners.length == tokens.length, "INVALID_INPUT_DATA_TOKENS"); require(owners.length == nftIDs.length, "INVALID_INPUT_DATA_CONTENT_URIS"); for (uint i = 0; i < owners.length; i++) { address owner = owners[i]; address minter = minters[i]; ExchangeData.NftType nftType = nftTypes[i]; address token = tokens[i]; uint256 nftID = nftIDs[i]; uint amount = S.amountWithdrawableNFT[owner][minter][nftType][token][nftID]; // Make sure this amount can't be withdrawn again delete S.amountWithdrawableNFT[owner][minter][nftType][token][nftID]; ExchangeData.Nft memory nft = ExchangeData.Nft({ minter: minter, nftType: nftType, token: token, nftID: nftID, creatorFeeBips: 0 }); // Transfer the NFTs to the owner transferNFTs( S, uint8(WithdrawalCategory.DISTRIBUTION), owner, owner, 0, amount, nft, new bytes(0), gasleft(), false ); } } function distributeWithdrawal( ExchangeData.State storage S, address from, address to, uint16 tokenID, uint amount, bytes memory extraData, uint gasLimit, ExchangeData.Nft memory nft ) public { if (!tokenID.isNFT()) { // Try to transfer the tokens if (!transferTokens( S, uint8(WithdrawalCategory.DISTRIBUTION), from, to, tokenID, amount, extraData, gasLimit, true )) { // If the transfer was successful there's nothing left to do. // However, if the transfer failed the tokens are still in the contract and can be // withdrawn later to `to` by anyone by using `withdrawFromApprovedWithdrawal. S.amountWithdrawable[to][tokenID] = S.amountWithdrawable[to][tokenID].add(amount); } } else { // Try to transfer the tokens if (!transferNFTs( S, uint8(WithdrawalCategory.DISTRIBUTION), from, to, tokenID, amount, nft, extraData, gasLimit, true )) { // If the transfer was successful there's nothing left to do. // However, if the transfer failed the tokens are still in the contract and can be // withdrawn later to `to` by anyone by using `withdrawFromApprovedNftWithdrawal. S.amountWithdrawableNFT[to][nft.minter][nft.nftType][nft.token][nft.nftID] = S.amountWithdrawableNFT[to][nft.minter][nft.nftType][nft.token][nft.nftID].add(amount); } } } // == Internal and Private Functions == // If allowFailure is true the transfer can fail because of a transfer error or // because the transfer uses more than `gasLimit` gas. The function // will return true when successful, false otherwise. // If allowFailure is false the transfer is guaranteed to succeed using // as much gas as needed, otherwise it throws. The function always returns true. function transferTokens( ExchangeData.State storage S, uint8 category, address from, address to, uint16 tokenID, uint amount, bytes memory extraData, uint gasLimit, bool allowFailure ) private returns (bool success) { // Redirect withdrawals to address(0) to the protocol fee vault if (to == address(0)) { to = S.loopring.protocolFeeVault(); } address token = S.getTokenAddress(tokenID); // Transfer the tokens from the deposit contract to the owner if (gasLimit > 0) { try S.depositContract.withdraw{gas: gasLimit}(from, to, token, amount, extraData) { success = true; } catch { success = false; } } else { success = false; } require(allowFailure || success, "TRANSFER_FAILURE"); if (success) { emit WithdrawalCompleted(category, from, to, token, amount); // Keep track of when the protocol fees were last withdrawn // (only done to make this data easier available). if (from == address(0)) { S.protocolFeeLastWithdrawnTime[token] = block.timestamp; } } else { emit WithdrawalFailed(category, from, to, token, amount); } } // If allowFailure is true the transfer can fail because of a transfer error or // because the transfer uses more than `gasLimit` gas. The function // will return true when successful, false otherwise. // If allowFailure is false the transfer is guaranteed to succeed using // as much gas as needed, otherwise it throws. The function always returns true. function transferNFTs( ExchangeData.State storage S, uint8 category, address from, address to, uint16 tokenID, uint amount, ExchangeData.Nft memory nft, bytes memory extraData, uint gasLimit, bool allowFailure ) private returns (bool success) { if (nft.token == nft.minter) { // This is an existing thirdparty NFT contract success = ExchangeNFT.withdraw( S, from, to, nft.nftType, nft.token, nft.nftID, amount, extraData, gasLimit ); } else { // This is an inhouse NFT contract with L2 minting support success = ExchangeNFT.mintFromL2( S, to, nft.token, nft.nftID, amount, nft.minter, extraData, gasLimit ); } require(allowFailure || success, "NFT_TRANSFER_FAILURE"); if (success) { emit NftWithdrawalCompleted(category, from, to, tokenID, nft.token, nft.nftID, amount); } else { emit NftWithdrawalFailed(category, from, to, tokenID, nft.token, nft.nftID, amount); } } } // File: contracts/core/impl/libtransactions/NftDataTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title NftDataTransaction /// @author Brecht Devos - <[email protected]> library NftDataTransaction { using BlockReader for bytes; using BytesUtil for bytes; // Read the data in two transactions, each containing partial data. // Each tx contains largely the same data (`nftID`, `nftType`, `creatorFeeBips`) // except when // type == SCHEME_WITH_TOKEN_ADDRESS -> bring `tokenAddress` to L1, // type == SCHEME_WITH_MINTER_ADDRESS -> bring `minter` to L1. enum NftDataScheme { SCHEME_WITH_MINTER_ADDRESS, SCHEME_WITH_TOKEN_ADDRESS } struct NftData { uint8 scheme; uint32 accountID; // the `to` or `from` account's ID. uint16 tokenID; ExchangeData.Nft nft; } function readTx( bytes memory data, uint offset, NftData memory nftData ) internal pure { uint _offset = offset; require( data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.NFT_DATA), "INVALID_TX_TYPE" ); _offset += 1; nftData.scheme = data.toUint8Unsafe(_offset); _offset += 1; // Extract the transfer data // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. nftData.accountID = data.toUint32Unsafe(_offset); _offset += 4; nftData.tokenID = data.toUint16Unsafe(_offset); _offset += 2; nftData.nft.nftID = data.toUintUnsafe(_offset); _offset += 32; nftData.nft.creatorFeeBips = data.toUint8Unsafe(_offset); _offset += 1; nftData.nft.nftType = ExchangeData.NftType(data.toUint8Unsafe(_offset)); _offset += 1; if (nftData.scheme == uint8(NftDataScheme.SCHEME_WITH_MINTER_ADDRESS)) { nftData.nft.minter = data.toAddressUnsafe(_offset); } else if (nftData.scheme == uint8(NftDataScheme.SCHEME_WITH_TOKEN_ADDRESS)) { nftData.nft.token = data.toAddressUnsafe(_offset); } else { revert("INVALID_NFT_DATA_SUBTYPE"); } _offset += 20; } function readDualNftData( ExchangeData.BlockContext memory ctx, uint32 accountID, uint16 tokenID, uint txIdx, NftDataTransaction.NftData memory nftData ) internal pure { // There's 68 bytes we can use per transaction. The NFT data now contains // `hash(minter, nftType, tokenAddress, nftID, creatorFeeBips)`. So this data // needs txType + (1 byte) + minter (20 bytes) + nftType (1 byte) + // tokenAddress (20 bytes) + nftID (32 bytes) + creatorFeeBips (1 byte) = 76 bytes. // So 8 bytes too much to fit inside the available space in a single tx. readNftData( ctx, accountID, tokenID, txIdx, NftDataScheme.SCHEME_WITH_MINTER_ADDRESS, nftData ); readNftData( ctx, accountID, tokenID, txIdx + 1, NftDataScheme.SCHEME_WITH_TOKEN_ADDRESS, nftData ); } function readNftData( ExchangeData.BlockContext memory ctx, uint32 accountID, uint16 tokenID, uint txOffset, NftDataScheme expectedScheme, NftDataTransaction.NftData memory nftData ) private pure { // Read the NFT_DATA transaction bytes memory txData = new bytes(ExchangeData.TX_DATA_AVAILABILITY_SIZE); ctx.block.data.readTransactionData(txOffset, ctx.block.blockSize, txData); NftDataTransaction.readTx(txData, 0, nftData); // Make sure the NFT_DATA transaction pushes data on-chain // that matches the the tokens that are getting withdrawn require( nftData.scheme == uint8(expectedScheme) && nftData.accountID == accountID && nftData.tokenID == tokenID, "INVALID_NFT_DATA" ); } } // File: contracts/core/impl/libtransactions/WithdrawTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title WithdrawTransaction /// @author Brecht Devos - <[email protected]> /// @dev The following 4 types of withdrawals are supported: /// - withdrawType = 0: offchain withdrawals with EdDSA signatures /// - withdrawType = 1: offchain withdrawals with ECDSA signatures or onchain appprovals /// - withdrawType = 2: onchain valid forced withdrawals (owner and accountID match), or /// offchain operator-initiated withdrawals for protocol fees or for /// users in shutdown mode /// - withdrawType = 3: onchain invalid forced withdrawals (owner and accountID mismatch) library WithdrawTransaction { using BlockReader for bytes; using BytesUtil for bytes; using FloatUtil for uint16; using MathUint for uint; using ExchangeMode for ExchangeData.State; using ExchangeSignatures for ExchangeData.State; using ExchangeTokens for uint16; using ExchangeWithdrawals for ExchangeData.State; bytes32 constant public WITHDRAWAL_TYPEHASH = keccak256( "Withdrawal(address owner,uint32 accountID,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,address to,bytes extraData,uint256 minGas,uint32 validUntil,uint32 storageID)" ); struct Withdrawal { uint withdrawalType; address from; uint32 fromAccountID; uint16 tokenID; uint96 amount; uint16 feeTokenID; uint96 maxFee; uint96 fee; address to; bytes extraData; uint minGas; uint32 validUntil; uint32 storageID; bytes20 onchainDataHash; } // Auxiliary data for each withdrawal struct WithdrawalAuxiliaryData { bool storeRecipient; uint gasLimit; bytes signature; uint minGas; address to; bytes extraData; uint96 maxFee; uint32 validUntil; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory ctx, bytes memory data, uint offset, bytes memory auxiliaryData ) internal { Withdrawal memory withdrawal; readTx(data, offset, withdrawal); // Read the NFT data if we're withdrawing an NFT NftDataTransaction.NftData memory nftData; if (withdrawal.tokenID.isNFT() && withdrawal.amount > 0) { NftDataTransaction.readDualNftData( ctx, withdrawal.fromAccountID, withdrawal.tokenID, ctx.txIndex.sub(2), nftData ); } WithdrawalAuxiliaryData memory auxData = abi.decode(auxiliaryData, (WithdrawalAuxiliaryData)); // Validate the withdrawal data not directly part of the DA bytes20 onchainDataHash = hashOnchainData( auxData.minGas, auxData.to, auxData.extraData ); // Only the 20 MSB are used, which is still 80-bit of security, which is more // than enough, especially when combined with validUntil. require(withdrawal.onchainDataHash == onchainDataHash, "INVALID_WITHDRAWAL_DATA"); // Fill in withdrawal data missing from DA withdrawal.to = auxData.to; withdrawal.minGas = auxData.minGas; withdrawal.extraData = auxData.extraData; withdrawal.maxFee = auxData.maxFee == 0 ? withdrawal.fee : auxData.maxFee; withdrawal.validUntil = auxData.validUntil; // If the account has an owner, don't allow withdrawing to the zero address // (which will be the protocol fee vault contract). require(withdrawal.from == address(0) || withdrawal.to != address(0), "INVALID_WITHDRAWAL_RECIPIENT"); if (withdrawal.withdrawalType == 0) { // Signature checked offchain, nothing to do } else if (withdrawal.withdrawalType == 1) { // Validate require(ctx.timestamp < withdrawal.validUntil, "WITHDRAWAL_EXPIRED"); require(withdrawal.fee <= withdrawal.maxFee, "WITHDRAWAL_FEE_TOO_HIGH"); // Check appproval onchain // Calculate the tx hash bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, withdrawal); // Check onchain authorization S.requireAuthorizedTx(withdrawal.from, auxData.signature, txHash); } else if (withdrawal.withdrawalType == 2 || withdrawal.withdrawalType == 3) { // Forced withdrawals cannot make use of certain features because the // necessary data is not authorized by the account owner. // For protocol fee withdrawals, `owner` and `to` are both address(0). require(withdrawal.from == withdrawal.to, "INVALID_WITHDRAWAL_ADDRESS"); // Forced withdrawal fees are charged when the request is submitted. require(withdrawal.fee == 0, "FEE_NOT_ZERO"); require(withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED"); ExchangeData.ForcedWithdrawal memory forcedWithdrawal = S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID]; if (forcedWithdrawal.timestamp != 0) { if (withdrawal.withdrawalType == 2) { require(withdrawal.from == forcedWithdrawal.owner, "INCONSISENT_OWNER"); } else { //withdrawal.withdrawalType == 3 require(withdrawal.from != forcedWithdrawal.owner, "INCONSISENT_OWNER"); require(withdrawal.amount == 0, "UNAUTHORIZED_WITHDRAWAL"); } // delete the withdrawal request and free a slot delete S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID]; S.numPendingForcedTransactions--; } else { // Allow the owner to submit full withdrawals without authorization // - when in shutdown mode // - to withdraw protocol fees require( withdrawal.fromAccountID == ExchangeData.ACCOUNTID_PROTOCOLFEE || S.isShutdown(), "FULL_WITHDRAWAL_UNAUTHORIZED" ); } } else { revert("INVALID_WITHDRAWAL_TYPE"); } // Check if there is a withdrawal recipient address recipient = S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID]; if (recipient != address(0)) { // Auxiliary data is not supported require (withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED"); // Set the new recipient address withdrawal.to = recipient; // Allow any amount of gas to be used on this withdrawal (which allows the transfer to be skipped) withdrawal.minGas = 0; // Do NOT delete the recipient to prevent replay attack // delete S.withdrawalRecipient[withdrawal.owner][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID]; } else if (auxData.storeRecipient) { // Store the destination address to mark the withdrawal as done require(withdrawal.to != address(0), "INVALID_DESTINATION_ADDRESS"); S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID] = withdrawal.to; } // Validate gas provided require(auxData.gasLimit >= withdrawal.minGas, "OUT_OF_GAS_FOR_WITHDRAWAL"); // Try to transfer the tokens with the provided gas limit S.distributeWithdrawal( withdrawal.from, withdrawal.to, withdrawal.tokenID, withdrawal.amount, withdrawal.extraData, auxData.gasLimit, nftData.nft ); } function readTx( bytes memory data, uint offset, Withdrawal memory withdrawal ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.WITHDRAWAL), "INVALID_TX_TYPE"); _offset += 1; // Extract the transfer data // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. withdrawal.withdrawalType = data.toUint8Unsafe(_offset); _offset += 1; withdrawal.from = data.toAddressUnsafe(_offset); _offset += 20; withdrawal.fromAccountID = data.toUint32Unsafe(_offset); _offset += 4; withdrawal.tokenID = data.toUint16Unsafe(_offset); _offset += 2; withdrawal.amount = data.toUint96Unsafe(_offset); _offset += 12; withdrawal.feeTokenID = data.toUint16Unsafe(_offset); _offset += 2; withdrawal.fee = data.toUint16Unsafe(_offset).decodeFloat16(); _offset += 2; withdrawal.storageID = data.toUint32Unsafe(_offset); _offset += 4; withdrawal.onchainDataHash = data.toBytes20Unsafe(_offset); _offset += 20; } function hashTx( bytes32 DOMAIN_SEPARATOR, Withdrawal memory withdrawal ) internal pure returns (bytes32) { return EIP712.hashPacked( DOMAIN_SEPARATOR, keccak256( abi.encode( WITHDRAWAL_TYPEHASH, withdrawal.from, withdrawal.fromAccountID, withdrawal.tokenID, withdrawal.amount, withdrawal.feeTokenID, withdrawal.maxFee, withdrawal.to, keccak256(withdrawal.extraData), withdrawal.minGas, withdrawal.validUntil, withdrawal.storageID ) ) ); } function hashOnchainData( uint minGas, address to, bytes memory extraData ) internal pure returns (bytes20) { // Only the 20 MSB are used, which is still 80-bit of security, which is more // than enough, especially when combined with validUntil. return bytes20(keccak256( abi.encodePacked( minGas, to, extraData ) )); } } // File: contracts/core/impl/libtransactions/NftMintTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title NftMintTransaction /// @author Brecht Devos - <[email protected]> library NftMintTransaction { using BlockReader for bytes; using BytesUtil for bytes; using ExchangeSignatures for ExchangeData.State; using FloatUtil for uint16; using MathUint96 for uint96; using MathUint for uint; bytes32 constant public NFTMINT_TYPEHASH = keccak256( "NftMint(address minter,address to,uint8 nftType,address token,uint256 nftID,uint8 creatorFeeBips,uint96 amount,uint16 feeTokenID,uint96 maxFee,uint32 validUntil,uint32 storageID)" ); // This structure represents either a L2 NFT mint or a L1-to-L2 NFT deposit. struct NftMint { uint mintType; uint32 minterAccountID; uint32 toAccountID; uint16 toTokenID; // slot uint96 amount; uint16 feeTokenID; uint96 maxFee; uint96 fee; uint32 validUntil; uint32 storageID; address to; ExchangeData.Nft nft; } // Auxiliary data for each NFT mint struct NftMintAuxiliaryData { bytes signature; uint96 maxFee; uint32 validUntil; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory ctx, bytes memory data, uint offset, bytes memory auxiliaryData ) internal { // Read in the mint NftMint memory mint; readTx(data, offset, mint); // Read the NFT data if we're minting or depositing an NFT // // Note that EdDSA-based minting has the following restrictions due // to storage limit: // 1) It's only possible to mint to the minter's own account. // 2) The max amount that can be minted is limited to 65535 (2**16 - 1) per mint. // // ECDSA and onchain approval hash-based minting do not have the above restrictions. { // Read the NFT data NftDataTransaction.NftData memory nftData; NftDataTransaction.readDualNftData( ctx, mint.toAccountID, mint.toTokenID, ctx.txIndex.add(1), nftData ); // Copy the data to the mint struct mint.nft = nftData.nft; } if (mint.mintType == 2) { // No fee allowed for deposits require(mint.fee == 0, "DEPOSIT_FEE_DISALLOWED"); require(mint.nft.creatorFeeBips == 0, "CREATORFEEBIPS_NONZERO"); // The minter should be the NFT token contract for deposits require(mint.nft.minter == mint.nft.token, "MINTER_NOT_TOKEN_CONTRACT"); // Process the deposit ExchangeData.Deposit memory pendingDeposit = S.pendingNFTDeposits[mint.to][mint.nft.nftType][mint.nft.token][mint.nft.nftID]; // Make sure the deposit was actually done require(pendingDeposit.timestamp > 0, "DEPOSIT_NOT_EXIST"); // Processing partial amounts of the deposited amount is allowed. // This is done to ensure the user can do multiple deposits after each other // without invalidating work done by the exchange owner for previous deposit amounts. require(pendingDeposit.amount >= mint.amount, "INVALID_AMOUNT"); pendingDeposit.amount = pendingDeposit.amount.sub(mint.amount); // If the deposit was fully consumed, reset it so the storage is freed up // and the owner receives a gas refund. if (pendingDeposit.amount == 0) { delete S.pendingNFTDeposits[mint.to][mint.nft.nftType][mint.nft.token][mint.nft.nftID]; } else { S.pendingNFTDeposits[mint.to][mint.nft.nftType][mint.nft.token][mint.nft.nftID] = pendingDeposit; } } else { // The minter should NOT be the NFT token contract for L2 mints require(mint.nft.minter != mint.nft.token, "MINTER_EQUALS_TOKEN_CONTRACT"); NftMintAuxiliaryData memory auxData = abi.decode(auxiliaryData, (NftMintAuxiliaryData)); // Fill in withdrawal data missing from DA or only available in the NftData // Fill in withdrawal data missing from DA mint.validUntil = auxData.validUntil; mint.maxFee = auxData.maxFee == 0 ? mint.fee : auxData.maxFee; // Validate require(ctx.timestamp < mint.validUntil, "NFTMINT_EXPIRED"); require(mint.fee <= mint.maxFee, "NFTMINT_FEE_TOO_HIGH"); // Calculate the tx hash bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, mint); // Check the on-chain authorization S.requireAuthorizedTx(mint.nft.minter, auxData.signature, txHash); } } function readTx( bytes memory data, uint offset, NftMint memory mint ) internal pure { uint _offset = offset; require( data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.NFT_MINT), "INVALID_TX_TYPE" ); _offset += 1; mint.mintType = data.toUint8Unsafe(_offset); _offset += 1; // Check that this is a conditional mint require(mint.mintType > 0, "INVALID_AUXILIARY_DATA"); // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. mint.minterAccountID = data.toUint32Unsafe(_offset); _offset += 4; mint.toTokenID = data.toUint16Unsafe(_offset); _offset += 2; mint.feeTokenID = data.toUint16Unsafe(_offset); _offset += 2; mint.fee = data.toUint16Unsafe(_offset).decodeFloat16(); _offset += 2; mint.amount = data.toUint96Unsafe(_offset); _offset += 12; mint.storageID = data.toUint32Unsafe(_offset); _offset += 4; mint.toAccountID = data.toUint32Unsafe(_offset); _offset += 4; mint.to = data.toAddressUnsafe(_offset); _offset += 20; } function hashTx( bytes32 DOMAIN_SEPARATOR, NftMint memory mint ) internal pure returns (bytes32) { return EIP712.hashPacked( DOMAIN_SEPARATOR, keccak256( abi.encode( NFTMINT_TYPEHASH, mint.nft.minter, mint.to, mint.nft.nftType, mint.nft.token, mint.nft.nftID, mint.nft.creatorFeeBips, mint.amount, mint.feeTokenID, mint.maxFee, mint.validUntil, mint.storageID ) ) ); } } // File: contracts/core/impl/libexchange/ExchangeBlocks.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeBlocks. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeBlocks { using AddressUtil for address; using AddressUtil for address payable; using BlockReader for bytes; using BytesUtil for bytes; using MathUint for uint; using ExchangeMode for ExchangeData.State; using ExchangeWithdrawals for ExchangeData.State; using SignatureUtil for bytes32; event BlockSubmitted( uint indexed blockIdx, bytes32 merkleRoot, bytes32 publicDataHash ); event ProtocolFeesUpdated( uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); function submitBlocks( ExchangeData.State storage S, ExchangeData.Block[] memory blocks ) public { // Exchange cannot be in withdrawal mode require(!S.isInWithdrawalMode(), "INVALID_MODE"); // Commit the blocks bytes32[] memory publicDataHashes = new bytes32[](blocks.length); for (uint i = 0; i < blocks.length; i++) { // Hash all the public data to a single value which is used as the input for the circuit publicDataHashes[i] = blocks[i].data.fastSHA256(); // Commit the block commitBlock(S, blocks[i], publicDataHashes[i]); } // Verify the blocks - blocks are verified in a batch to save gas. verifyBlocks(S, blocks, publicDataHashes); } // == Internal Functions == function commitBlock( ExchangeData.State storage S, ExchangeData.Block memory _block, bytes32 _publicDataHash ) private { // Read the block header BlockReader.BlockHeader memory header = _block.data.readHeader(); // Validate the exchange require(header.exchange == address(this), "INVALID_EXCHANGE"); // Validate the Merkle roots require(header.merkleRootBefore == S.merkleRoot, "INVALID_MERKLE_ROOT"); require(header.merkleRootAfter != header.merkleRootBefore, "EMPTY_BLOCK_DISABLED"); require(uint(header.merkleRootAfter) < ExchangeData.SNARK_SCALAR_FIELD, "INVALID_MERKLE_ROOT"); // Validate the timestamp require( header.timestamp > block.timestamp - ExchangeData.TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS && header.timestamp < block.timestamp + ExchangeData.TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS, "INVALID_TIMESTAMP" ); // Validate the protocol fee values require( validateAndSyncProtocolFees(S, header.protocolTakerFeeBips, header.protocolMakerFeeBips), "INVALID_PROTOCOL_FEES" ); // Process conditional transactions processConditionalTransactions( S, _block, header ); // Emit an event uint numBlocks = S.numBlocks; emit BlockSubmitted(numBlocks, header.merkleRootAfter, _publicDataHash); S.merkleRoot = header.merkleRootAfter; if (_block.storeBlockInfoOnchain) { S.blocks[numBlocks] = ExchangeData.BlockInfo( uint32(block.timestamp), bytes28(_publicDataHash) ); } S.numBlocks = numBlocks + 1; } function verifyBlocks( ExchangeData.State storage S, ExchangeData.Block[] memory blocks, bytes32[] memory publicDataHashes ) private view { IBlockVerifier blockVerifier = S.blockVerifier; uint numBlocksVerified = 0; bool[] memory blockVerified = new bool[](blocks.length); ExchangeData.Block memory firstBlock; uint[] memory batch = new uint[](blocks.length); while (numBlocksVerified < blocks.length) { // Find all blocks of the same type uint batchLength = 0; for (uint i = 0; i < blocks.length; i++) { if (blockVerified[i] == false) { if (batchLength == 0) { firstBlock = blocks[i]; batch[batchLength++] = i; } else { ExchangeData.Block memory _block = blocks[i]; if (_block.blockType == firstBlock.blockType && _block.blockSize == firstBlock.blockSize && _block.blockVersion == firstBlock.blockVersion) { batch[batchLength++] = i; } } } } // Prepare the data for batch verification uint[] memory publicInputs = new uint[](batchLength); uint[] memory proofs = new uint[](batchLength * 8); for (uint i = 0; i < batchLength; i++) { uint blockIdx = batch[i]; // Mark the block as verified blockVerified[blockIdx] = true; // Strip the 3 least significant bits of the public data hash // so we don't have any overflow in the snark field publicInputs[i] = uint(publicDataHashes[blockIdx]) >> 3; // Copy proof ExchangeData.Block memory _block = blocks[blockIdx]; for (uint j = 0; j < 8; j++) { proofs[i*8 + j] = _block.proof[j]; } } // Verify the proofs require( blockVerifier.verifyProofs( uint8(firstBlock.blockType), firstBlock.blockSize, firstBlock.blockVersion, publicInputs, proofs ), "INVALID_PROOF" ); numBlocksVerified += batchLength; } } function processConditionalTransactions( ExchangeData.State storage S, ExchangeData.Block memory _block, BlockReader.BlockHeader memory header ) private { if (header.numConditionalTransactions > 0) { // Cache the domain separator to save on SLOADs each time it is accessed. ExchangeData.BlockContext memory ctx = ExchangeData.BlockContext({ DOMAIN_SEPARATOR: S.DOMAIN_SEPARATOR, timestamp: header.timestamp, block: _block, txIndex: 0 }); ExchangeData.AuxiliaryData[] memory block_auxiliaryData; bytes memory blockAuxData = _block.auxiliaryData; assembly { block_auxiliaryData := add(blockAuxData, 64) } require( block_auxiliaryData.length == header.numConditionalTransactions, "AUXILIARYDATA_INVALID_LENGTH" ); // Run over all conditional transactions uint minTxIndex = 0; bytes memory txData = new bytes(ExchangeData.TX_DATA_AVAILABILITY_SIZE); for (uint i = 0; i < block_auxiliaryData.length; i++) { // Load the data from auxiliaryData, which is still encoded as calldata uint txIndex; bool approved; bytes memory auxData; assembly { // Offset to block_auxiliaryData[i] let auxOffset := mload(add(block_auxiliaryData, add(32, mul(32, i)))) // Load `txIndex` (pos 0) and `approved` (pos 1) in block_auxiliaryData[i] txIndex := mload(add(add(32, block_auxiliaryData), auxOffset)) approved := mload(add(add(64, block_auxiliaryData), auxOffset)) // Load `data` (pos 2) let auxDataOffset := mload(add(add(96, block_auxiliaryData), auxOffset)) auxData := add(add(32, block_auxiliaryData), add(auxOffset, auxDataOffset)) } ctx.txIndex = txIndex; // Each conditional transaction needs to be processed from left to right require(txIndex >= minTxIndex, "AUXILIARYDATA_INVALID_ORDER"); minTxIndex = txIndex + 1; if (approved) { continue; } // Get the transaction data _block.data.readTransactionData(txIndex, _block.blockSize, txData); // Process the transaction ExchangeData.TransactionType txType = ExchangeData.TransactionType( txData.toUint8(0) ); uint txDataOffset = 0; if (txType == ExchangeData.TransactionType.DEPOSIT) { DepositTransaction.process( S, ctx, txData, txDataOffset, auxData ); } else if (txType == ExchangeData.TransactionType.WITHDRAWAL) { WithdrawTransaction.process( S, ctx, txData, txDataOffset, auxData ); } else if (txType == ExchangeData.TransactionType.TRANSFER) { TransferTransaction.process( S, ctx, txData, txDataOffset, auxData ); } else if (txType == ExchangeData.TransactionType.ACCOUNT_UPDATE) { AccountUpdateTransaction.process( S, ctx, txData, txDataOffset, auxData ); } else if (txType == ExchangeData.TransactionType.AMM_UPDATE) { AmmUpdateTransaction.process( S, ctx, txData, txDataOffset, auxData ); } else if (txType == ExchangeData.TransactionType.NFT_MINT) { NftMintTransaction.process( S, ctx, txData, txDataOffset, auxData ); } else { // ExchangeData.TransactionType.NOOP, // ExchangeData.TransactionType.SPOT_TRADE and // ExchangeData.TransactionType.SIGNATURE_VERIFICATION // are not supported revert("UNSUPPORTED_TX_TYPE"); } } } } function validateAndSyncProtocolFees( ExchangeData.State storage S, uint8 takerFeeBips, uint8 makerFeeBips ) private returns (bool) { ExchangeData.ProtocolFeeData memory data = S.protocolFeeData; if (block.timestamp > data.syncedAt + ExchangeData.MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED) { // Store the current protocol fees in the previous protocol fees data.previousTakerFeeBips = data.takerFeeBips; data.previousMakerFeeBips = data.makerFeeBips; // Get the latest protocol fees for this exchange (data.takerFeeBips, data.makerFeeBips) = S.loopring.getProtocolFeeValues(); data.syncedAt = uint32(block.timestamp); if (data.takerFeeBips != data.previousTakerFeeBips || data.makerFeeBips != data.previousMakerFeeBips) { emit ProtocolFeesUpdated( data.takerFeeBips, data.makerFeeBips, data.previousTakerFeeBips, data.previousMakerFeeBips ); } // Update the data in storage S.protocolFeeData = data; } // The given fee values are valid if they are the current or previous protocol fee values return (takerFeeBips == data.takerFeeBips && makerFeeBips == data.makerFeeBips) || (takerFeeBips == data.previousTakerFeeBips && makerFeeBips == data.previousMakerFeeBips); } } // File: contracts/core/impl/libexchange/ExchangeDeposits.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeDeposits. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeDeposits { using AddressUtil for address payable; using MathUint96 for uint96; using ExchangeMode for ExchangeData.State; using ExchangeTokens for ExchangeData.State; event DepositRequested( address from, address to, address token, uint16 tokenId, uint96 amount ); event NFTDepositRequested( address from, address to, uint8 nftType, address token, uint256 nftID, uint96 amount ); function deposit( ExchangeData.State storage S, address from, address to, address tokenAddress, uint96 amount, // can be zero bytes memory extraData ) internal // inline call { require(to != address(0), "ZERO_ADDRESS"); // Deposits are still possible when the exchange is being shutdown, or even in withdrawal mode. // This is fine because the user can easily withdraw the deposited amounts again. // We don't want to make all deposits more expensive just to stop that from happening. // Allow depositing with amount == 0 to allow updating the deposit timestamp uint16 tokenID = S.getTokenID(tokenAddress); // Transfer the tokens to this contract uint96 amountDeposited = S.depositContract.deposit{value: msg.value}( from, tokenAddress, amount, extraData ); // Add the amount to the deposit request and reset the time the operator has to process it ExchangeData.Deposit memory _deposit = S.pendingDeposits[to][tokenID]; _deposit.timestamp = uint64(block.timestamp); _deposit.amount = _deposit.amount.add(amountDeposited); S.pendingDeposits[to][tokenID] = _deposit; emit DepositRequested( from, to, tokenAddress, tokenID, amountDeposited ); } function depositNFT( ExchangeData.State storage S, address from, address to, ExchangeData.NftType nftType, address tokenAddress, uint256 nftID, uint96 amount, // can be zero bytes memory extraData ) public { require(to != address(0), "ZERO_ADDRESS"); // Deposits are still possible when the exchange is being shutdown, or even in withdrawal mode. // This is fine because the user can easily withdraw the deposited amounts again. // We don't want to make all deposits more expensive just to stop that from happening. // Allow depositing with amount == 0 to allow updating the deposit timestamp // Transfer the tokens to this contract ExchangeNFT.deposit( S, from, nftType, tokenAddress, nftID, amount, extraData ); // Add the amount to the deposit request and reset the time the operator has to process it ExchangeData.Deposit memory _deposit = S.pendingNFTDeposits[to][nftType][tokenAddress][nftID]; _deposit.timestamp = uint64(block.timestamp); _deposit.amount = _deposit.amount.add(amount); S.pendingNFTDeposits[to][nftType][tokenAddress][nftID] = _deposit; emit NFTDepositRequested( from, to, uint8(nftType), tokenAddress, nftID, amount ); } } // File: contracts/core/impl/libexchange/ExchangeGenesis.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeGenesis. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeGenesis { using ExchangeTokens for ExchangeData.State; function initializeGenesisBlock( ExchangeData.State storage S, address _loopringAddr, bytes32 _genesisMerkleRoot, bytes32 _domainSeparator ) public { require(address(0) != _loopringAddr, "INVALID_LOOPRING_ADDRESS"); require(_genesisMerkleRoot != 0, "INVALID_GENESIS_MERKLE_ROOT"); S.maxAgeDepositUntilWithdrawable = ExchangeData.MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND; S.DOMAIN_SEPARATOR = _domainSeparator; ILoopringV3 loopring = ILoopringV3(_loopringAddr); S.loopring = loopring; S.blockVerifier = IBlockVerifier(loopring.blockVerifierAddress()); S.merkleRoot = _genesisMerkleRoot; S.blocks[0] = ExchangeData.BlockInfo(uint32(block.timestamp), bytes28(0)); S.numBlocks = 1; // Get the protocol fees for this exchange S.protocolFeeData.syncedAt = uint32(0); S.protocolFeeData.takerFeeBips = S.loopring.protocolTakerFeeBips(); S.protocolFeeData.makerFeeBips = S.loopring.protocolMakerFeeBips(); S.protocolFeeData.previousTakerFeeBips = S.protocolFeeData.takerFeeBips; S.protocolFeeData.previousMakerFeeBips = S.protocolFeeData.makerFeeBips; // Call these after the main state has been set up S.registerToken(address(0)); S.registerToken(loopring.lrcAddress()); } } // File: contracts/core/impl/ExchangeV3.sol // Copyright 2017 Loopring Technology Limited. /// @title An Implementation of IExchangeV3. /// @dev This contract supports upgradability proxy, therefore its constructor /// must do NOTHING. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> contract ExchangeV3 is IExchangeV3, ReentrancyGuard, ERC1155Holder, ERC721Holder { using AddressUtil for address; using ERC20SafeTransfer for address; using MathUint for uint; using ExchangeAdmins for ExchangeData.State; using ExchangeBalances for ExchangeData.State; using ExchangeBlocks for ExchangeData.State; using ExchangeDeposits for ExchangeData.State; using ExchangeGenesis for ExchangeData.State; using ExchangeMode for ExchangeData.State; using ExchangeTokens for ExchangeData.State; using ExchangeWithdrawals for ExchangeData.State; ExchangeData.State private state; modifier onlyWhenUninitialized() { require( state.loopringAddr == address(0) && state.merkleRoot == bytes32(0), "INITIALIZED" ); _; } modifier onlyFromUserOrAgent(address owner) { require(isUserOrAgent(owner), "UNAUTHORIZED"); _; } /// @dev The constructor must do NOTHING to support proxy. constructor() {} function version() public pure returns (string memory) { return "3.6.0"; } function domainSeparator() public view returns (bytes32) { return state.DOMAIN_SEPARATOR; } // -- Initialization -- function initialize( address _loopring, address _owner, bytes32 _genesisMerkleRoot ) external override nonReentrant onlyWhenUninitialized { require(address(0) != _owner, "ZERO_ADDRESS"); owner = _owner; state.loopringAddr = _loopring; state.initializeGenesisBlock( _loopring, _genesisMerkleRoot, EIP712.hash(EIP712.Domain("Loopring Protocol", version(), address(this))) ); } function setAgentRegistry(address _agentRegistry) external override nonReentrant onlyOwner { require(_agentRegistry != address(0), "ZERO_ADDRESS"); require(state.agentRegistry == IAgentRegistry(0), "ALREADY_SET"); state.agentRegistry = IAgentRegistry(_agentRegistry); } function refreshBlockVerifier() external override nonReentrant onlyOwner { require(state.loopring.blockVerifierAddress() != address(0), "ZERO_ADDRESS"); state.blockVerifier = IBlockVerifier(state.loopring.blockVerifierAddress()); } function getAgentRegistry() external override view returns (IAgentRegistry) { return state.agentRegistry; } function setDepositContract(address _depositContract) external override nonReentrant onlyOwner { require(_depositContract != address(0), "ZERO_ADDRESS"); // Only used for initialization require(state.depositContract == IDepositContract(0), "ALREADY_SET"); state.depositContract = IDepositContract(_depositContract); } function getDepositContract() external override view returns (IDepositContract) { return state.depositContract; } function withdrawExchangeFees( address token, address recipient ) external override nonReentrant onlyOwner { require(recipient != address(0), "INVALID_ADDRESS"); // Does not call a standard NFT transfer function so we can allow any contract address. // Disallow calls to the deposit contract as a precaution. require(token != address(state.depositContract), "INVALID_TOKEN"); if (token == address(0)) { uint amount = address(this).balance; recipient.sendETHAndVerify(amount, gasleft()); } else { uint amount = ERC20(token).balanceOf(address(this)); token.safeTransferAndVerify(recipient, amount); } } function isUserOrAgent(address owner) public view returns (bool) { return owner == msg.sender || state.agentRegistry != IAgentRegistry(address(0)) && state.agentRegistry.isAgent(owner, msg.sender); } // -- Constants -- function getConstants() external override pure returns(ExchangeData.Constants memory) { return ExchangeData.Constants( uint(ExchangeData.SNARK_SCALAR_FIELD), uint(ExchangeData.MAX_OPEN_FORCED_REQUESTS), uint(ExchangeData.MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE), uint(ExchangeData.TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS), uint(ExchangeData.MAX_NUM_ACCOUNTS), uint(ExchangeData.MAX_NUM_TOKENS), uint(ExchangeData.MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED), uint(ExchangeData.MIN_TIME_IN_SHUTDOWN), uint(ExchangeData.TX_DATA_AVAILABILITY_SIZE), uint(ExchangeData.MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND) ); } // -- Mode -- function isInWithdrawalMode() external override view returns (bool) { return state.isInWithdrawalMode(); } function isShutdown() external override view returns (bool) { return state.isShutdown(); } // -- Tokens -- function registerToken( address tokenAddress ) external override nonReentrant onlyOwner returns (uint16) { return state.registerToken(tokenAddress); } function getTokenID( address tokenAddress ) external override view returns (uint16) { return state.getTokenID(tokenAddress); } function getTokenAddress( uint16 tokenID ) external override view returns (address) { return state.getTokenAddress(tokenID); } // -- Stakes -- function getExchangeStake() external override view returns (uint) { return state.loopring.getExchangeStake(address(this)); } function withdrawExchangeStake( address recipient ) external override nonReentrant onlyOwner returns (uint) { return state.withdrawExchangeStake(recipient); } function getProtocolFeeLastWithdrawnTime( address tokenAddress ) external override view returns (uint) { return state.protocolFeeLastWithdrawnTime[tokenAddress]; } function burnExchangeStake() external override nonReentrant { // Allow burning the complete exchange stake when the exchange gets into withdrawal mode if (state.isInWithdrawalMode()) { // Burn the complete stake of the exchange uint stake = state.loopring.getExchangeStake(address(this)); state.loopring.burnExchangeStake(stake); } } // -- Blocks -- function getMerkleRoot() external override view returns (bytes32) { return state.merkleRoot; } function getBlockHeight() external override view returns (uint) { return state.numBlocks; } function getBlockInfo(uint blockIdx) external override view returns (ExchangeData.BlockInfo memory) { return state.blocks[blockIdx]; } function submitBlocks(ExchangeData.Block[] calldata blocks) external override nonReentrant onlyOwner { state.submitBlocks(blocks); } function getNumAvailableForcedSlots() external override view returns (uint) { return state.getNumAvailableForcedSlots(); } // -- Deposits -- function deposit( address from, address to, address tokenAddress, uint96 amount, bytes calldata extraData ) external payable override nonReentrant onlyFromUserOrAgent(from) { state.deposit(from, to, tokenAddress, amount, extraData); } function depositNFT( address from, address to, ExchangeData.NftType nftType, address tokenAddress, uint256 nftID, uint96 amount, bytes calldata extraData ) external override nonReentrant onlyFromUserOrAgent(from) { state.depositNFT(from, to, nftType, tokenAddress, nftID, amount, extraData); } function getPendingDepositAmount( address owner, address tokenAddress ) public override view returns (uint96) { uint16 tokenID = state.getTokenID(tokenAddress); return state.pendingDeposits[owner][tokenID].amount; } function getPendingNFTDepositAmount( address owner, address token, ExchangeData.NftType nftType, uint256 nftID ) public override view returns (uint96) { return state.pendingNFTDeposits[owner][nftType][token][nftID].amount; } // -- Withdrawals -- function forceWithdrawByTokenID( address owner, uint16 tokenID, uint32 accountID ) external override nonReentrant payable onlyFromUserOrAgent(owner) { state.forceWithdraw(owner, tokenID, accountID); } function forceWithdraw( address owner, address token, uint32 accountID ) external override nonReentrant payable onlyFromUserOrAgent(owner) { uint16 tokenID = state.getTokenID(token); state.forceWithdraw(owner, tokenID, accountID); } function isForcedWithdrawalPending( uint32 accountID, address token ) external override view returns (bool) { uint16 tokenID = state.getTokenID(token); return state.pendingForcedWithdrawals[accountID][tokenID].timestamp != 0; } function withdrawProtocolFees( address token ) external override nonReentrant payable { uint16 tokenID = state.getTokenID(token); state.forceWithdraw(address(0), tokenID, ExchangeData.ACCOUNTID_PROTOCOLFEE); } // We still alow anyone to withdraw these funds for the account owner function withdrawFromMerkleTree( ExchangeData.MerkleProof calldata merkleProof ) external override nonReentrant { state.withdrawFromMerkleTree(merkleProof); } function isWithdrawnInWithdrawalMode( uint32 accountID, address token ) external override view returns (bool) { uint16 tokenID = state.getTokenID(token); return state.withdrawnInWithdrawMode[accountID][tokenID]; } function withdrawFromDepositRequest( address owner, address token ) external override nonReentrant { state.withdrawFromDepositRequest( owner, token ); } function withdrawFromNFTDepositRequest( address owner, address token, ExchangeData.NftType nftType, uint256 nftID ) external override nonReentrant { state.withdrawFromNFTDepositRequest( owner, token, nftType, nftID ); } function withdrawFromApprovedWithdrawals( address[] calldata owners, address[] calldata tokens ) external override nonReentrant { state.withdrawFromApprovedWithdrawals( owners, tokens ); } function withdrawFromApprovedWithdrawalsNFT( address[] memory owners, address[] memory minters, ExchangeData.NftType[] memory nftTypes, address[] memory tokens, uint256[] memory nftIDs ) external override nonReentrant { state.withdrawFromApprovedWithdrawalsNFT( owners, minters, nftTypes, tokens, nftIDs ); } function getAmountWithdrawable( address owner, address token ) external override view returns (uint) { uint16 tokenID = state.getTokenID(token); return state.amountWithdrawable[owner][tokenID]; } function getAmountWithdrawableNFT( address owner, address token, ExchangeData.NftType nftType, uint256 nftID, address minter ) external override view returns (uint) { return state.amountWithdrawableNFT[owner][minter][nftType][token][nftID]; } function notifyForcedRequestTooOld( uint32 accountID, uint16 tokenID ) external override nonReentrant { ExchangeData.ForcedWithdrawal storage withdrawal = state.pendingForcedWithdrawals[accountID][tokenID]; require(withdrawal.timestamp != 0, "WITHDRAWAL_NOT_TOO_OLD"); // Check if the withdrawal has indeed exceeded the time limit require(block.timestamp >= withdrawal.timestamp + ExchangeData.MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE, "WITHDRAWAL_NOT_TOO_OLD"); // Enter withdrawal mode state.withdrawalModeStartTime = block.timestamp; emit WithdrawalModeActivated(state.withdrawalModeStartTime); } function setWithdrawalRecipient( address from, address to, address token, uint96 amount, uint32 storageID, address newRecipient ) external override nonReentrant onlyFromUserOrAgent(from) { require(newRecipient != address(0), "INVALID_DATA"); uint16 tokenID = state.getTokenID(token); require(state.withdrawalRecipient[from][to][tokenID][amount][storageID] == address(0), "CANNOT_OVERRIDE_RECIPIENT_ADDRESS"); state.withdrawalRecipient[from][to][tokenID][amount][storageID] = newRecipient; } function getWithdrawalRecipient( address from, address to, address token, uint96 amount, uint32 storageID ) external override view returns (address) { uint16 tokenID = state.getTokenID(token); return state.withdrawalRecipient[from][to][tokenID][amount][storageID]; } function onchainTransferFrom( address from, address to, address token, uint amount ) external override nonReentrant onlyFromUserOrAgent(from) { require(state.allowOnchainTransferFrom, "NOT_ALLOWED"); state.depositContract.transfer(from, to, token, amount); } function approveTransaction( address owner, bytes32 transactionHash ) external override nonReentrant onlyFromUserOrAgent(owner) { state.approvedTx[owner][transactionHash] = true; emit TransactionApproved(owner, transactionHash); } function approveTransactions( address[] calldata owners, bytes32[] calldata transactionHashes ) external override nonReentrant { require(owners.length == transactionHashes.length, "INVALID_DATA"); require(state.agentRegistry.isAgent(owners, msg.sender), "UNAUTHORIZED"); for (uint i = 0; i < owners.length; i++) { state.approvedTx[owners[i]][transactionHashes[i]] = true; } } function isTransactionApproved( address owner, bytes32 transactionHash ) external override view returns (bool) { return state.approvedTx[owner][transactionHash]; } function getDomainSeparator() external override view returns (bytes32) { return state.DOMAIN_SEPARATOR; } // -- Admins -- function setMaxAgeDepositUntilWithdrawable( uint32 newValue ) external override nonReentrant onlyOwner returns (uint32) { return state.setMaxAgeDepositUntilWithdrawable(newValue); } function getMaxAgeDepositUntilWithdrawable() external override view returns (uint32) { return state.maxAgeDepositUntilWithdrawable; } function shutdown() external override nonReentrant onlyOwner returns (bool success) { require(!state.isInWithdrawalMode(), "INVALID_MODE"); require(!state.isShutdown(), "ALREADY_SHUTDOWN"); state.shutdownModeStartTime = block.timestamp; emit Shutdown(state.shutdownModeStartTime); return true; } function getProtocolFeeValues() external override view returns ( uint32 syncedAt, uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ) { syncedAt = state.protocolFeeData.syncedAt; takerFeeBips = state.protocolFeeData.takerFeeBips; makerFeeBips = state.protocolFeeData.makerFeeBips; previousTakerFeeBips = state.protocolFeeData.previousTakerFeeBips; previousMakerFeeBips = state.protocolFeeData.previousMakerFeeBips; } function setAmmFeeBips(uint8 _feeBips) external override nonReentrant onlyOwner { require(_feeBips <= 200, "INVALID_VALUE"); state.ammFeeBips = _feeBips; } function getAmmFeeBips() external override view returns (uint8) { return state.ammFeeBips; } function setAllowOnchainTransferFrom(bool value) external nonReentrant onlyOwner { require(state.allowOnchainTransferFrom != value, "SAME_VALUE"); state.allowOnchainTransferFrom = value; } }
the `to` or `from` account's ID.
uint32 accountID;
10,597,195
[ 1, 4625, 348, 7953, 560, 30, 225, 326, 1375, 869, 68, 578, 1375, 2080, 68, 2236, 1807, 1599, 18, 203, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1578, 9079, 26643, 31, 1850, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x114d647B099D53237be9E03A540DFFaa24351E87/sources/contracts/strategies/balancer/BalancerStrategyBase.sol
* @dev Performs a single swap using Balancer Vault. @param tokenOut The address of the output ERC20 token. @param tokenIn The address of the input ERC20 token. @param amountIn The amount of input token to swap. @param minAmountOut The minimum acceptable amount of the output token. @param poolId The PoolId of the Balancer pool to use for the swap. @return receivedTokenOut The actual amount of output tokens received./
function _balancerSwapSingle( address tokenOut, address tokenIn, uint256 amountIn, uint256 minAmountOut, bytes32 poolId ) internal returns (uint256) { return IBalancerWrapper(BAL_WRAPPER).swapSingle( tokenOut, tokenIn, amountIn, minAmountOut, poolId, _getDeadline() ); }
3,107,603
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 27391, 279, 2202, 7720, 1450, 605, 5191, 17329, 18, 632, 891, 1147, 1182, 1021, 1758, 434, 326, 876, 4232, 39, 3462, 1147, 18, 632, 891, 1147, 382, 1021, 1758, 434, 326, 810, 4232, 39, 3462, 1147, 18, 632, 891, 3844, 382, 1021, 3844, 434, 810, 1147, 358, 7720, 18, 632, 891, 1131, 6275, 1182, 1021, 5224, 14206, 3844, 434, 326, 876, 1147, 18, 632, 891, 2845, 548, 1021, 8828, 548, 434, 326, 605, 5191, 2845, 358, 999, 364, 326, 7720, 18, 632, 2463, 5079, 1345, 1182, 1021, 3214, 3844, 434, 876, 2430, 5079, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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034, 1131, 6275, 1182, 16, 203, 3639, 1731, 1578, 2845, 548, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 203, 5411, 467, 6444, 3611, 12, 38, 1013, 67, 27664, 3194, 2934, 22270, 5281, 12, 203, 7734, 1147, 1182, 16, 203, 7734, 1147, 382, 16, 203, 7734, 3844, 382, 16, 203, 7734, 1131, 6275, 1182, 16, 203, 7734, 2845, 548, 16, 203, 7734, 389, 588, 15839, 1435, 203, 5411, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; contract CryptoCatsMarket { /* You can use this hash to verify the image file containing all cats */ string public imageHash = "e055fe5eb1d95ea4e42b24d1038db13c24667c494ce721375bdd827d34c59059"; /* Struct object for storing cat details */ struct Cat { uint256 idNum; // cat index number string name; // cat name bool owned; // status of cat ownership address owner; // address if cat owner } /* Variables to store contract owner and contract token standard details */ address owner; string public standard = 'CryptoCats'; string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; bool public allCatsAssigned = false; // boolean flag to indicate if all available cats are claimed uint256 public catsRemainingToAssign = 0; // variable to track cats remaining to be assigned/claimed /* Create array to store cat index to owner address */ mapping (uint256 => address) public catIndexToAddress; /* Create an array with all balances */ mapping (address => uint256) public balanceOf; /* Create array to store cat details like names */ mapping (uint256 => Cat) public catDetails; /* Define event types used to publish to EVM log when cat assignment/claim and cat transfer occurs */ event Assign(address indexed to, uint256 catIndex); event Transfer(address indexed from, address indexed to, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function CryptoCatsMarket() payable { owner = msg.sender; // Set contract creation sender as owner _totalSupply = 12; // Set total supply catsRemainingToAssign = _totalSupply; // Initialise cats remaining to total supply amount name = "CRYPTOCATS"; // Set the name for display purposes symbol = "CCAT"; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes initialiseCats(); // initialise cat details } /* Admin function to set all cats assigned flag to true (callable by owner only) */ function allInitialOwnersAssigned() { require(msg.sender == owner); allCatsAssigned = true; } /* Transfer cat by owner to another wallet address Different usage in Cryptocats than in normal token transfers This will transfer an owner's cat to another wallet's address Cat is identified by cat index passed in as _value */ function transfer(address _to, uint256 _value) returns (bool success) { if (_value < _totalSupply && // ensure cat index is valid catIndexToAddress[_value] == msg.sender && // ensure sender is owner of cat balanceOf[msg.sender] > 0) { // ensure sender balance of cat exists balanceOf[msg.sender]--; // update (reduce) cat balance from owner catIndexToAddress[_value] = _to; // set new owner of cat in cat index catDetails[_value].owner = _to; // set new owner of cat in cat details balanceOf[_to]++; // update (include) cat balance for recepient Transfer(msg.sender, _to, _value); // trigger event with transfer details to EVM success = true; // set success as true after transfer completed } else { success = false; // set success as false if conditions not met } return success; // return success status } /* Admin function to set all cats details during contract initialisation */ function initialiseCats() private { require(msg.sender == owner); // require function caller to be contract owner catDetails[0] = Cat(0,"Cat 0", false, 0x0); catDetails[1] = Cat(1,"Cat 1", false, 0x0); catDetails[2] = Cat(2,"Cat 2", false, 0x0); catDetails[3] = Cat(3,"Cat 3", false, 0x0); catDetails[4] = Cat(4,"Cat 4", false, 0x0); catDetails[5] = Cat(5,"Cat 5", false, 0x0); catDetails[6] = Cat(6,"Cat 6", false, 0x0); catDetails[7] = Cat(7,"Cat 7", false, 0x0); catDetails[8] = Cat(8,"Cat 8", false, 0x0); catDetails[9] = Cat(9,"Cat 9", false, 0x0); catDetails[10] = Cat(10,"Cat 10", false, 0x0); catDetails[11] = Cat(11,"Cat 11", false, 0x0); } /* Returns count of how many cats are owned by an owner */ function balanceOf(address _owner) constant returns (uint256 balance) { require(balanceOf[_owner] != 0); // requires that cat owner balance is not 0 return balanceOf[_owner]; // return number of cats owned from array of balances by owner address } /* Return total supply of cats existing */ function totalSupply() constant returns (uint256 totalSupply) { return _totalSupply; } /* Claim cat at specified index if it is unassigned */ function claimCat(uint catIndex) { require(!allCatsAssigned); // require all cats have not been assigned/claimed require(catsRemainingToAssign != 0); // require cats remaining to be assigned count is not 0 require(catIndexToAddress[catIndex] == 0x0); // require owner address for requested cat index is empty require(catIndex < _totalSupply); // require cat index requested does not exceed total supply catIndexToAddress[catIndex] = msg.sender; // Assign sender's address as owner of cat balanceOf[msg.sender]++; // Increase sender's balance holder catsRemainingToAssign--; // Decrease cats remaining count catDetails[catIndex].owned = true; // set owned flag in cat details to true for this cat index catDetails[catIndex].owner = msg.sender; // store owner address in cat details for this cat index Assign(msg.sender, catIndex); // Triggers address assignment event to EVM's // log to allow javascript callbacks } /* Get address of owner based on cat index */ function getCatOwner(uint256 catIndex) public returns (address) { require(catIndexToAddress[catIndex] != 0x0); return catIndexToAddress[catIndex]; // Return address at array position of cat index } /* Get address of contract owner who performed contract creation and initialisation */ function getContractOwner() public returns (address) { return owner; // Return address of contract owner } /* Get cat details consisting of index, name, owned status and owner address for a particular cat index */ function getCatDetail(uint256 catIndex) public returns (uint256, string, bool, address) { Cat cat = catDetails[catIndex]; // get cat struct object from cat details array return (cat.idNum, cat.name, cat.owned, cat.owner); // return cat detail values } }
Get address of contract owner who performed contract creation and initialisation */
function getContractOwner() public returns (address) { }
6,085,639
[ 1, 4625, 348, 7953, 560, 30, 225, 968, 1758, 434, 6835, 3410, 10354, 9591, 6835, 6710, 471, 2172, 10742, 1195, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8924, 5541, 1435, 1071, 1135, 261, 2867, 13, 288, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/42/0x8806587D0668A152953ed99aFC81800D9E7b32f1/sources/PingPong.sol
Dependency file: @openzeppelin/contracts/GSN/Context.sol 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 setMaintainer(address _maintainer) external virtual; } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { return msg.data; } }
3,454,012
[ 1, 4625, 348, 7953, 560, 30, 225, 11993, 585, 30, 632, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 43, 13653, 19, 1042, 18, 18281, 10878, 18035, 560, 3602, 20, 18, 26, 18, 20, 31, 632, 5206, 28805, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 611, 13653, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17801, 6835, 1772, 288, 203, 565, 445, 15430, 1598, 1521, 12, 2867, 389, 81, 1598, 1521, 13, 3903, 5024, 31, 203, 97, 203, 203, 203, 203, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 1234, 18, 892, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/42220/0x12620e1E2909a4ACc9B8Cfc83D53d9CAf8f06ae1/sources/marketplace.sol
* @notice Calculate price and associated fees for a collection @param collection: address of the collection @param price: listed price/
function calculatePriceAndFeesForCollection(address collection, uint256 price) external view returns ( uint256 netPrice, uint256 tradingFee, uint256 creatorFee ) { if (_collections[collection].status != CollectionStatus.Open) { return (0, 0, 0); } return (_calculatePriceAndFeesForCollection(collection, price)); }
16,340,755
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 9029, 6205, 471, 3627, 1656, 281, 364, 279, 1849, 632, 891, 1849, 30, 1758, 434, 326, 1849, 632, 891, 6205, 30, 12889, 6205, 19, 2, 0, 0, 0, 0, 0, 0, 0, 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034, 2901, 5147, 16, 203, 5411, 2254, 5034, 1284, 7459, 14667, 16, 203, 5411, 2254, 5034, 11784, 14667, 203, 3639, 262, 203, 565, 288, 203, 3639, 309, 261, 67, 19246, 63, 5548, 8009, 2327, 480, 2200, 1482, 18, 3678, 13, 288, 203, 5411, 327, 261, 20, 16, 374, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 327, 261, 67, 11162, 5147, 1876, 2954, 281, 1290, 2532, 12, 5548, 16, 6205, 10019, 203, 565, 289, 203, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 02/08/2021 *https://t.me/RagnarInu */ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; 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; } } 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); } 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; } } 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"); } /** * @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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } 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 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 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 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 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 implementation contract ASTROPUP is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'ASTROPUP'; string private _symbol = 'APUP'; uint8 private _decimals = 9; // Tax and team fees will start at 0 so we don't have a big impact when deploying to Uniswap // Team wallet address is null but the method to set the address is exposed uint256 private _taxFee = 10; uint256 private _teamFee = 10; uint256 private _previousTaxFee = _taxFee; uint256 private _previousTeamFee = _teamFee; address payable public _teamWalletAddress; address payable public _developerWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 100000000000000e9; // We will set a minimum amount of tokens to be swaped => 5M uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable teamWalletAddress, address payable developerWalletAddress) public { _teamWalletAddress = teamWalletAddress; _developerWalletAddress = developerWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } 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 _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public 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 isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousTeamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousTeamFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(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"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(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"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap? // also, don't get caught in a circular team event. // also, don't swap if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { // We need to swap the current tokens to ETH and send to the team wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } //transfer amount, it will take tax and team fee _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // 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 sendETHToTeam(uint256 amount) private { _teamWalletAddress.transfer(amount.div(2)); _developerWalletAddress.transfer(amount.div(2)); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToTeam(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25'); _taxFee = taxFee; } function _setTeamFee(uint256 teamFee) external onlyOwner() { require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25'); _teamFee = teamFee; } function _setTeamWallet(address payable teamWalletAddress) external onlyOwner() { _teamWalletAddress = teamWalletAddress; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9'); _maxTxAmount = maxTxAmount; } }
Contract implementation Tax and team fees will start at 0 so we don't have a big impact when deploying to Uniswap Team wallet address is null but the method to set the address is exposed We will set a minimum amount of tokens to be swaped => 5M
contract ASTROPUP is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'ASTROPUP'; string private _symbol = 'APUP'; uint8 private _decimals = 9; uint256 private _taxFee = 10; uint256 private _teamFee = 10; uint256 private _previousTaxFee = _taxFee; uint256 private _previousTeamFee = _teamFee; address payable public _teamWalletAddress; address payable public _developerWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 100000000000000e9; uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable teamWalletAddress, address payable developerWalletAddress) public { _teamWalletAddress = teamWalletAddress; _developerWalletAddress = developerWalletAddress; _rOwned[_msgSender()] = _rTotal; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } 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 _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public 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 isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousTeamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousTeamFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(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"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(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"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } function _transfer(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"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } function _transfer(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"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } function _transfer(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"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } bool takeFee = true; function _transfer(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"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } _tokenTransfer(sender,recipient,amount,takeFee); function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function sendETHToTeam(uint256 amount) private { _teamWalletAddress.transfer(amount.div(2)); _developerWalletAddress.transfer(amount.div(2)); } function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToTeam(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25'); _taxFee = taxFee; } function _setTeamFee(uint256 teamFee) external onlyOwner() { require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25'); _teamFee = teamFee; } function _setTeamWallet(address payable teamWalletAddress) external onlyOwner() { _teamWalletAddress = teamWalletAddress; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9'); _maxTxAmount = maxTxAmount; } }
611,922
[ 1, 4625, 348, 7953, 560, 30, 225, 13456, 4471, 18240, 471, 5927, 1656, 281, 903, 787, 622, 374, 1427, 732, 2727, 1404, 1240, 279, 5446, 15800, 1347, 7286, 310, 358, 1351, 291, 91, 438, 10434, 9230, 1758, 353, 446, 1496, 326, 707, 358, 444, 326, 1758, 353, 16265, 1660, 903, 444, 279, 5224, 3844, 434, 2430, 358, 506, 1352, 5994, 516, 1381, 49, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6835, 9183, 12578, 3079, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 3639, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 3639, 1450, 5267, 364, 1758, 31, 203, 203, 3639, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 3639, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 3639, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 3639, 1758, 8526, 3238, 389, 24602, 31, 203, 377, 203, 3639, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 3639, 2254, 5034, 3238, 389, 88, 5269, 273, 15088, 9449, 380, 1728, 636, 29, 31, 203, 3639, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 3639, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 203, 3639, 533, 3238, 389, 529, 273, 296, 9053, 12578, 3079, 13506, 203, 3639, 533, 3238, 389, 7175, 273, 296, 2203, 3079, 13506, 203, 3639, 2254, 28, 3238, 389, 31734, 273, 2468, 31, 203, 540, 203, 3639, 2254, 5034, 3238, 389, 8066, 14667, 273, 1728, 31, 7010, 3639, 2254, 5034, 3238, 389, 10035, 14667, 273, 1728, 31, 203, 3639, 2254, 5034, 3238, 389, 11515, 7731, 14667, 273, 389, 8066, 14667, 31, 203, 3639, 2254, 5034, 3238, 389, 11515, 8689, 14667, 273, 389, 10035, 14667, 31, 203, 203, 3639, 1758, 8843, 429, 1071, 389, 10035, 16936, 1887, 31, 203, 3639, 1758, 8843, 429, 1071, 389, 23669, 16936, 1887, 31, 203, 540, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 3639, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 3639, 1426, 316, 12521, 273, 629, 31, 203, 3639, 1426, 1071, 7720, 1526, 273, 638, 31, 203, 203, 3639, 2254, 5034, 3238, 389, 1896, 4188, 6275, 273, 2130, 12648, 2787, 73, 29, 31, 203, 3639, 2254, 5034, 3238, 389, 2107, 951, 5157, 774, 11688, 1290, 8689, 273, 1381, 380, 1728, 636, 23, 380, 1728, 636, 29, 31, 203, 203, 3639, 871, 5444, 5157, 4649, 12521, 7381, 12, 11890, 5034, 1131, 5157, 4649, 12521, 1769, 203, 3639, 871, 12738, 1526, 7381, 12, 6430, 3696, 1769, 203, 203, 3639, 9606, 2176, 1986, 12521, 288, 203, 5411, 316, 12521, 273, 638, 31, 203, 5411, 389, 31, 203, 5411, 316, 12521, 273, 629, 31, 203, 3639, 289, 203, 203, 3639, 3885, 261, 2867, 8843, 429, 5927, 16936, 1887, 16, 1758, 8843, 429, 8751, 16936, 1887, 13, 1071, 288, 203, 5411, 389, 10035, 16936, 1887, 273, 5927, 16936, 1887, 31, 203, 5411, 389, 23669, 16936, 1887, 273, 8751, 16936, 1887, 31, 203, 5411, 389, 86, 5460, 329, 63, 67, 3576, 12021, 1435, 65, 273, 389, 86, 5269, 31, 203, 203, 5411, 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, 10756, 203, 7734, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 203, 5411, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 5411, 389, 291, 16461, 1265, 14667, 63, 8443, 1435, 65, 273, 638, 31, 203, 5411, 389, 291, 16461, 1265, 14667, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 203, 5411, 3626, 12279, 12, 2867, 12, 20, 3631, 389, 3576, 12021, 9334, 389, 88, 5269, 1769, 203, 3639, 289, 203, 203, 3639, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 5411, 327, 389, 529, 31, 203, 3639, 289, 203, 203, 3639, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 5411, 327, 389, 7175, 31, 203, 3639, 289, 203, 203, 3639, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 5411, 327, 389, 31734, 31, 203, 3639, 289, 203, 203, 3639, 445, 2078, 3088, 1283, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 5411, 327, 389, 88, 5269, 31, 203, 3639, 289, 203, 203, 3639, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 5411, 309, 261, 67, 291, 16461, 63, 4631, 5717, 327, 389, 88, 5460, 329, 63, 4631, 15533, 203, 5411, 327, 1147, 1265, 9801, 24899, 86, 5460, 329, 63, 4631, 19226, 203, 3639, 289, 203, 203, 3639, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 1071, 3849, 1135, 261, 6430, 13, 288, 203, 5411, 389, 13866, 24899, 3576, 12021, 9334, 8027, 16, 3844, 1769, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 203, 3639, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 5411, 327, 389, 5965, 6872, 63, 8443, 6362, 87, 1302, 264, 15533, 203, 3639, 289, 203, 203, 3639, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 1071, 3849, 1135, 261, 6430, 13, 288, 203, 5411, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 3844, 1769, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 203, 3639, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 1071, 3849, 1135, 261, 6430, 13, 288, 203, 5411, 389, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 5411, 389, 12908, 537, 12, 15330, 16, 389, 3576, 12021, 9334, 389, 5965, 6872, 63, 15330, 6362, 67, 3576, 12021, 1435, 8009, 1717, 12, 8949, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 1699, 1359, 7923, 1769, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 203, 3639, 445, 10929, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 3096, 620, 13, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 5411, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 389, 5965, 6872, 63, 67, 3576, 12021, 1435, 2 ]
./full_match/5/0xed6b2Ad30E38111272417239731e869470D5D900/sources/contracts/WorldPassNFT.sol
* Override to limit roles./
function _canMint() internal view virtual override returns (bool) { return hasRole(MINTER_ROLE, msg.sender); }
1,888,462
[ 1, 4625, 348, 7953, 560, 30, 380, 1439, 358, 1800, 4900, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4169, 49, 474, 1435, 2713, 1476, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 28335, 12, 6236, 2560, 67, 16256, 16, 1234, 18, 15330, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x5625E1Bbe09AB07a0E2a73f2bB5D169838Fd5CCb/sources/home/liam/EtherProjects/YFN/core/contracts/YFNOEngine.sol
Return reward multiplier over the given _from to _to block, yield halved when reach point.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if( yfno.totalSupply() >= halvingYfnooSupply){ return _to.sub(_from).div(2); } if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _to.sub(_from); return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } }
15,734,130
[ 1, 4625, 348, 7953, 560, 30, 225, 2000, 19890, 15027, 1879, 326, 864, 389, 2080, 358, 389, 869, 1203, 16, 2824, 19514, 2155, 1347, 9287, 1634, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 31863, 5742, 12, 11890, 5034, 389, 2080, 16, 2254, 5034, 389, 869, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 12, 677, 74, 2135, 18, 4963, 3088, 1283, 1435, 1545, 19514, 6282, 61, 74, 2135, 83, 3088, 1283, 15329, 203, 5411, 327, 389, 869, 18, 1717, 24899, 2080, 2934, 2892, 12, 22, 1769, 203, 3639, 289, 203, 3639, 309, 261, 67, 869, 1648, 324, 22889, 1638, 1768, 13, 288, 203, 5411, 327, 389, 869, 18, 1717, 24899, 2080, 2934, 16411, 12, 38, 673, 3378, 67, 24683, 2053, 654, 1769, 203, 5411, 327, 389, 869, 18, 1717, 24899, 2080, 1769, 203, 5411, 327, 324, 22889, 1638, 1768, 18, 1717, 24899, 2080, 2934, 16411, 12, 38, 673, 3378, 67, 24683, 2053, 654, 2934, 1289, 12, 203, 7734, 389, 869, 18, 1717, 12, 18688, 407, 1638, 1768, 13, 203, 5411, 11272, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /** * @dev A library for working with mutable byte buffers in Solidity. * * Byte buffers are mutable and expandable, and provide a variety of primitives * for writing to them. At any time you can fetch a bytes object containing the * current contents of the buffer. The bytes object should not be stored between * operations, as it may change due to resizing of the buffer. */ library Buffer { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly {let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns(buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if (a > b) { return a; } return b; } /** * @dev Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint dest; uint src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } src := add(data, 32) } // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) { if (off >= buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { return writeInt(buf, buf.buf.length, data, len); } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.appendUint8(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.appendUint8(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.appendUint8(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.appendUint8(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /** * @title Library for common Chainlink functions * @dev Uses imported CBOR library for encoding to buffer */ library Chainlink { uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase using CBOR for Buffer.buffer; struct Request { bytes32 id; address callbackAddress; bytes4 callbackFunctionId; uint256 nonce; Buffer.buffer buf; } /** * @notice Initializes a Chainlink request * @dev Sets the ID, callback address, and callback function signature on the request * @param self The uninitialized request * @param _id The Job Specification ID * @param _callbackAddress The callback address * @param _callbackFunction The callback function signature * @return The initialized request */ function initialize( Request memory self, bytes32 _id, address _callbackAddress, bytes4 _callbackFunction ) internal pure returns (Chainlink.Request memory) { Buffer.init(self.buf, defaultBufferSize); self.id = _id; self.callbackAddress = _callbackAddress; self.callbackFunctionId = _callbackFunction; return self; } /** * @notice Sets the data for the buffer without encoding CBOR on-chain * @dev CBOR can be closed with curly-brackets {} or they can be left off * @param self The initialized request * @param _data The CBOR data */ function setBuffer(Request memory self, bytes _data) internal pure { Buffer.init(self.buf, _data.length); Buffer.append(self.buf, _data); } /** * @notice Adds a string value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The string value to add */ function add(Request memory self, string _key, string _value) internal pure { self.buf.encodeString(_key); self.buf.encodeString(_value); } /** * @notice Adds a bytes value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The bytes value to add */ function addBytes(Request memory self, string _key, bytes _value) internal pure { self.buf.encodeString(_key); self.buf.encodeBytes(_value); } /** * @notice Adds a int256 value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The int256 value to add */ function addInt(Request memory self, string _key, int256 _value) internal pure { self.buf.encodeString(_key); self.buf.encodeInt(_value); } /** * @notice Adds a uint256 value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The uint256 value to add */ function addUint(Request memory self, string _key, uint256 _value) internal pure { self.buf.encodeString(_key); self.buf.encodeUInt(_value); } /** * @notice Adds an array of strings to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _values The array of string values to add */ function addStringArray(Request memory self, string _key, string[] memory _values) internal pure { self.buf.encodeString(_key); self.buf.startArray(); for (uint256 i = 0; i < _values.length; i++) { self.buf.encodeString(_values[i]); } self.buf.endSequence(); } } interface ENSInterface { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external; function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } interface LinkTokenInterface { function allowance(address owner, address spender) external returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external returns (uint256 balance); function decimals() external returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external returns (string tokenName); function symbol() external returns (string tokenSymbol); function totalSupply() external returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } interface ChainlinkRequestInterface { function oracleRequest( address sender, uint256 payment, bytes32 id, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 version, bytes data ) external; function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunctionId, uint256 expiration ) external; } interface PointerInterface { function getAddress() external view returns (address); } contract ENSResolver { function addr(bytes32 node) public view returns (address); } /** * @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) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } 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; } } /** * @title The ChainlinkClient contract * @notice Contract writers can inherit this contract in order to create requests for the * Chainlink network */ contract ChainlinkClient { using Chainlink for Chainlink.Request; using SafeMath for uint256; uint256 constant internal LINK = 10**18; uint256 constant private AMOUNT_OVERRIDE = 0; address constant private SENDER_OVERRIDE = 0x0; uint256 constant private ARGS_VERSION = 1; bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link"); bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle"); address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; ENSInterface private ens; bytes32 private ensNode; LinkTokenInterface private link; ChainlinkRequestInterface private oracle; uint256 private requests = 1; mapping(bytes32 => address) private pendingRequests; event ChainlinkRequested(bytes32 indexed id); event ChainlinkFulfilled(bytes32 indexed id); event ChainlinkCancelled(bytes32 indexed id); /** * @notice Creates a request that can hold additional parameters * @param _specId The Job Specification ID that the request will be created for * @param _callbackAddress The callback address that the response will be sent to * @param _callbackFunctionSignature The callback function signature to use for the callback address * @return A Chainlink Request struct in memory */ function buildChainlinkRequest( bytes32 _specId, address _callbackAddress, bytes4 _callbackFunctionSignature ) internal pure returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev Calls `chainlinkRequestTo` with the stored oracle address * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return The request ID */ function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32) { return sendChainlinkRequestTo(oracle, _req, _payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param _oracle The address of the oracle for the request * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return The request ID */ function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32 requestId) { requestId = keccak256(abi.encodePacked(this, requests)); _req.nonce = requests; pendingRequests[requestId] = _oracle; emit ChainlinkRequested(requestId); require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle"); requests += 1; return requestId; } /** * @notice Allows a request to be cancelled if it has not been fulfilled * @dev Requires keeping track of the expiration value emitted from the oracle contract. * Deletes the request from the `pendingRequests` mapping. * Emits ChainlinkCancelled event. * @param _requestId The request ID * @param _payment The amount of LINK sent for the request * @param _callbackFunc The callback function specified for the request * @param _expiration The time of the expiration for the request */ function cancelChainlinkRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) internal { ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]); delete pendingRequests[_requestId]; emit ChainlinkCancelled(_requestId); requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration); } /** * @notice Sets the stored oracle address * @param _oracle The address of the oracle contract */ function setChainlinkOracle(address _oracle) internal { oracle = ChainlinkRequestInterface(_oracle); } /** * @notice Sets the LINK token address * @param _link The address of the LINK token contract */ function setChainlinkToken(address _link) internal { link = LinkTokenInterface(_link); } /** * @notice Sets the Chainlink token address for the public * network as given by the Pointer contract */ function setPublicChainlinkToken() internal { setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress()); } /** * @notice Retrieves the stored address of the LINK token * @return The address of the LINK token */ function chainlinkTokenAddress() internal view returns (address) { return address(link); } /** * @notice Retrieves the stored address of the oracle contract * @return The address of the oracle contract */ function chainlinkOracleAddress() internal view returns (address) { return address(oracle); } /** * @notice Allows for a request which was created on another contract to be fulfilled * on this contract * @param _oracle The address of the oracle contract that will fulfill the request * @param _requestId The request ID used for the response */ function addChainlinkExternalRequest(address _oracle, bytes32 _requestId) internal notPendingRequest(_requestId) { pendingRequests[_requestId] = _oracle; } /** * @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS * @dev Accounts for subnodes having different resolvers * @param _ens The address of the ENS contract * @param _node The ENS node hash */ function useChainlinkWithENS(address _ens, bytes32 _node) internal { ens = ENSInterface(_ens); ensNode = _node; bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME)); ENSResolver resolver = ENSResolver(ens.resolver(linkSubnode)); setChainlinkToken(resolver.addr(linkSubnode)); updateChainlinkOracleWithENS(); } /** * @notice Sets the stored oracle contract with the address resolved by ENS * @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously */ function updateChainlinkOracleWithENS() internal { bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME)); ENSResolver resolver = ENSResolver(ens.resolver(oracleSubnode)); setChainlinkOracle(resolver.addr(oracleSubnode)); } /** * @notice Encodes the request to be sent to the oracle contract * @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types * will be validated in the oracle contract. * @param _req The initialized Chainlink Request * @return The bytes payload for the `transferAndCall` method */ function encodeRequest(Chainlink.Request memory _req) private view returns (bytes memory) { return abi.encodeWithSelector( oracle.oracleRequest.selector, SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent _req.id, _req.callbackAddress, _req.callbackFunctionId, _req.nonce, ARGS_VERSION, _req.buf.buf); } /** * @notice Ensures that the fulfillment is valid for this contract * @dev Use if the contract developer prefers methods instead of modifiers for validation * @param _requestId The request ID for fulfillment */ function validateChainlinkCallback(bytes32 _requestId) internal recordChainlinkFulfillment(_requestId) // solhint-disable-next-line no-empty-blocks {} /** * @dev Reverts if the sender is not the oracle of the request. * Emits ChainlinkFulfilled event. * @param _requestId The request ID for fulfillment */ modifier recordChainlinkFulfillment(bytes32 _requestId) { require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request"); delete pendingRequests[_requestId]; emit ChainlinkFulfilled(_requestId); _; } /** * @dev Reverts if the request is already pending * @param _requestId The request ID for fulfillment */ modifier notPendingRequest(bytes32 _requestId) { require(pendingRequests[_requestId] == address(0), "Request is already pending"); _; } } interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy); } library SignedSafeMath { /** * @dev Adds two int256s and makes sure the result doesn't overflow. Signed * integers aren't supported by the SafeMath library, thus this method * @param _a The first number to be added * @param _a The second number to be added */ 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; } } /** * @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; } } /** * @title An example Chainlink contract with aggregation * @notice Requesters can use this contract as a framework for creating * requests to multiple Chainlink nodes and running aggregation * as the contract receives answers. */ contract Aggregator is AggregatorInterface, ChainlinkClient, Ownable { using SignedSafeMath for int256; struct Answer { uint128 minimumResponses; uint128 maxResponses; int256[] responses; } event ResponseReceived(int256 indexed response, uint256 indexed answerId, address indexed sender); int256 private currentAnswerValue; uint256 private updatedTimestampValue; uint256 private latestCompletedAnswer; uint128 public paymentAmount; uint128 public minimumResponses; bytes32[] public jobIds; address[] public oracles; uint256 private answerCounter = 1; mapping(address => bool) public authorizedRequesters; mapping(bytes32 => uint256) private requestAnswers; mapping(uint256 => Answer) private answers; mapping(uint256 => int256) private currentAnswers; mapping(uint256 => uint256) private updatedTimestamps; uint256 constant private MAX_ORACLE_COUNT = 45; /** * @notice Deploy with the address of the LINK token and arrays of matching * length containing the addresses of the oracles and their corresponding * Job IDs. * @dev Sets the LinkToken address for the network, addresses of the oracles, * and jobIds in storage. * @param _link The address of the LINK token * @param _paymentAmount the amount of LINK to be sent to each oracle for each request * @param _minimumResponses the minimum number of responses * before an answer will be calculated * @param _oracles An array of oracle addresses * @param _jobIds An array of Job IDs */ constructor( address _link, uint128 _paymentAmount, uint128 _minimumResponses, address[] _oracles, bytes32[] _jobIds ) public Ownable() { setChainlinkToken(_link); updateRequestDetails(_paymentAmount, _minimumResponses, _oracles, _jobIds); } /** * @notice Creates a Chainlink request for each oracle in the oracles array. * @dev This example does not include request parameters. Reference any documentation * associated with the Job IDs used to determine the required parameters per-request. */ function requestRateUpdate() external ensureAuthorizedRequester() { Chainlink.Request memory request; bytes32 requestId; uint256 oraclePayment = paymentAmount; for (uint i = 0; i < oracles.length; i++) { request = buildChainlinkRequest(jobIds[i], this, this.chainlinkCallback.selector); requestId = sendChainlinkRequestTo(oracles[i], request, oraclePayment); requestAnswers[requestId] = answerCounter; } answers[answerCounter].minimumResponses = minimumResponses; answers[answerCounter].maxResponses = uint128(oracles.length); answerCounter = answerCounter.add(1); emit NewRound(answerCounter, msg.sender); } /** * @notice Receives the answer from the Chainlink node. * @dev This function can only be called by the oracle that received the request. * @param _clRequestId The Chainlink request ID associated with the answer * @param _response The answer provided by the Chainlink node */ function chainlinkCallback(bytes32 _clRequestId, int256 _response) external { validateChainlinkCallback(_clRequestId); uint256 answerId = requestAnswers[_clRequestId]; delete requestAnswers[_clRequestId]; answers[answerId].responses.push(_response); emit ResponseReceived(_response, answerId, msg.sender); updateLatestAnswer(answerId); deleteAnswer(answerId); } /** * @notice Updates the arrays of oracles and jobIds with new values, * overwriting the old values. * @dev Arrays are validated to be equal length. * @param _paymentAmount the amount of LINK to be sent to each oracle for each request * @param _minimumResponses the minimum number of responses * before an answer will be calculated * @param _oracles An array of oracle addresses * @param _jobIds An array of Job IDs */ function updateRequestDetails( uint128 _paymentAmount, uint128 _minimumResponses, address[] _oracles, bytes32[] _jobIds ) public onlyOwner() validateAnswerRequirements(_minimumResponses, _oracles, _jobIds) { paymentAmount = _paymentAmount; minimumResponses = _minimumResponses; jobIds = _jobIds; oracles = _oracles; } /** * @notice Allows the owner of the contract to withdraw any LINK balance * available on the contract. * @dev The contract will need to have a LINK balance in order to create requests. * @param _recipient The address to receive the LINK tokens * @param _amount The amount of LINK to send from the contract */ function transferLINK(address _recipient, uint256 _amount) public onlyOwner() { LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress()); require(linkToken.transfer(_recipient, _amount), "LINK transfer failed"); } /** * @notice Called by the owner to permission other addresses to generate new * requests to oracles. * @param _requester the address whose permissions are being set * @param _allowed boolean that determines whether the requester is * permissioned or not */ function setAuthorization(address _requester, bool _allowed) external onlyOwner() { authorizedRequesters[_requester] = _allowed; } /** * @notice Cancels an outstanding Chainlink request. * The oracle contract requires the request ID and additional metadata to * validate the cancellation. Only old answers can be cancelled. * @param _requestId is the identifier for the chainlink request being cancelled * @param _payment is the amount of LINK paid to the oracle for the request * @param _expiration is the time when the request expires */ function cancelRequest( bytes32 _requestId, uint256 _payment, uint256 _expiration ) external ensureAuthorizedRequester() { uint256 answerId = requestAnswers[_requestId]; require(answerId < latestCompletedAnswer, "Cannot modify an in-progress answer"); delete requestAnswers[_requestId]; answers[answerId].responses.push(0); deleteAnswer(answerId); cancelChainlinkRequest( _requestId, _payment, this.chainlinkCallback.selector, _expiration ); } /** * @notice Called by the owner to kill the contract. This transfers all LINK * balance and ETH balance (if there is any) to the owner. */ function destroy() external onlyOwner() { LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress()); transferLINK(owner, linkToken.balanceOf(address(this))); selfdestruct(owner); } /** * @dev Performs aggregation of the answers received from the Chainlink nodes. * Assumes that at least half the oracles are honest and so can't contol the * middle of the ordered responses. * @param _answerId The answer ID associated with the group of requests */ function updateLatestAnswer(uint256 _answerId) private ensureMinResponsesReceived(_answerId) ensureOnlyLatestAnswer(_answerId) { uint256 responseLength = answers[_answerId].responses.length; uint256 middleIndex = responseLength.div(2); int256 currentAnswerTemp; if (responseLength % 2 == 0) { int256 median1 = quickselect(answers[_answerId].responses, middleIndex); int256 median2 = quickselect(answers[_answerId].responses, middleIndex.add(1)); // quickselect is 1 indexed currentAnswerTemp = median1.add(median2) / 2; // signed integers are not supported by SafeMath } else { currentAnswerTemp = quickselect(answers[_answerId].responses, middleIndex.add(1)); // quickselect is 1 indexed } currentAnswerValue = currentAnswerTemp; latestCompletedAnswer = _answerId; updatedTimestampValue = now; updatedTimestamps[_answerId] = now; currentAnswers[_answerId] = currentAnswerTemp; emit AnswerUpdated(currentAnswerTemp, _answerId, now); } /** * @notice get the most recently reported answer */ function latestAnswer() external view returns (int256) { return currentAnswers[latestCompletedAnswer]; } /** * @notice get the last updated at block timestamp */ function latestTimestamp() external view returns (uint256) { return updatedTimestamps[latestCompletedAnswer]; } /** * @notice get past rounds answers * @param _roundId the answer number to retrieve the answer for */ function getAnswer(uint256 _roundId) external view returns (int256) { return currentAnswers[_roundId]; } /** * @notice get block timestamp when an answer was last updated * @param _roundId the answer number to retrieve the updated timestamp for */ function getTimestamp(uint256 _roundId) external view returns (uint256) { return updatedTimestamps[_roundId]; } /** * @notice get the latest completed round where the answer was updated */ function latestRound() external view returns (uint256) { return latestCompletedAnswer; } /** * @dev Returns the kth value of the ordered array * See: http://www.cs.yale.edu/homes/aspnes/pinewiki/QuickSelect.html * @param _a The list of elements to pull from * @param _k The index, 1 based, of the elements you want to pull from when ordered */ function quickselect(int256[] memory _a, uint256 _k) private pure returns (int256) { int256[] memory a = _a; uint256 k = _k; uint256 aLen = a.length; int256[] memory a1 = new int256[](aLen); int256[] memory a2 = new int256[](aLen); uint256 a1Len; uint256 a2Len; int256 pivot; uint256 i; while (true) { pivot = a[aLen.div(2)]; a1Len = 0; a2Len = 0; for (i = 0; i < aLen; i++) { if (a[i] < pivot) { a1[a1Len] = a[i]; a1Len++; } else if (a[i] > pivot) { a2[a2Len] = a[i]; a2Len++; } } if (k <= a1Len) { aLen = a1Len; (a, a1) = swap(a, a1); } else if (k > (aLen.sub(a2Len))) { k = k.sub(aLen.sub(a2Len)); aLen = a2Len; (a, a2) = swap(a, a2); } else { return pivot; } } } /** * @dev Swaps the pointers to two uint256 arrays in memory * @param _a The pointer to the first in memory array * @param _b The pointer to the second in memory array */ function swap(int256[] memory _a, int256[] memory _b) private pure returns(int256[] memory, int256[] memory) { return (_b, _a); } /** * @dev Cleans up the answer record if all responses have been received. * @param _answerId The identifier of the answer to be deleted */ function deleteAnswer(uint256 _answerId) private ensureAllResponsesReceived(_answerId) { delete answers[_answerId]; } /** * @dev Prevents taking an action if the minimum number of responses has not * been received for an answer. * @param _answerId The the identifier of the answer that keeps track of the responses. */ modifier ensureMinResponsesReceived(uint256 _answerId) { if (answers[_answerId].responses.length >= answers[_answerId].minimumResponses) { _; } } /** * @dev Prevents taking an action if not all responses are received for an answer. * @param _answerId The the identifier of the answer that keeps track of the responses. */ modifier ensureAllResponsesReceived(uint256 _answerId) { if (answers[_answerId].responses.length == answers[_answerId].maxResponses) { _; } } /** * @dev Prevents taking an action if a newer answer has been recorded. * @param _answerId The current answer's identifier. * Answer IDs are in ascending order. */ modifier ensureOnlyLatestAnswer(uint256 _answerId) { if (latestCompletedAnswer <= _answerId) { _; } } /** * @dev Ensures corresponding number of oracles and jobs. * @param _oracles The list of oracles. * @param _jobIds The list of jobs. */ modifier validateAnswerRequirements( uint256 _minimumResponses, address[] _oracles, bytes32[] _jobIds ) { require(_oracles.length <= MAX_ORACLE_COUNT, "cannot have more than 45 oracles"); require(_oracles.length >= _minimumResponses, "must have at least as many oracles as responses"); require(_oracles.length == _jobIds.length, "must have exactly as many oracles as job IDs"); _; } /** * @dev Reverts if `msg.sender` is not authorized to make requests. */ modifier ensureAuthorizedRequester() { require(authorizedRequesters[msg.sender] || msg.sender == owner, "Not an authorized address for creating requests"); _; } }
* @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the capacity of the buffer. @param buf The buffer to append to. @param off The offset to write at. @param data The data to append. @return The original buffer, for chaining./
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); }
464,590
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 30053, 279, 1731, 3462, 358, 326, 1613, 18, 1124, 3128, 309, 9957, 1427, 4102, 9943, 326, 1377, 7519, 434, 326, 1613, 18, 632, 891, 1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, 3778, 13, 288, 203, 565, 327, 1045, 12, 4385, 16, 3397, 16, 1731, 1578, 12, 892, 3631, 4200, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "../../v1/Auction.sol"; import "../../v1/FixedPrice.sol"; import "../../v1/OpenOffers.sol"; interface IFarbeMarketplace { function assignToInstitution(address _institutionAddress, uint256 _tokenId, address _owner) external; function getIsFarbeMarketplace() external view returns (bool); } /** * @title ERC721 contract implementation * @dev Implements the ERC721 interface for the Farbe artworks */ contract FarbeArtV3Upgradeable is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, AccessControlUpgradeable { // counter for tracking token IDs CountersUpgradeable.Counter internal _tokenIdCounter; // details of the artwork struct artworkDetails { address tokenCreator; uint16 creatorCut; bool isSecondarySale; } // mapping of token id to original creator mapping(uint256 => artworkDetails) public tokenIdToDetails; // not using this here anymore, it has been moved to the farbe marketplace contract // platform cut on primary sales in %age * 10 uint16 public platformCutOnPrimarySales; // constant for defining the minter role bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // reference to auction contract AuctionSale public auctionSale; // reference to fixed price contract FixedPriceSale public fixedPriceSale; // reference to open offer contract OpenOffersSale public openOffersSale; event TokenUriChanged(uint256 tokenId, string uri); /** * @dev Initializer for the ERC721 contract */ function initialize() public initializer { __ERC721_init("FarbeArt", "FBA"); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); } /** * @dev Implementation of ERC721Enumerable */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev Destroy (burn) the NFT * @param tokenId The ID of the token to burn */ function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { super._burn(tokenId); } /** * @dev Returns the Uniform Resource Identifier (URI) for the token * @param tokenId ID of the token to return URI of * @return URI for the token */ function tokenURI(uint256 tokenId) public view override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(tokenId); } /** * @dev Implementation of the ERC165 interface * @param interfaceId The Id of the interface to check support for */ function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } uint256[1000] private __gap; } /** * @title Farbe NFT sale contract * @dev Extension of the FarbeArt contract to add sale functionality */ contract FarbeArtSaleV3Upgradeable is FarbeArtV3Upgradeable { /** * @dev Only allow owner to execute if no one (gallery) has been approved * @param _tokenId Id of the token to check approval and ownership of */ modifier onlyOwnerOrApproved(uint256 _tokenId) { if(getApproved(_tokenId) == address(0)){ require(ownerOf(_tokenId) == msg.sender, "Not owner or approved"); } else { require(getApproved(_tokenId) == msg.sender, "Only approved can list, revoke approval to list yourself"); } _; } /** * @dev Make sure the starting time is not greater than 60 days * @param _startingTime starting time of the sale in UNIX timestamp */ modifier onlyValidStartingTime(uint64 _startingTime) { if(_startingTime > block.timestamp) { require(_startingTime - block.timestamp <= 60 days, "Start time too far"); } _; } using CountersUpgradeable for CountersUpgradeable.Counter; /** * @dev Function to mint an artwork as NFT. If no gallery is approved, the parameter is zero * @param _to The address to send the minted NFT * @param _creatorCut The cut that the original creator will take on secondary sales */ function safeMint( address _to, address _galleryAddress, uint8 _numberOfCopies, uint16 _creatorCut, string[] memory _tokenURI ) public { require(hasRole(MINTER_ROLE, msg.sender), "does not have minter role"); require(_tokenURI.length == _numberOfCopies, "Metadata URIs not equal to editions"); for(uint i = 0; i < _numberOfCopies; i++){ // mint the token _safeMint(_to, _tokenIdCounter.current()); // approve the gallery (0 if no gallery authorized) setApprovalForAll(farbeMarketplace, true); // set the token URI _setTokenURI(_tokenIdCounter.current(), _tokenURI[i]); // track token creator tokenIdToDetails[_tokenIdCounter.current()].tokenCreator = _to; // track creator's cut tokenIdToDetails[_tokenIdCounter.current()].creatorCut = _creatorCut; if(_galleryAddress != address(0)){ IFarbeMarketplace(farbeMarketplace).assignToInstitution(_galleryAddress, _tokenIdCounter.current(), msg.sender); } // increment tokenId _tokenIdCounter.increment(); } } /** * @dev Initializer for the FarbeArtSale contract * name for initializer changed from "initialize" to "farbeInitialze" as it was causing override error with the initializer of NFT contract */ function farbeInitialize() public initializer { FarbeArtV3Upgradeable.initialize(); } function burn(uint256 tokenId) external { // must be owner require(ownerOf(tokenId) == msg.sender); _burn(tokenId); } /** * @dev Change the tokenUri of the token. Can only be changed when the creator is the owner * @param _tokenURI New Uri of the token * @param _tokenId Id of the token to change Uri of */ function changeTokenUri(string memory _tokenURI, uint256 _tokenId) external { // must be owner and creator require(ownerOf(_tokenId) == msg.sender, "Not owner"); require(tokenIdToDetails[_tokenId].tokenCreator == msg.sender, "Not creator"); _setTokenURI(_tokenId, _tokenURI); emit TokenUriChanged( uint256(_tokenId), string(_tokenURI) ); } function setFarbeMarketplaceAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) { farbeMarketplace = _address; } function getTokenCreatorAddress(uint256 _tokenId) public view returns(address) { return tokenIdToDetails[_tokenId].tokenCreator; } function getTokenCreatorCut(uint256 _tokenId) public view returns(uint16) { return tokenIdToDetails[_tokenId].creatorCut; } uint256[1000] private __gap; // #sbt upgrades-plugin does not support __gaps for now // so including the new variable here address public farbeMarketplace; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 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 initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _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 { 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 = 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); } /** * @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); } /** * @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 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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).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 {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable { function __ERC721URIStorage_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721URIStorage_init_unchained(); } function __ERC721URIStorage_init_unchained() internal initializer { } using StringsUpgradeable 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]; } } uint256[49] private __gap; } // 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 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; } } // SPDX-License-Identifier: MIT 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 a proxied contract can't have 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. */ 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() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) 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 Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @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 override 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 override onlyRole(getRoleAdmin(role)) { _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 override onlyRole(getRoleAdmin(role)) { _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 override { 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, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "./FarbeArt.sol"; import "./SaleBase.sol"; /** * @title Base auction contract * @dev This is the base auction contract which implements the auction functionality */ contract AuctionBase is SaleBase { using Address for address payable; // auction struct to keep track of the auctions struct Auction { address seller; address creator; address gallery; address buyer; uint128 currentPrice; uint64 duration; uint64 startedAt; uint16 creatorCut; uint16 platformCut; uint16 galleryCut; } // mapping for tokenId to its auction mapping(uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); /** * @dev Add the auction to the mapping and emit the AuctionCreated event, duration must meet the requirements * @param _tokenId ID of the token to auction * @param _auction Reference to the auction struct to add to the mapping */ function _addAuction(uint256 _tokenId, Auction memory _auction) internal { // check minimum and maximum time requirements require(_auction.duration >= 1 hours && _auction.duration <= 30 days, "time requirement failed"); // update mapping tokenIdToAuction[_tokenId] = _auction; // emit event emit AuctionCreated( uint256(_tokenId), uint256(_auction.currentPrice), uint256(_auction.duration) ); } /** * @dev Remove the auction from the mapping (sets everything to zero/false) * @param _tokenId ID of the token to remove auction of */ function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /** * @dev Internal function to check the current price of the auction * @param auction Reference to the auction to check price of * @return uint128 The current price of the auction */ function _currentPrice(Auction storage auction) internal view returns (uint128) { return (auction.currentPrice); } /** * @dev Internal function to return the bid to the previous bidder if there was one * @param _destination Address of the previous bidder * @param _amount Amount to return to the previous bidder */ function _returnBid(address payable _destination, uint256 _amount) private { // zero address means there was no previous bidder if (_destination != address(0)) { _destination.sendValue(_amount); } } /** * @dev Internal function to check if an auction started. By default startedAt is at 0 * @param _auction Reference to the auction struct to check * @return bool Weather the auction has started */ function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0 && _auction.startedAt <= block.timestamp); } /** * @dev Internal function to implement the bid functionality * @param _tokenId ID of the token to bid upon * @param _bidAmount Amount to bid */ function _bid(uint _tokenId, uint _bidAmount) internal { // get reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // check if the item is on auction require(_isOnAuction(auction), "Item is not on auction"); // check if auction time has ended uint256 secondsPassed = block.timestamp - auction.startedAt; require(secondsPassed <= auction.duration, "Auction time has ended"); // check if bid is higher than the previous one uint256 price = auction.currentPrice; require(_bidAmount > price, "Bid is too low"); // return the previous bidder's bid amount _returnBid(payable(auction.buyer), auction.currentPrice); // update the current bid amount and the bidder address auction.currentPrice = uint128(_bidAmount); auction.buyer = msg.sender; // if the bid is made in the last 15 minutes, increase the duration of the // auction so that the timer resets to 15 minutes uint256 timeRemaining = auction.duration - secondsPassed; if (timeRemaining <= 15 minutes) { uint256 timeToAdd = 15 minutes - timeRemaining; auction.duration += uint64(timeToAdd); } } /** * @dev Internal function to finish the auction after the auction time has ended * @param _tokenId ID of the token to finish auction of */ function _finishAuction(uint256 _tokenId) internal { // using storage for _isOnAuction Auction storage auction = tokenIdToAuction[_tokenId]; // check if token was on auction require(_isOnAuction(auction), "Token was not on auction"); // check if auction time has ended uint256 secondsPassed = block.timestamp - auction.startedAt; require(secondsPassed > auction.duration, "Auction hasn't ended"); // using struct to avoid stack too deep error Auction memory referenceAuction = auction; // delete the auction _removeAuction(_tokenId); // if there was no successful bid, return token to the seller if (referenceAuction.buyer == address(0)) { _transfer(referenceAuction.seller, _tokenId); emit AuctionSuccessful( _tokenId, 0, referenceAuction.seller ); } // if there was a successful bid, pay the seller and transfer the token to the buyer else { _payout( payable(referenceAuction.seller), payable(referenceAuction.creator), payable(referenceAuction.gallery), referenceAuction.creatorCut, referenceAuction.platformCut, referenceAuction.galleryCut, referenceAuction.currentPrice, _tokenId ); _transfer(referenceAuction.buyer, _tokenId); emit AuctionSuccessful( _tokenId, referenceAuction.currentPrice, referenceAuction.buyer ); } } /** * @dev This is an internal function to end auction meant to only be used as a safety * mechanism if an NFT got locked within the contract. Can only be called by the super admin * after a period f 7 days has passed since the auction ended * @param _tokenId Id of the token to end auction of * @param _nftBeneficiary Address to send the NFT to * @param _paymentBeneficiary Address to send the payment to */ function _forceFinishAuction( uint256 _tokenId, address _nftBeneficiary, address _paymentBeneficiary ) internal { // using storage for _isOnAuction Auction storage auction = tokenIdToAuction[_tokenId]; // check if token was on auction require(_isOnAuction(auction), "Token was not on auction"); // check if auction time has ended uint256 secondsPassed = block.timestamp - auction.startedAt; require(secondsPassed > auction.duration, "Auction hasn't ended"); // check if its been more than 7 days since auction ended require(secondsPassed - auction.duration >= 7 days); // using struct to avoid stack too deep error Auction memory referenceAuction = auction; // delete the auction _removeAuction(_tokenId); // transfer ether to the beneficiary payable(_paymentBeneficiary).sendValue(referenceAuction.currentPrice); // transfer nft to the nft beneficiary _transfer(_nftBeneficiary, _tokenId); } } /** * @title Auction sale contract that provides external functions * @dev Implements the external and public functions of the auction implementation */ contract AuctionSale is AuctionBase { // sanity check for the nft contract bool public isFarbeSaleAuction = true; // ERC721 interface id bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd); constructor(address _nftAddress, address _platformAddress) { // check NFT contract supports ERC721 interface FarbeArtSale candidateContract = FarbeArtSale(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); platformWalletAddress = _platformAddress; NFTContract = candidateContract; } /** * @dev External function to create auction. Called by the Farbe NFT contract * @param _tokenId ID of the token to create auction for * @param _startingPrice Starting price of the auction in wei * @param _duration Duration of the auction in seconds * @param _creator Address of the original creator of the NFT * @param _seller Address of the seller of the NFT * @param _gallery Address of the gallery of this auction, will be 0 if no gallery is involved * @param _creatorCut The cut that goes to the creator, as %age * 10 * @param _galleryCut The cut that goes to the gallery, as %age * 10 * @param _platformCut The cut that goes to the platform if it is a primary sale */ function createSale( uint256 _tokenId, uint128 _startingPrice, uint64 _startingTime, uint64 _duration, address _creator, address _seller, address _gallery, uint16 _creatorCut, uint16 _galleryCut, uint16 _platformCut ) external onlyFarbeContract { // create and add the auction Auction memory auction = Auction( _seller, _creator, _gallery, address(0), uint128(_startingPrice), uint64(_duration), _startingTime, _creatorCut, _platformCut, _galleryCut ); _addAuction(_tokenId, auction); } /** * @dev External payable bid function. Sellers can not bid on their own artworks * @param _tokenId ID of the token to bid on */ function bid(uint256 _tokenId) external payable { // do not allow sellers and galleries to bid on their own artwork require(tokenIdToAuction[_tokenId].seller != msg.sender && tokenIdToAuction[_tokenId].gallery != msg.sender, "Sellers and Galleries not allowed"); _bid(_tokenId, msg.value); } /** * @dev External function to finish the auction. Currently can be called by anyone TODO restrict access? * @param _tokenId ID of the token to finish auction of */ function finishAuction(uint256 _tokenId) external { _finishAuction(_tokenId); } /** * @dev External view function to get the details of an auction * @param _tokenId ID of the token to get the auction information of * @return seller Address of the seller * @return buyer Address of the buyer * @return currentPrice Current Price of the auction in wei * @return duration Duration of the auction in seconds * @return startedAt Unix timestamp for when the auction started */ function getAuction(uint256 _tokenId) external view returns ( address seller, address buyer, uint256 currentPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.buyer, auction.currentPrice, auction.duration, auction.startedAt ); } /** * @dev External view function to get the current price of an auction * @param _tokenId ID of the token to get the current price of * @return uint128 Current price of the auction in wei */ function getCurrentPrice(uint256 _tokenId) external view returns (uint128) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } /** * @dev Helper function for testing with timers TODO Remove this before deploying live * @param _tokenId ID of the token to get timers of */ function getTimers(uint256 _tokenId) external view returns ( uint256 saleStart, uint256 blockTimestamp, uint256 duration ) { Auction memory auction = tokenIdToAuction[_tokenId]; return (auction.startedAt, block.timestamp, auction.duration); } /** * @dev This is an internal function to end auction meant to only be used as a safety * mechanism if an NFT got locked within the contract. Can only be called by the super admin * after a period f 7 days has passed since the auction ended * @param _tokenId Id of the token to end auction of * @param _nftBeneficiary Address to send the NFT to * @param _paymentBeneficiary Address to send the payment to */ function forceFinishAuction( uint256 _tokenId, address _nftBeneficiary, address _paymentBeneficiary ) external onlyRole(DEFAULT_ADMIN_ROLE) { _forceFinishAuction(_tokenId, _nftBeneficiary, _paymentBeneficiary); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./SaleBase.sol"; /** * @title Base fixed price contract * @dev This is the base fixed price contract which implements the internal functionality */ contract FixedPriceBase is SaleBase { using Address for address payable; // fixed price sale struct to keep track of the sales struct FixedPrice { address seller; address creator; address gallery; uint128 fixedPrice; uint64 startedAt; uint16 creatorCut; uint16 platformCut; uint16 galleryCut; } // mapping for tokenId to its sale mapping(uint256 => FixedPrice) tokenIdToSale; event FixedSaleCreated(uint256 tokenId, uint256 fixedPrice); event FixedSaleSuccessful(uint256 tokenId, uint256 totalPrice, address winner); /** * @dev Add the sale to the mapping and emit the FixedSaleCreated event * @param _tokenId ID of the token to sell * @param _fixedSale Reference to the sale struct to add to the mapping */ function _addSale(uint256 _tokenId, FixedPrice memory _fixedSale) internal { // update mapping tokenIdToSale[_tokenId] = _fixedSale; // emit event emit FixedSaleCreated( uint256(_tokenId), uint256(_fixedSale.fixedPrice) ); } /** * @dev Remove the sale from the mapping (sets everything to zero/false) * @param _tokenId ID of the token to remove sale of */ function _removeSale(uint256 _tokenId) internal { delete tokenIdToSale[_tokenId]; } /** * @dev Internal function to check if a sale started. By default startedAt is at 0 * @param _fixedSale Reference to the sale struct to check * @return bool Weather the sale has started */ function _isOnSale(FixedPrice storage _fixedSale) internal view returns (bool) { return (_fixedSale.startedAt > 0 && _fixedSale.startedAt <= block.timestamp); } /** * @dev Internal function to buy a token on sale * @param _tokenId Id of the token to buy * @param _amount The amount in wei */ function _buy(uint256 _tokenId, uint256 _amount) internal { // get reference to the fixed price sale struct FixedPrice storage fixedSale = tokenIdToSale[_tokenId]; // check if the item is on sale require(_isOnSale(fixedSale), "Item is not on sale"); // check if sent amount is equal or greater than the set price require(_amount >= fixedSale.fixedPrice, "Amount sent is not enough to buy the token"); // using struct to avoid stack too deep error FixedPrice memory referenceFixedSale = fixedSale; // delete the sale _removeSale(_tokenId); // pay the seller, and distribute cuts _payout( payable(referenceFixedSale.seller), payable(referenceFixedSale.creator), payable(referenceFixedSale.gallery), referenceFixedSale.creatorCut, referenceFixedSale.platformCut, referenceFixedSale.galleryCut, _amount, _tokenId ); // transfer the token to the buyer _transfer(msg.sender, _tokenId); emit FixedSaleSuccessful(_tokenId, referenceFixedSale.fixedPrice, msg.sender); } /** * @dev Function to finish the sale. Can be called manually if no one bought the NFT. If * a gallery put the artwork on sale, only it can call this function. The super admin can * also call the function, this is implemented as a safety mechanism for the seller in case * the gallery becomes idle * @param _tokenId Id of the token to end sale of */ function _finishSale(uint256 _tokenId) internal { FixedPrice storage fixedSale = tokenIdToSale[_tokenId]; // only the gallery can finish the sale if it was the one to put it on auction if(fixedSale.gallery != address(0)) { require(fixedSale.gallery == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender)); } else { require(fixedSale.seller == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender)); } // check if token was on sale require(_isOnSale(fixedSale)); address seller = fixedSale.seller; // delete the sale _removeSale(_tokenId); // return the token to the seller _transfer(seller, _tokenId); } } /** * @title Fixed Price sale contract that provides external functions * @dev Implements the external and public functions of the Fixed price implementation */ contract FixedPriceSale is FixedPriceBase { // sanity check for the nft contract bool public isFarbeFixedSale = true; // ERC721 interface id bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd); constructor(address _nftAddress, address _platformAddress) { // check NFT contract supports ERC721 interface FarbeArtSale candidateContract = FarbeArtSale(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); platformWalletAddress = _platformAddress; NFTContract = candidateContract; } /** * @dev External function to create fixed sale. Called by the Farbe NFT contract * @param _tokenId ID of the token to create sale for * @param _fixedPrice Starting price of the sale in wei * @param _creator Address of the original creator of the NFT * @param _seller Address of the seller of the NFT * @param _gallery Address of the gallery of this sale, will be 0 if no gallery is involved * @param _creatorCut The cut that goes to the creator, as %age * 10 * @param _galleryCut The cut that goes to the gallery, as %age * 10 * @param _platformCut The cut that goes to the platform if it is a primary sale */ function createSale( uint256 _tokenId, uint128 _fixedPrice, uint64 _startingTime, address _creator, address _seller, address _gallery, uint16 _creatorCut, uint16 _galleryCut, uint16 _platformCut ) external onlyFarbeContract { // create and add the sale FixedPrice memory fixedSale = FixedPrice( _seller, _creator, _gallery, _fixedPrice, _startingTime, _creatorCut, _platformCut, _galleryCut ); _addSale(_tokenId, fixedSale); } /** * @dev External payable function to buy the artwork * @param _tokenId Id of the token to buy */ function buy(uint256 _tokenId) external payable { // do not allow sellers and galleries to buy their own artwork require(tokenIdToSale[_tokenId].seller != msg.sender && tokenIdToSale[_tokenId].gallery != msg.sender, "Sellers and Galleries not allowed"); _buy(_tokenId, msg.value); } /** * @dev External function to finish the sale if no one bought it. Can only be called by the owner or gallery * @param _tokenId ID of the token to finish sale of */ function finishSale(uint256 _tokenId) external { _finishSale(_tokenId); } /** * @dev External view function to get the details of a sale * @param _tokenId ID of the token to get the sale information of * @return seller Address of the seller * @return fixedPrice Fixed Price of the sale in wei * @return startedAt Unix timestamp for when the sale started */ function getFixedSale(uint256 _tokenId) external view returns ( address seller, uint256 fixedPrice, uint256 startedAt ) { FixedPrice storage fixedSale = tokenIdToSale[_tokenId]; require(_isOnSale(fixedSale), "Item is not on sale"); return ( fixedSale.seller, fixedSale.fixedPrice, fixedSale.startedAt ); } /** * @dev Helper function for testing with timers TODO Remove this before deploying live * @param _tokenId ID of the token to get timers of */ function getTimers(uint256 _tokenId) external view returns ( uint256 saleStart, uint256 blockTimestamp ) { FixedPrice memory fixedSale = tokenIdToSale[_tokenId]; return (fixedSale.startedAt, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/PullPayment.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./SaleBase.sol"; import "../EnumerableMap.sol"; /** * @title Base open offers contract * @dev This is the base contract which implements the open offers functionality */ contract OpenOffersBase is PullPayment, ReentrancyGuard, SaleBase { using Address for address payable; // Add the library methods using EnumerableMap for EnumerableMap.AddressToUintMap; struct OpenOffers { address seller; address creator; address gallery; uint64 startedAt; uint16 creatorCut; uint16 platformCut; uint16 galleryCut; EnumerableMap.AddressToUintMap offers; } // this struct is only used for referencing in memory. The OpenOffers struct can not // be used because it is only valid in storage since it contains a nested mapping struct OffersReference { address seller; address creator; address gallery; uint16 creatorCut; uint16 platformCut; uint16 galleryCut; } // mapping for tokenId to its sale mapping(uint256 => OpenOffers) tokenIdToSale; event OpenOffersSaleCreated(uint256 tokenId); event OpenOffersSaleSuccessful(uint256 tokenId, uint256 totalPrice, address winner); /** * @dev Internal function to check if the sale started, by default startedAt will be 0 * */ function _isOnSale(OpenOffers storage _openSale) internal view returns (bool) { return (_openSale.startedAt > 0 && _openSale.startedAt <= block.timestamp); } /** * @dev Remove the sale from the mapping (sets everything to zero/false) * @param _tokenId ID of the token to remove sale of */ function _removeSale(uint256 _tokenId) internal { delete tokenIdToSale[_tokenId]; } /** * @dev Internal that updates the mapping when a new offer is made for a token on sale * @param _tokenId Id of the token to make offer on * @param _bidAmount The offer in wei */ function _makeOffer(uint _tokenId, uint _bidAmount) internal { // get reference to the open offer struct OpenOffers storage openSale = tokenIdToSale[_tokenId]; // check if the item is on sale require(_isOnSale(openSale)); uint256 returnAmount; bool offerExists; // get reference to the amount to return (offerExists, returnAmount) = openSale.offers.tryGet(msg.sender); // update the mapping with the new offer openSale.offers.set(msg.sender, _bidAmount); // if there was a previous offer from this address, return the previous offer amount if(offerExists){ payable(msg.sender).sendValue(returnAmount); } } /** * @dev Internal function to accept the offer of an address. Once an offer is accepted, all existing offers * for the token are moved into the PullPayment contract and the mapping is deleted. Only gallery can accept * offers if the sale involves a gallery * @param _tokenId Id of the token to accept offer of * @param _buyer The address of the buyer to accept offer from */ function _acceptOffer(uint256 _tokenId, address _buyer) internal nonReentrant { OpenOffers storage openSale = tokenIdToSale[_tokenId]; // only the gallery can accept the offer if it was the one to put it on auction if(openSale.gallery != address(0)) { require(openSale.gallery == msg.sender); } else { require(openSale.seller == msg.sender); } // check if token was on sale require(_isOnSale(openSale)); // check if the offer from the buyer exists require(openSale.offers.contains(_buyer)); // get reference to the offer uint256 _payoutAmount = openSale.offers.get(_buyer); // remove the offer from the enumerable mapping openSale.offers.remove(_buyer); address returnAddress; uint256 returnAmount; // put the returns in the pull payments contract for (uint i = 0; i < openSale.offers.length(); i++) { (returnAddress, returnAmount) = openSale.offers.at(i); // transfer the return amount into the pull payement contract _asyncTransfer(returnAddress, returnAmount); } // using struct to avoid stack too deep error OffersReference memory openSaleReference = OffersReference( openSale.seller, openSale.creator, openSale.gallery, openSale.creatorCut, openSale.platformCut, openSale.galleryCut ); // delete the sale _removeSale(_tokenId); // pay the seller and distribute the cuts _payout( payable(openSaleReference.seller), payable(openSaleReference.creator), payable(openSaleReference.gallery), openSaleReference.creatorCut, openSaleReference.platformCut, openSaleReference.galleryCut, _payoutAmount, _tokenId ); // transfer the token to the buyer _transfer(_buyer, _tokenId); } /** * @dev Internal function to cancel an offer. This is used for both rejecting and revoking offers * @param _tokenId Id of the token to cancel offer of * @param _buyer The address to cancel bid of */ function _cancelOffer(uint256 _tokenId, address _buyer) internal { OpenOffers storage openSale = tokenIdToSale[_tokenId]; // check if token was on sale require(_isOnSale(openSale)); // get reference to the offer, will fail if mapping doesn't exist uint256 _payoutAmount = openSale.offers.get(_buyer); // remove the offer from the enumerable mapping openSale.offers.remove(_buyer); // return the ether payable(_buyer).sendValue(_payoutAmount); } /** * @dev Function to finish the sale. Can be called manually if there was no suitable offer * for the NFT. If a gallery put the artwork on sale, only it can call this function. * The super admin can also call the function, this is implemented as a safety mechanism for * the seller in case the gallery becomes idle * @param _tokenId Id of the token to end sale of */ function _finishSale(uint256 _tokenId) internal nonReentrant { OpenOffers storage openSale = tokenIdToSale[_tokenId]; // only the gallery or admin can finish the sale if it was the one to put it on auction if(openSale.gallery != address(0)) { require(openSale.gallery == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender)); } else { require(openSale.seller == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender)); } // check if token was on sale require(_isOnSale(openSale)); address seller = openSale.seller; address returnAddress; uint256 returnAmount; // put all pending returns in the pull payments contract for (uint i = 0; i < openSale.offers.length(); i++) { (returnAddress, returnAmount) = openSale.offers.at(i); // transfer the return amount into the pull payement contract _asyncTransfer(returnAddress, returnAmount); } // delete the sale _removeSale(_tokenId); // return the token to the seller _transfer(seller, _tokenId); } } /** * @title Open Offers sale contract that provides external functions * @dev Implements the external and public functions of the open offers implementation */ contract OpenOffersSale is OpenOffersBase { bool public isFarbeOpenOffersSale = true; /** * External function to create an Open Offers sale. Can only be called by the Farbe NFT contract * @param _tokenId Id of the token to create sale for * @param _startingTime Starting time of the sale * @param _creator Address of the original creator of the artwork * @param _seller Address of the owner of the artwork * @param _gallery Address of the gallery of the artwork, 0 address if gallery is not involved * @param _creatorCut Cut of the creator in %age * 10 * @param _galleryCut Cut of the gallery in %age * 10 * @param _platformCut Cut of the platform on primary sales in %age * 10 */ function createSale( uint256 _tokenId, uint64 _startingTime, address _creator, address _seller, address _gallery, uint16 _creatorCut, uint16 _galleryCut, uint16 _platformCut ) external onlyFarbeContract { OpenOffers storage openOffers = tokenIdToSale[_tokenId]; openOffers.seller = _seller; openOffers.creator = _creator; openOffers.gallery = _gallery; openOffers.startedAt = _startingTime; openOffers.creatorCut = _creatorCut; openOffers.platformCut = _platformCut; openOffers.galleryCut = _galleryCut; } /** * @dev External function that allows others to make offers for an artwork * @param _tokenId Id of the token to make offer for */ function makeOffer(uint256 _tokenId) external payable { // do not allow sellers and galleries to make offers on their own artwork require(tokenIdToSale[_tokenId].seller != msg.sender && tokenIdToSale[_tokenId].gallery != msg.sender, "Sellers and Galleries not allowed"); _makeOffer(_tokenId, msg.value); } /** * @dev External function to allow a gallery or a seller to accept an offer * @param _tokenId Id of the token to accept offer of * @param _buyer Address of the buyer to accept offer of */ function acceptOffer(uint256 _tokenId, address _buyer) external { _acceptOffer(_tokenId, _buyer); } /** * @dev External function to reject a particular offer and return the ether * @param _tokenId Id of the token to reject offer of * @param _buyer Address of the buyer to reject offer of */ function rejectOffer(uint256 _tokenId, address _buyer) external { // only owner or gallery can reject an offer require(tokenIdToSale[_tokenId].seller == msg.sender || tokenIdToSale[_tokenId].gallery == msg.sender); _cancelOffer(_tokenId, _buyer); } /** * @dev External function to allow buyers to revoke their offers * @param _tokenId Id of the token to revoke offer of */ function revokeOffer(uint256 _tokenId) external { _cancelOffer(_tokenId, msg.sender); } /** * @dev External function to finish the sale if no one bought it. Can only be called by the owner or gallery * @param _tokenId ID of the token to finish sale of */ function finishSale(uint256 _tokenId) external { _finishSale(_tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @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; } // 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 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 * ==== */ 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); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.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 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 initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT 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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // 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 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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 "@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/utils/Counters.sol"; import "./OpenOffers.sol"; import "./Auction.sol"; import "./FixedPrice.sol"; /** * @title ERC721 contract implementation * @dev Implements the ERC721 interface for the Farbe artworks */ contract FarbeArt is ERC721, ERC721Enumerable, ERC721URIStorage, AccessControl { // counter for tracking token IDs using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; // details of the artwork struct artworkDetails { address tokenCreator; uint16 creatorCut; bool isSecondarySale; } // mapping of token id to original creator mapping(uint256 => artworkDetails) tokenIdToDetails; // platform cut on primary sales in %age * 10 uint16 public platformCutOnPrimarySales; // constant for defining the minter role bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // reference to auction contract AuctionSale public auctionSale; // reference to fixed price contract FixedPriceSale public fixedPriceSale; // reference to open offer contract OpenOffersSale public openOffersSale; event TokenUriChanged(uint256 tokenId, string uri); /** * @dev Constructor for the ERC721 contract */ constructor() ERC721("FarbeArt", "FBA") { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); } /** * @dev Function to mint an artwork as NFT. If no gallery is approved, the parameter is zero * @param _to The address to send the minted NFT * @param _creatorCut The cut that the original creator will take on secondary sales */ function safeMint( address _to, address _galleryAddress, uint8 _numberOfCopies, uint16 _creatorCut, string[] memory _tokenURI ) public { require(hasRole(MINTER_ROLE, msg.sender), "does not have minter role"); require(_tokenURI.length == _numberOfCopies, "Metadata URIs not equal to editions"); for(uint i = 0; i < _numberOfCopies; i++){ // mint the token _safeMint(_to, _tokenIdCounter.current()); // approve the gallery (0 if no gallery authorized) approve(_galleryAddress, _tokenIdCounter.current()); // set the token URI _setTokenURI(_tokenIdCounter.current(), _tokenURI[i]); // track token creator tokenIdToDetails[_tokenIdCounter.current()].tokenCreator = _to; // track creator's cut tokenIdToDetails[_tokenIdCounter.current()].creatorCut = _creatorCut; // increment tokenId _tokenIdCounter.increment(); } } /** * @dev Implementation of ERC721Enumerable */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev Destroy (burn) the NFT * @param tokenId The ID of the token to burn */ function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } /** * @dev Returns the Uniform Resource Identifier (URI) for the token * @param tokenId ID of the token to return URI of * @return URI for the token */ function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } /** * @dev Implementation of the ERC165 interface * @param interfaceId The Id of the interface to check support for */ function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } } /** * @title Farbe NFT sale contract * @dev Extension of the FarbeArt contract to add sale functionality */ contract FarbeArtSale is FarbeArt { /** * @dev Only allow owner to execute if no one (gallery) has been approved * @param _tokenId Id of the token to check approval and ownership of */ modifier onlyOwnerOrApproved(uint256 _tokenId) { if(getApproved(_tokenId) == address(0)){ require(ownerOf(_tokenId) == msg.sender, "Not owner or approved"); } else { require(getApproved(_tokenId) == msg.sender, "Only approved can list, revoke approval to list yourself"); } _; } /** * @dev Make sure the starting time is not greater than 60 days * @param _startingTime starting time of the sale in UNIX timestamp */ modifier onlyValidStartingTime(uint64 _startingTime) { if(_startingTime > block.timestamp) { require(_startingTime - block.timestamp <= 60 days, "Start time too far"); } _; } /** * @dev Set the primary platform cut on deployment * @param _platformCut Cut that the platform will take on primary sales */ constructor(uint16 _platformCut) { platformCutOnPrimarySales = _platformCut; } function burn(uint256 tokenId) external { // must be owner require(ownerOf(tokenId) == msg.sender); _burn(tokenId); } /** * @dev Change the tokenUri of the token. Can only be changed when the creator is the owner * @param _tokenURI New Uri of the token * @param _tokenId Id of the token to change Uri of */ function changeTokenUri(string memory _tokenURI, uint256 _tokenId) external { // must be owner and creator require(ownerOf(_tokenId) == msg.sender, "Not owner"); require(tokenIdToDetails[_tokenId].tokenCreator == msg.sender, "Not creator"); _setTokenURI(_tokenId, _tokenURI); emit TokenUriChanged( uint256(_tokenId), string(_tokenURI) ); } /** * @dev Set the address for the external auction contract. Can only be set by the admin * @param _address Address of the external contract */ function setAuctionContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) { AuctionSale auction = AuctionSale(_address); require(auction.isFarbeSaleAuction()); auctionSale = auction; } /** * @dev Set the address for the external auction contract. Can only be set by the admin * @param _address Address of the external contract */ function setFixedSaleContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) { FixedPriceSale fixedSale = FixedPriceSale(_address); require(fixedSale.isFarbeFixedSale()); fixedPriceSale = fixedSale; } /** * @dev Set the address for the external auction contract. Can only be set by the admin * @param _address Address of the external contract */ function setOpenOffersContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) { OpenOffersSale openOffers = OpenOffersSale(_address); require(openOffers.isFarbeOpenOffersSale()); openOffersSale = openOffers; } /** * @dev Set the percentage cut that the platform will take on all primary sales * @param _platformCut The cut that the platform will take on primary sales as %age * 10 for values < 1% */ function setPlatformCut(uint16 _platformCut) external onlyRole(DEFAULT_ADMIN_ROLE) { platformCutOnPrimarySales = _platformCut; } /** * @dev Track artwork as sold before by updating the mapping. Can only be called by the sales contracts * @param _tokenId The id of the token which was sold */ function setSecondarySale(uint256 _tokenId) external { require(msg.sender != address(0)); require(msg.sender == address(auctionSale) || msg.sender == address(fixedPriceSale) || msg.sender == address(openOffersSale), "Caller is not a farbe sale contract"); tokenIdToDetails[_tokenId].isSecondarySale = true; } /** * @dev Checks from the mapping if the token has been sold before * @param _tokenId ID of the token to check * @return bool Weather this is a secondary sale (token has been sold before) */ function getSecondarySale(uint256 _tokenId) public view returns (bool) { return tokenIdToDetails[_tokenId].isSecondarySale; } /** * @dev Creates the sale auction for the token by calling the external auction contract. Can only be called by owner, * individual external contract calls are expensive so a single function is used to pass all parameters * @param _tokenId ID of the token to put on auction * @param _startingPrice Starting price of the auction * @param _startingTime Starting time of the auction in UNIX timestamp * @param _duration The duration in seconds for the auction * @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved */ function createSaleAuction( uint256 _tokenId, uint128 _startingPrice, uint64 _startingTime, uint64 _duration, uint16 _galleryCut ) external onlyOwnerOrApproved(_tokenId) onlyValidStartingTime(_startingTime) { // using struct to avoid 'stack too deep' error artworkDetails memory _details = artworkDetails( tokenIdToDetails[_tokenId].tokenCreator, tokenIdToDetails[_tokenId].creatorCut, false ); require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%"); // determine gallery address (0 if called by owner) address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender; // get reference to owner before transfer address _seller = ownerOf(_tokenId); // escrow the token into the auction smart contract safeTransferFrom(_seller, address(auctionSale), _tokenId); // call the external contract function to create the auction auctionSale.createSale( _tokenId, _startingPrice, _startingTime, _duration, _details.tokenCreator, _seller, _galleryAddress, _details.creatorCut, _galleryCut, platformCutOnPrimarySales ); } /** * @dev Creates the fixed price sale for the token by calling the external fixed sale contract. Can only be called by owner. * Individual external contract calls are expensive so a single function is used to pass all parameters * @param _tokenId ID of the token to put on auction * @param _fixedPrice Fixed price of the auction * @param _startingTime Starting time of the auction in UNIX timestamp * @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved */ function createSaleFixedPrice( uint256 _tokenId, uint128 _fixedPrice, uint64 _startingTime, uint16 _galleryCut ) external onlyOwnerOrApproved(_tokenId) onlyValidStartingTime(_startingTime) { // using struct to avoid 'stack too deep' error artworkDetails memory _details = artworkDetails( tokenIdToDetails[_tokenId].tokenCreator, tokenIdToDetails[_tokenId].creatorCut, false ); require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%"); // determine gallery address (0 if called by owner) address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender; // get reference to owner before transfer address _seller = ownerOf(_tokenId); // escrow the token into the auction smart contract safeTransferFrom(ownerOf(_tokenId), address(fixedPriceSale), _tokenId); // call the external contract function to create the auction fixedPriceSale.createSale( _tokenId, _fixedPrice, _startingTime, _details.tokenCreator, _seller, _galleryAddress, _details.creatorCut, _galleryCut, platformCutOnPrimarySales ); } /** * @dev Creates the open offer sale for the token by calling the external open offers contract. Can only be called by owner, * individual external contract calls are expensive so a single function is used to pass all parameters * @param _tokenId ID of the token to put on auction * @param _startingTime Starting time of the auction in UNIX timestamp * @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved */ function createSaleOpenOffer( uint256 _tokenId, uint64 _startingTime, uint16 _galleryCut ) external onlyOwnerOrApproved(_tokenId) onlyValidStartingTime(_startingTime) { // using struct to avoid 'stack too deep' error artworkDetails memory _details = artworkDetails( tokenIdToDetails[_tokenId].tokenCreator, tokenIdToDetails[_tokenId].creatorCut, false ); require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%"); // get reference to owner before transfer address _seller = ownerOf(_tokenId); // determine gallery address (0 if called by owner) address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender; // escrow the token into the auction smart contract safeTransferFrom(ownerOf(_tokenId), address(openOffersSale), _tokenId); // call the external contract function to create the auction openOffersSale.createSale( _tokenId, _startingTime, _details.tokenCreator, _seller, _galleryAddress, _details.creatorCut, _galleryCut, platformCutOnPrimarySales ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./FarbeArt.sol"; contract SaleBase is IERC721Receiver, AccessControl { using Address for address payable; // reference to the NFT contract FarbeArtSale public NFTContract; // address of the platform wallet to which the platform cut will be sent address internal platformWalletAddress; modifier onlyFarbeContract() { // check the caller is the FarbeNFT contract require(msg.sender == address(NFTContract), "Caller is not the Farbe contract"); _; } /** * @dev Implementation of ERC721Receiver */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes memory _data ) public override virtual returns (bytes4) { // This will fail if the received token is not a FarbeArt token // _owns calls NFTContract require(_owns(address(this), _tokenId), "owner is not the sender"); return this.onERC721Received.selector; } /** * @dev Internal function to check if address owns a token * @param _claimant The address to check * @param _tokenId ID of the token to check for ownership * @return bool Weather the _claimant owns the _tokenId */ function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (NFTContract.ownerOf(_tokenId) == _claimant); } /** * @dev Internal function to transfer the NFT from this contract to another address * @param _receiver The address to send the NFT to * @param _tokenId ID of the token to transfer */ function _transfer(address _receiver, uint256 _tokenId) internal { NFTContract.safeTransferFrom(address(this), _receiver, _tokenId); } /** * @dev Internal function that calculates the cuts of all parties and distributes the payment among them * @param _seller Address of the seller * @param _creator Address of the original creator * @param _gallery Address of the gallery, 0 address if gallery is not involved * @param _creatorCut The cut of the original creator * @param _platformCut The cut that goes to the Farbe platform * @param _galleryCut The cut that goes to the gallery * @param _amount The total amount to be split * @param _tokenId The ID of the token that was sold */ function _payout( address payable _seller, address payable _creator, address payable _gallery, uint16 _creatorCut, uint16 _platformCut, uint16 _galleryCut, uint256 _amount, uint256 _tokenId ) internal { // if this is a secondary sale if (NFTContract.getSecondarySale(_tokenId)) { // initialize amount to send to gallery, defaults to 0 uint256 galleryAmount; // calculate gallery cut if this is a gallery sale, wrapped in an if statement in case owner // accidentally sets a gallery cut if(_gallery != address(0)){ galleryAmount = (_galleryCut * _amount) / 1000; } // platform gets 2.5% on secondary sales (hard-coded) uint256 platformAmount = (25 * _amount) / 1000; // calculate amount to send to creator uint256 creatorAmount = (_creatorCut * _amount) / 1000; // calculate amount to send to the seller uint256 sellerAmount = _amount - (platformAmount + creatorAmount + galleryAmount); // repeating if statement to follow check-effect-interaction pattern if(_gallery != address(0)) { _gallery.sendValue(galleryAmount); } payable(platformWalletAddress).sendValue(platformAmount); _creator.sendValue(creatorAmount); _seller.sendValue(sellerAmount); } // if this is a primary sale else { require(_seller == _creator, "Seller is not the creator"); // dividing by 1000 because percentages are multiplied by 10 for values < 1% uint256 platformAmount = (_platformCut * _amount) / 1000; // initialize amount to be sent to gallery, defaults to 0 uint256 galleryAmount; // calculate gallery cut if this is a gallery sale wrapped in an if statement in case owner // accidentally sets a gallery cut if(_gallery != address(0)) { galleryAmount = (_galleryCut * _amount) / 1000; } // calculate the amount to send to the seller uint256 sellerAmount = _amount - (platformAmount + galleryAmount); // repeating if statement to follow check-effect-interaction pattern if(_gallery != address(0)) { _gallery.sendValue(galleryAmount); } _seller.sendValue(sellerAmount); payable(platformWalletAddress).sendValue(platformAmount); // set secondary sale to true NFTContract.setSecondarySale(_tokenId); } } /** * @dev External function to allow admin to change the address of the platform wallet * @param _address Address of the new wallet */ function setPlatformWalletAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) { platformWalletAddress = _address; } } // 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}. 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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` 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 { } } // 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; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. 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; } } } // 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 "../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; // 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.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) { 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.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[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; 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 "../utils/escrow/Escrow.sol"; /** * @dev Simple implementation of a * https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment] * strategy, where the paying contract doesn't interact directly with the * receiver account, which must withdraw its payments itself. * * Pull-payments are often considered the best practice when it comes to sending * Ether, security-wise. It prevents recipients from blocking execution, and * eliminates reentrancy concerns. * * 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]. * * To use, derive from the `PullPayment` contract, and use {_asyncTransfer} * instead of Solidity's `transfer` function. Payees can query their due * payments with {payments}, and retrieve them with {withdrawPayments}. */ abstract contract PullPayment { Escrow immutable private _escrow; constructor () { _escrow = new Escrow(); } /** * @dev Withdraw accumulated payments, forwarding all gas to the recipient. * * Note that _any_ account can call this function, not just the `payee`. * This means that contracts unaware of the `PullPayment` protocol can still * receive funds this way, by having a separate account call * {withdrawPayments}. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee Whose payments will be withdrawn. */ function withdrawPayments(address payable payee) public virtual { _escrow.withdraw(payee); } /** * @dev Returns the payments owed to an address. * @param dest The creditor's address. */ function payments(address dest) public view returns (uint256) { return _escrow.depositsOf(dest); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * Funds sent in this way are stored in an intermediate {Escrow} contract, so * there is no danger of them being spent before withdrawal. * * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function _asyncTransfer(address dest, uint256 amount) internal virtual { _escrow.deposit{ value: amount }(dest); } } // SPDX-License-Identifier: MIT 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 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.AddressToUintMap; * * // Declare a set state variable * EnumerableMap.AddressToUintMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `address -> uint256` (`AddressToUintMap`) are * supported. */ library EnumerableMap { using EnumerableSet for EnumerableSet.Bytes32Set; // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { map._values[key] = value; return map._keys.add(key); } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { delete map._values[key]; return map._keys.remove(key); } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.length(); } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // AddressToUintMap struct AddressToUintMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( AddressToUintMap storage map, address key, uint256 value ) internal returns (bool) { return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(AddressToUintMap storage map, address key) internal returns (bool) { return _remove(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(AddressToUintMap storage map, address key) internal view returns (bool) { return _contains(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns the number of elements in the map. O(1). */ function length(AddressToUintMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (address(uint160(uint256(key))), uint256(value)); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(AddressToUintMap storage map, address key) internal view returns (bool, uint256) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key)))); return (success, uint256(value)); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(AddressToUintMap storage map, address key) internal view returns (uint256) { return uint256(_get(map._inner, bytes32(uint256(uint160(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( AddressToUintMap storage map, address key, string memory errorMessage ) internal view returns (uint256) { return uint256(_get(map._inner, bytes32(uint256(uint160(key))), errorMessage)); } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../access/Ownable.sol"; import "../Address.sol"; /** * @title Escrow * @dev Base escrow contract, holds funds designated for a payee until they * withdraw them. * * Intended usage: This contract (and derived escrow contracts) should be a * standalone contract, that only interacts with the contract that instantiated * it. That way, it is guaranteed that all Ether will be handled according to * the `Escrow` rules, and there is no need to check for payable functions or * transfers in the inheritance tree. The contract that uses the escrow as its * payment method should be its owner, and provide public methods redirecting * to the escrow's deposit and withdraw. */ contract Escrow is Ownable { using Address for address payable; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private _deposits; function depositsOf(address payee) public view returns (uint256) { return _deposits[payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param payee The destination address of the funds. */ function deposit(address payee) public payable virtual onlyOwner { uint256 amount = msg.value; _deposits[payee] = _deposits[payee] + amount; emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee, forwarding all gas to the * recipient. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payable payee) public virtual onlyOwner { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.sendValue(payment); emit Withdrawn(payee, payment); } } // 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 () { 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) 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 Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ))); } } /** * @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 override 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 override onlyRole(getRoleAdmin(role)) { _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 override onlyRole(getRoleAdmin(role)) { _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 override { 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, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT 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; // 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] = 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) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // 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); } // 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)))); } // 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)); } }
* @title Auction sale contract that provides external functions @dev Implements the external and public functions of the auction implementation/ sanity check for the nft contract ERC721 interface id
contract AuctionSale is AuctionBase { bool public isFarbeSaleAuction = true; bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd); constructor(address _nftAddress, address _platformAddress) { FarbeArtSale candidateContract = FarbeArtSale(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); platformWalletAddress = _platformAddress; NFTContract = candidateContract; } function createSale( uint256 _tokenId, uint128 _startingPrice, uint64 _startingTime, uint64 _duration, address _creator, address _seller, address _gallery, uint16 _creatorCut, uint16 _galleryCut, uint16 _platformCut ) external onlyFarbeContract { Auction memory auction = Auction( _seller, _creator, _gallery, address(0), uint128(_startingPrice), uint64(_duration), _startingTime, _creatorCut, _platformCut, _galleryCut ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable { require(tokenIdToAuction[_tokenId].seller != msg.sender && tokenIdToAuction[_tokenId].gallery != msg.sender, "Sellers and Galleries not allowed"); _bid(_tokenId, msg.value); } function finishAuction(uint256 _tokenId) external { _finishAuction(_tokenId); } function getAuction(uint256 _tokenId) external view returns ( address seller, address buyer, uint256 currentPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.buyer, auction.currentPrice, auction.duration, auction.startedAt ); } function getCurrentPrice(uint256 _tokenId) external view returns (uint128) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } function getTimers(uint256 _tokenId) external view returns ( uint256 saleStart, uint256 blockTimestamp, uint256 duration ) { Auction memory auction = tokenIdToAuction[_tokenId]; return (auction.startedAt, block.timestamp, auction.duration); } function forceFinishAuction( uint256 _tokenId, address _nftBeneficiary, address _paymentBeneficiary ) external onlyRole(DEFAULT_ADMIN_ROLE) { _forceFinishAuction(_tokenId, _nftBeneficiary, _paymentBeneficiary); } }
60,821
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2649, 432, 4062, 272, 5349, 6835, 716, 8121, 3903, 4186, 632, 5206, 29704, 326, 3903, 471, 1071, 4186, 434, 326, 279, 4062, 4471, 19, 16267, 866, 364, 326, 290, 1222, 6835, 4232, 39, 27, 5340, 1560, 612, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 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, 432, 4062, 30746, 353, 432, 4062, 2171, 288, 203, 565, 1426, 1071, 353, 17393, 2196, 30746, 37, 4062, 273, 638, 31, 203, 203, 565, 1731, 24, 5381, 6682, 5374, 67, 654, 39, 27, 5340, 273, 1731, 24, 12, 20, 92, 3672, 1077, 8204, 4315, 1769, 203, 203, 565, 3885, 12, 2867, 389, 82, 1222, 1887, 16, 1758, 389, 9898, 1887, 13, 288, 203, 3639, 478, 297, 2196, 4411, 30746, 5500, 8924, 273, 478, 297, 2196, 4411, 30746, 24899, 82, 1222, 1887, 1769, 203, 3639, 2583, 12, 19188, 8924, 18, 28064, 1358, 12, 1358, 5374, 67, 654, 39, 27, 5340, 10019, 203, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 3639, 4072, 16936, 1887, 273, 389, 9898, 1887, 31, 203, 203, 3639, 423, 4464, 8924, 273, 5500, 8924, 31, 203, 565, 289, 203, 203, 565, 445, 752, 30746, 12, 203, 3639, 2254, 5034, 389, 2316, 548, 16, 203, 3639, 2254, 10392, 389, 18526, 5147, 16, 203, 3639, 2254, 1105, 389, 18526, 950, 16, 203, 3639, 2254, 1105, 389, 8760, 16, 203, 3639, 1758, 389, 20394, 16, 203, 3639, 1758, 389, 1786, 749, 16, 203, 3639, 1758, 389, 21454, 16, 203, 3639, 2254, 2313, 389, 20394, 15812, 16, 203, 3639, 2254, 2313, 389, 21454, 15812, 16, 203, 3639, 2254, 2313, 389, 9898, 15812, 203, 565, 262, 203, 565, 3903, 203, 565, 1338, 17393, 2196, 8924, 203, 565, 288, 203, 3639, 432, 4062, 3778, 279, 4062, 273, 432, 4062, 12, 203, 5411, 389, 1786, 749, 16, 203, 5411, 389, 20394, 16, 203, 5411, 389, 21454, 16, 203, 5411, 1758, 12, 20, 3631, 203, 5411, 2254, 10392, 24899, 18526, 5147, 3631, 203, 5411, 2254, 1105, 24899, 8760, 3631, 203, 5411, 389, 18526, 950, 16, 203, 5411, 389, 20394, 15812, 16, 203, 5411, 389, 9898, 15812, 16, 203, 5411, 389, 21454, 15812, 203, 3639, 11272, 203, 3639, 389, 1289, 37, 4062, 24899, 2316, 548, 16, 279, 4062, 1769, 203, 565, 289, 203, 203, 565, 445, 9949, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 2316, 28803, 37, 4062, 63, 67, 2316, 548, 8009, 1786, 749, 480, 1234, 18, 15330, 597, 1147, 28803, 37, 4062, 63, 67, 2316, 548, 8009, 21454, 480, 1234, 18, 15330, 16, 203, 5411, 315, 55, 1165, 414, 471, 611, 30912, 486, 2935, 8863, 203, 203, 3639, 389, 19773, 24899, 2316, 548, 16, 1234, 18, 1132, 1769, 203, 565, 289, 203, 203, 565, 445, 4076, 37, 4062, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 288, 203, 3639, 389, 13749, 37, 4062, 24899, 2316, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 4506, 4062, 12, 11890, 5034, 389, 2316, 548, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 203, 565, 261, 203, 3639, 1758, 29804, 16, 203, 3639, 1758, 27037, 16, 203, 3639, 2254, 5034, 783, 5147, 16, 203, 3639, 2254, 5034, 3734, 16, 203, 3639, 2254, 5034, 5746, 861, 203, 565, 262, 288, 203, 3639, 432, 4062, 2502, 279, 4062, 273, 1147, 28803, 37, 4062, 63, 67, 2316, 548, 15533, 203, 3639, 2583, 24899, 291, 1398, 37, 4062, 12, 69, 4062, 10019, 203, 3639, 327, 261, 203, 3639, 279, 4062, 18, 1786, 749, 16, 203, 3639, 279, 4062, 18, 70, 16213, 16, 203, 3639, 279, 4062, 18, 2972, 5147, 16, 203, 3639, 279, 4062, 18, 8760, 16, 203, 3639, 279, 4062, 18, 14561, 861, 203, 3639, 11272, 203, 565, 289, 203, 203, 565, 445, 5175, 5147, 12, 11890, 5034, 389, 2316, 548, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 261, 11890, 10392, 13, 203, 565, 288, 203, 3639, 432, 4062, 2502, 279, 4062, 273, 1147, 28803, 37, 4062, 63, 67, 2316, 548, 15533, 203, 3639, 2583, 24899, 291, 1398, 37, 4062, 12, 69, 4062, 10019, 203, 3639, 327, 389, 2972, 5147, 12, 69, 4062, 1769, 203, 565, 289, 203, 203, 565, 445, 3181, 381, 414, 12, 11890, 5034, 389, 2316, 548, 13, 203, 565, 3903, 203, 565, 1476, 1135, 261, 203, 3639, 2254, 5034, 272, 5349, 1685, 16, 203, 3639, 2254, 5034, 1203, 4921, 16, 203, 3639, 2254, 5034, 3734, 203, 565, 262, 288, 203, 3639, 432, 4062, 3778, 279, 4062, 273, 1147, 28803, 37, 4062, 63, 67, 2316, 548, 15533, 203, 3639, 327, 261, 69, 4062, 18, 14561, 861, 16, 1203, 18, 5508, 16, 279, 4062, 18, 8760, 1769, 203, 565, 289, 203, 203, 565, 445, 2944, 11641, 37, 4062, 12, 203, 3639, 2254, 5034, 389, 2316, 548, 16, 203, 3639, 1758, 389, 82, 1222, 38, 4009, 74, 14463, 814, 16, 203, 3639, 1758, 389, 9261, 38, 4009, 74, 14463, 814, 203, 565, 262, 203, 565, 3903, 203, 565, 1338, 2996, 12, 5280, 67, 15468, 67, 16256, 13, 203, 565, 288, 203, 3639, 389, 5734, 11641, 37, 4062, 24899, 2316, 548, 16, 389, 82, 1222, 38, 4009, 74, 14463, 814, 16, 389, 9261, 38, 4009, 74, 14463, 814, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: Unlicense pragma solidity ^0.7.0; //Order struct struct Order { bytes32 id; address token_address; uint256 block_nr; bool order_type; address from; uint256 eth_sent; uint256 eth_left; uint256 token_amount; uint256 token_left; uint256 limit; bool executed; bool cancelled; bytes32 previous_order; bytes32 next_order; } //Trade struct struct Trade { bytes32 id; address token_address; uint256 block_nr; uint256 timestamp; bool order_type; bytes32 buy_order_id; bytes32 sell_order_id; uint256 exec_amount; uint256 price; } //Exchange Struct struct Exchange { //First order of the queue mapping(address => bytes32) first_buy_order_id; mapping(address => bytes32) first_sell_order_id; //mapping of all orders by order_id in uint format //can be reconverted to the right format using web3.toHex mapping(address => mapping(bytes32 => Order)) orders; mapping(address => uint256[]) order_list; //Executions records //(i) mapping token => execution_id => execution //(ii) mapping token => (uint) execution_id mapping(address => mapping(bytes32 => Trade)) trades; mapping(address => uint256[]) trade_list; //mapping of address with current balance with the exchange mapping(address => uint256) eth_balance; mapping(address => mapping(address => uint256)) token_balance; //mapping of listed tokens mapping(address => string) listed_tokens; mapping(address => bool) is_token_listed; address[] token_list_array; bool is_exchange_open; } contract _0xChange { Exchange private exchange; constructor(){ exchange.is_exchange_open = true; } function buy(address _token, uint _amount, uint _limit) public payable { _0xChangeLib.place_buy_order(exchange, _token, _amount, _limit); } function sell(address _seller, address _token, uint _amount, uint _limit) public { _0xChangeLib.place_sell_order(exchange, _seller, _token, _amount, _limit); } function takeEth(address _sender) public { _0xChangeLib.withdrawEth(exchange, _sender); } function takeCoin(address _token, address _sender) public { _0xChangeLib.withdrawToken(exchange, _token, _sender); } function cancel(address _token, bytes32 orderId) public { _0xChangeLib.cancelOrder(exchange, _token, orderId); } function receiveApproval(address _from, uint _token, address _tokenContract, bytes memory _data) public { if(!ERC20Interface(_tokenContract).transferFrom(_from, address(this), _token)) { revert(); } _0xChangeLib.place_sell_order(exchange, _from, _tokenContract, _token, _0xChangeLib.toUint256(_data)); } // ------------------------------------------------------------------------ // Getters and setters for web3 interface // ------------------------------------------------------------------------ // User function getEthBalance(address user) public view returns(uint256) { return exchange.eth_balance[user]; } function getTokenBalance(address token, address user) public view returns(uint256) { return exchange.token_balance[token][user]; } // Tokens function getTokenListLength() public view returns(uint) { return exchange.token_list_array.length; } function getTokenAddress(uint pos) public view returns(address) { return exchange.token_list_array[pos]; } function getTokenSymbol(address tokenAddress) public view returns(string memory) { return exchange.listed_tokens[tokenAddress]; } function addToken(address tokenAddress) public { if(exchange.is_token_listed[tokenAddress] == false) { exchange.token_list_array.push(tokenAddress); exchange.listed_tokens[tokenAddress] = ERC20Interface(tokenAddress).symbol(); exchange.is_token_listed[tokenAddress] = true; } else { exchange.listed_tokens[tokenAddress] = ERC20Interface(tokenAddress).symbol(); } } //Info function getLastPrice(address tokenAddress) public view returns(uint) { return exchange.trades[tokenAddress][bytes32(exchange.trade_list[tokenAddress][getExecutionsLength(tokenAddress)-1])].price; } function getFirstBuyOrder(address tokenAddress) public view returns(bytes32) { return exchange.first_buy_order_id[tokenAddress]; } function getFirstSellOrder(address tokenAddress) public view returns(bytes32) { return exchange.first_sell_order_id[tokenAddress]; } // Executions function getExecutionsLength(address _token) public view returns(uint) { return exchange.trade_list[_token].length; } // Order function getOrderFrom(address _token, bytes32 _orderId) public view returns (address) { return exchange.orders[_token][_orderId].from; } } library _0xChangeLib { //Event generated when an order is placed successfully event Placed(bytes32 order_id, address token_address, uint block_nr, bool order_type, address sender, uint eth_left, uint token_left, uint limit, bool executed, bool cancelled, bytes32 previous_order, bytes32 next_order); event Updated(bytes32 order_id, address token, uint eth_left, uint token_left, bool executed, bool cancelled, bytes32 previous_order, bytes32 next_order); event Traded(bytes32 trade_id, address token_address, uint block_nr, uint trade_timestamp, bool order_type, bytes32 buy_order_id, bytes32 sell_order_id, uint trade_amount, uint trade_price); function place_buy_order( Exchange storage self, address _token, uint256 _amount, uint256 _limit ) public returns (bool) { require( (_amount * _limit) / (10**uint256(ERC20Interface(_token).decimals())) <= msg.value ); require(msg.value > 0); require(self.is_exchange_open); bytes32 order_id = keccak256( abi.encodePacked(block.number, _token, msg.sender, _amount, _limit) ); self.orders[_token][order_id].id = order_id; self.orders[_token][order_id].token_address = _token; self.orders[_token][order_id].block_nr = block.number; self.orders[_token][order_id].order_type = true; self.orders[_token][order_id].from = msg.sender; self.orders[_token][order_id].eth_sent = msg.value; self.orders[_token][order_id].eth_left = msg.value; self.orders[_token][order_id].token_amount = _amount; self.orders[_token][order_id].token_left = _amount; self.orders[_token][order_id].limit = _limit; self.orders[_token][order_id].executed = false; self.orders[_token][order_id].cancelled = false; self.orders[_token][order_id].previous_order = bytes32(0); self.orders[_token][order_id].next_order = bytes32(0); self.order_list[_token].push(uint256(order_id)); insertBuyOrder(self, _token, order_id); emitOrder(self, _token, order_id); matching(self, _token, true); } function insertBuyOrder( Exchange storage self, address _token, bytes32 _order_id ) internal { bytes32 position; //In case no other buy order exists if (self.first_buy_order_id[_token] == 0) { self.first_buy_order_id[_token] = _order_id; return; } //loop through the buy order book and insert new buy orders position = self.first_buy_order_id[_token]; do { //insert market orders before limit order (first market order) if ( self.orders[_token][_order_id].limit == 0 && self.orders[_token][position].limit != 0 && (self.orders[_token][getPreviousOrder(self, _token, position)].id == 0 || self.orders[_token][getPreviousOrder(self, _token, position)] .limit == 0) ) { if ( self.orders[_token][getPreviousOrder(self, _token, position)] .id == 0 ) self.first_buy_order_id[_token] = _order_id; self.orders[_token][_order_id] .previous_order = getPreviousOrder(self, _token, position); self.orders[_token][_order_id].next_order = position; self.orders[_token][getPreviousOrder(self, _token, position)] .next_order = _order_id; self.orders[_token][position].previous_order = _order_id; return; } //insert market order after the last market order if ( self.orders[_token][_order_id].limit == 0 && self.orders[_token][position].limit == 0 && (self.orders[_token][getNextOrder(self, _token, position)].id == 0 || self.orders[_token][getNextOrder(self, _token, position)].limit != 0) ) { self.orders[_token][_order_id].previous_order = position; self.orders[_token][_order_id].next_order = self .orders[_token][position] .next_order; self.orders[_token][getNextOrder(self, _token, position)] .previous_order = _order_id; self.orders[_token][position].next_order = _order_id; return; } //insert limit order for new highest bid if ( self.orders[_token][_order_id].limit != 0 && self.orders[_token][position].limit != 0 && self.orders[_token][_order_id].limit > self.orders[_token][position].limit && (self.orders[_token][getPreviousOrder(self, _token, position)].id == 0 || self.orders[_token][getPreviousOrder(self, _token, position)] .limit == 0) ) { if ( self.orders[_token][getPreviousOrder(self, _token, position)] .id == 0 ) self.first_buy_order_id[_token] = _order_id; self.orders[_token][_order_id] .previous_order = self.orders[_token][getPreviousOrder( self, _token, position )] .id; self.orders[_token][_order_id].next_order = position; self.orders[_token][getPreviousOrder(self, _token, position)] .next_order = _order_id; self.orders[_token][position].previous_order = _order_id; return; } //insert limit order, case where the order is among existing limit buy orders //or first limit order after market order(s) if ( (self.orders[_token][_order_id].limit != 0 && self.orders[_token][position].limit != 0 && self.orders[_token][_order_id].limit <= self.orders[_token][position].limit && self.orders[_token][_order_id].block_nr >= self.orders[_token][position].block_nr && //to be tested for block order (self.orders[_token][getNextOrder(self, _token, position)].id == 0 || self.orders[_token][_order_id].limit > self.orders[_token][getNextOrder(self, _token, position)] .limit)) || (self.orders[_token][_order_id].limit != 0 && self.orders[_token][position].limit == 0 && self.orders[_token][getNextOrder(self, _token, position)].id == 0) ) { self.orders[_token][_order_id].previous_order = position; self.orders[_token][_order_id].next_order = getNextOrder( self, _token, position ); self.orders[_token][getNextOrder(self, _token, position)] .previous_order = _order_id; self.orders[_token][position].next_order = _order_id; return; } position = getNextOrder(self, _token, position); } while (position != 0); } function place_sell_order(Exchange storage self, address _seller, address _token, uint256 _amount, uint256 _limit ) internal returns (bool) { require(self.is_exchange_open); bytes32 order_id = keccak256( abi.encodePacked(block.number, _token, msg.sender, _amount, _limit) ); self.orders[_token][order_id].id = order_id; self.orders[_token][order_id].token_address = _token; self.orders[_token][order_id].block_nr = block.number; self.orders[_token][order_id].order_type = false; self.orders[_token][order_id].from = _seller; self.orders[_token][order_id].eth_sent = 0; self.orders[_token][order_id].eth_left = 0; self.orders[_token][order_id].token_amount = _amount; self.orders[_token][order_id].token_left = _amount; self.orders[_token][order_id].limit = _limit; self.orders[_token][order_id].executed = false; self.orders[_token][order_id].cancelled = false; self.orders[_token][order_id].previous_order = bytes32(0); self.orders[_token][order_id].next_order = bytes32(0); self.order_list[_token].push(uint256(order_id)); insertSellOrder(self, _token, order_id); emitOrder(self, _token, order_id); matching(self, _token, false); } function insertSellOrder(Exchange storage self, address _token, bytes32 _order_id) internal { bytes32 position; if (self.first_sell_order_id[_token] == 0) { self.first_sell_order_id[_token] = _order_id; return; } position = self.first_sell_order_id[_token]; do { //insert orders, market orders with limit 0 first_sell_order_id //then limit order by ascending order. Orders of equal limit //sorted ascending by block nr if ( self.orders[_token][_order_id].limit < self.orders[_token][position].limit ) { if (self.orders[_token][position].previous_order == 0) { self.first_sell_order_id[_token] = _order_id; } self.orders[_token][_order_id].previous_order = getPreviousOrder( self, _token, position ); self.orders[_token][_order_id].next_order = position; self.orders[_token][getPreviousOrder(self, _token, position)] .next_order = _order_id; self.orders[_token][position].previous_order = _order_id; return; } //insert limit order, case where the order is among existing limit buy orders if ( self.orders[_token][_order_id].limit >= self.orders[_token][position].limit && (self.orders[_token][_order_id].limit < self.orders[_token][getNextOrder(self, _token, position)].limit || self.orders[_token][getNextOrder(self, _token, position)].id == 0) && self.orders[_token][_order_id].block_nr >= self.orders[_token][position].block_nr ) { self.orders[_token][_order_id].previous_order = position; self.orders[_token][_order_id].next_order = getNextOrder( self, _token, position ); self.orders[_token][getNextOrder(self, _token, position)] .previous_order = _order_id; self.orders[_token][position].next_order = _order_id; return; } position = getNextOrder(self, _token, position); } while (position != 0); } // ------------------------------------------------------------------------ // Withdraw Eth from the traders balance // ------------------------------------------------------------------------ function withdrawEth(Exchange storage self, address _sender) public returns (bool) { require(msg.sender == _sender); uint balance = self.eth_balance[msg.sender]; self.eth_balance[msg.sender] = 0; msg.sender.transfer(balance); } // ------------------------------------------------------------------------ // Withdraw Tokens from the traders balance // ------------------------------------------------------------------------ function withdrawToken(Exchange storage self, address _token, address _sender) public returns (bool){ require(msg.sender == _sender); uint balance = self.token_balance[_token][msg.sender]; self.token_balance[_token][_sender] = 0; ERC20Interface(_token).transfer(_sender, balance); } function matching(Exchange storage self, address _token, bool _type) public { bytes32 exec_id; uint256 price; uint256 amount; while (matchingPossible(self, _token)) { //set execution price for market vs market, //market vs limit order, limit vs market //and limit vs. limit type of order price = transactionPrice(self, _token, _type); amount = transactionAmount(self, _token, price); exec_id = keccak256( abi.encodePacked( _token, block.number, _token, self.first_buy_order_id[_token], self.first_sell_order_id[_token], price, amount ) ); //Build the trade self.trades[_token][exec_id].id = exec_id; self.trades[_token][exec_id].token_address = _token; self.trades[_token][exec_id].block_nr = block.number; self.trades[_token][exec_id].timestamp = block.timestamp; self.trades[_token][exec_id].order_type = _type; self.trades[_token][exec_id] .buy_order_id = self.first_buy_order_id[_token]; self.trades[_token][exec_id] .sell_order_id = self.first_sell_order_id[_token]; self.trades[_token][exec_id].exec_amount = amount; self.trades[_token][exec_id].price = price; //Record the trades self.trade_list[_token].push(uint256(exec_id)); //Settle payment and finalize the trade settlement(self, _token, exec_id); } } function settlement(Exchange storage self, address _token, bytes32 _exec_id) internal { uint256 trx_volume = (self.trades[_token][_exec_id].exec_amount * self.trades[_token][_exec_id].price) / (10**uint256(ERC20Interface(_token).decimals())); uint256 payment; //update orders self.orders[_token][self.first_buy_order_id[_token]] .token_left -= self.trades[_token][_exec_id].exec_amount; self.orders[_token][self.first_sell_order_id[_token]] .token_left -= self.trades[_token][_exec_id].exec_amount; self.orders[_token][self.first_buy_order_id[_token]] .eth_left -= trx_volume; payment = trx_volume; self.token_balance[_token][getOrderFrom( self, _token, self.trades[_token][_exec_id].buy_order_id )] += self.trades[_token][_exec_id].exec_amount; self.eth_balance[getOrderFrom( self, _token, self.trades[_token][_exec_id].sell_order_id )] += payment; //Consider an order as executed if the token amount left is zero //or if the eth amount left is smaller than 10000000000 wei (0.00000001 ETH) if ( self.orders[_token][self.first_buy_order_id[_token]].token_left == 0 || self.orders[_token][self.first_buy_order_id[_token]].eth_left < 10000000000 ) { self.orders[_token][self.first_buy_order_id[_token]].executed = true; self.eth_balance[getOrderFrom( self, _token, self.trades[_token][_exec_id].buy_order_id )] += self.orders[_token][self.first_buy_order_id[_token]].eth_left; self.orders[_token][self.first_buy_order_id[_token]].eth_left = 0; self.first_buy_order_id[_token] = self.orders[_token][self.first_buy_order_id[_token]] .next_order; self.orders[_token][self.first_buy_order_id[_token]] .previous_order = bytes32(0); self.orders[_token][self.trades[_token][_exec_id].buy_order_id] .next_order = bytes32(0); } if ( self.orders[_token][self.first_sell_order_id[_token]].token_left == 0 ) { self.orders[_token][self.first_sell_order_id[_token]].executed = true; self.first_sell_order_id[_token] = self.orders[_token][self.first_sell_order_id[_token]] .next_order; self.orders[_token][self.first_sell_order_id[_token]] .previous_order = bytes32(0); self.orders[_token][self.trades[_token][_exec_id].sell_order_id] .next_order = bytes32(0); } emit Traded( _exec_id, _token, self.trades[_token][_exec_id].block_nr, self.trades[_token][_exec_id].timestamp, self.trades[_token][_exec_id].order_type, self.trades[_token][_exec_id].buy_order_id, self.trades[_token][_exec_id].sell_order_id, self.trades[_token][_exec_id].exec_amount, self.trades[_token][_exec_id].price ); } function cancelOrder(Exchange storage self, address _token, bytes32 orderId) public returns(bool) { require(msg.sender == self.orders[_token][orderId].from); require(self.orders[_token][orderId].cancelled == false); require(self.orders[_token][orderId].executed == false); Order memory _order = self.orders[_token][orderId]; if(_order.order_type == true) { if(self.first_buy_order_id[_token] == orderId){ self.first_buy_order_id[_token] = _order.next_order; self.orders[_token][_order.next_order].previous_order = _order.previous_order; } else { self.orders[_token][_order.previous_order].next_order = _order.next_order; self.orders[_token][_order.next_order].previous_order = _order.previous_order; } } else { if(self.first_sell_order_id[_token] == orderId){ self.first_sell_order_id[_token] = _order.next_order; self.orders[_token][_order.next_order].previous_order = _order.previous_order; } else { self.orders[_token][_order.previous_order].next_order = _order.next_order; self.orders[_token][_order.next_order].previous_order = _order.previous_order; } } _order.previous_order = bytes32(0); _order.next_order = bytes32(0); _order.cancelled = true; self.eth_balance[_order.from] += _order.eth_left; _order.eth_left = 0; self.orders[_token][orderId] = _order; } function matchingPossible(Exchange storage self, address _token) internal view returns (bool) { return (self.orders[_token][self.first_buy_order_id[_token]].limit >= self.orders[_token][self.first_sell_order_id[_token]].limit || (self.orders[_token][self.first_buy_order_id[_token]].limit == 0 || self.orders[_token][self.first_sell_order_id[_token]].limit == 0)) && (self.first_buy_order_id[_token] != 0 && self.first_sell_order_id[_token] != 0); } function transactionAmount(Exchange storage self, address _token, uint256 price) internal view returns (uint256) { return min( self.orders[_token][self.first_buy_order_id[_token]].token_left, min( (self.orders[_token][self.first_buy_order_id[_token]] .eth_left * (10**uint256(ERC20Interface(_token).decimals()))) / price, self.orders[_token][self.first_sell_order_id[_token]] .token_left ) ); } function transactionPrice(Exchange storage self, address _token, bool _type) internal view returns (uint256) { //Market order against market order //We call the getBestPrice function, which returns the lowest of //the last trade or the best bid if ( self.orders[_token][self.first_buy_order_id[_token]].limit == 0 && self.orders[_token][self.first_sell_order_id[_token]].limit == 0 ) { return getBestPrice(self, _token); //Buy order at best vs limited sell order ==> ask price } else if ( self.orders[_token][self.first_buy_order_id[_token]].limit == 0 && self.orders[_token][self.first_sell_order_id[_token]].limit != 0 ) { return self.orders[_token][self.first_sell_order_id[_token]].limit; //Limited buy order vs market sell order ==> bid price } else if ( self.orders[_token][self.first_buy_order_id[_token]].limit != 0 && self.orders[_token][self.first_sell_order_id[_token]].limit == 0 ) { return self.orders[_token][self.first_buy_order_id[_token]].limit; //Limited buy order vs limited sell order // ==> limit placed by the counterparty not initiating the trade } else if ( self.orders[_token][self.first_buy_order_id[_token]].limit != 0 && self.orders[_token][self.first_sell_order_id[_token]].limit != 0 ) { if (_type) return self.orders[_token][self.first_sell_order_id[_token]].limit; else return self.orders[_token][self.first_buy_order_id[_token]].limit; } } function getBestPrice(Exchange storage self, address _token) public view returns (uint256 price) { //lowest of last paid price or lowest limit sell order //used to execute market orders bytes32 position = self.first_sell_order_id[_token]; uint256 best_price = getLastPrice(self, _token); while (self.orders[_token][position].id != 0) { if (self.orders[_token][position].limit != 0) { if (self.orders[_token][position].limit < best_price) { best_price = self.orders[_token][position].limit; } return best_price; } position = self.orders[_token][getNextOrder( self, _token, position )] .id; } } function emitOrder( Exchange storage self, address token, bytes32 order_id ) public { emit Placed( order_id, self.orders[token][order_id].from, token, self.orders[token][order_id].order_type, self.orders[token][order_id].block_nr, self.orders[token][order_id].eth_sent, self.orders[token][order_id].eth_left, self.orders[token][order_id].token_amount, self.orders[token][order_id].token_left, self.orders[token][order_id].limit, self.orders[token][order_id].previous_order, self.orders[token][order_id].next_order ); } function getPreviousOrder(Exchange storage self, address _token, bytes32 _orderId) public view returns (bytes32) { return self.orders[_token][_orderId].previous_order; } function getNextOrder(Exchange storage self, address _token, bytes32 _orderId) public view returns (bytes32) { return self.orders[_token][_orderId].next_order; } function getLastPrice(Exchange storage self, address tokenAddress) public view returns (uint256) { return self.trades[tokenAddress][bytes32( self.trade_list[tokenAddress][getExecutionsLength(self, tokenAddress) - 1] )] .price; } function getExecutionsLength(Exchange storage self, address _token) public view returns (uint256) { return self.trade_list[_token].length; } function getOrderFrom(Exchange storage self, address _token, bytes32 _orderId) public view returns (address) { return self.orders[_token][_orderId].from; } // Various utils function max(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) return a; else return b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a <= b) return a; else return b; } function toUint256(bytes memory _bytes) internal pure returns (uint256 value) { assembly { value := mload(add(_bytes, 0x20)) } value = value >> (32-_bytes.length); } } abstract contract ERC20Interface { uint8 public decimals; string public symbol; string public name; function totalSupply() public virtual returns (uint256); function balanceOf(address tokenOwner) public virtual returns (uint256 balance); function allowance(address tokenOwner, address spender) public virtual 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 ); }
lowest of last paid price or lowest limit sell orderused to execute market orders
function getBestPrice(Exchange storage self, address _token) public view returns (uint256 price) { bytes32 position = self.first_sell_order_id[_token]; uint256 best_price = getLastPrice(self, _token); while (self.orders[_token][position].id != 0) { if (self.orders[_token][position].limit != 0) { if (self.orders[_token][position].limit < best_price) { best_price = self.orders[_token][position].limit; } return best_price; } position = self.orders[_token][getNextOrder( self, _token, position )] .id; } }
1,761,579
[ 1, 4625, 348, 7953, 560, 30, 11981, 434, 1142, 30591, 6205, 578, 11981, 1800, 357, 80, 1353, 3668, 358, 1836, 13667, 11077, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 28782, 5147, 12, 11688, 2502, 365, 16, 1758, 389, 2316, 13, 1071, 1476, 1135, 261, 11890, 5034, 6205, 13, 288, 203, 3639, 1731, 1578, 1754, 273, 365, 18, 3645, 67, 87, 1165, 67, 1019, 67, 350, 63, 67, 2316, 15533, 203, 3639, 2254, 5034, 3796, 67, 8694, 273, 7595, 5147, 12, 2890, 16, 389, 2316, 1769, 203, 203, 3639, 1323, 261, 2890, 18, 9972, 63, 67, 2316, 6362, 3276, 8009, 350, 480, 374, 13, 288, 203, 5411, 309, 261, 2890, 18, 9972, 63, 67, 2316, 6362, 3276, 8009, 3595, 480, 374, 13, 288, 203, 7734, 309, 261, 2890, 18, 9972, 63, 67, 2316, 6362, 3276, 8009, 3595, 411, 3796, 67, 8694, 13, 288, 203, 10792, 3796, 67, 8694, 273, 365, 18, 9972, 63, 67, 2316, 6362, 3276, 8009, 3595, 31, 203, 7734, 289, 203, 203, 7734, 327, 3796, 67, 8694, 31, 203, 5411, 289, 203, 203, 5411, 1754, 273, 365, 18, 9972, 63, 67, 2316, 6362, 588, 2134, 2448, 12, 203, 7734, 365, 16, 203, 7734, 389, 2316, 16, 203, 7734, 1754, 203, 5411, 262, 65, 203, 7734, 263, 350, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Items. @author Tim Clancy This is the governing registry of all SuperFarm Item assets. */ contract FarmItemRecords is Ownable, ReentrancyGuard { /// A version number for this record contract's interface. uint256 public version = 1; /// A mapping for an array of all Fee1155s deployed by a particular address. mapping (address => address[]) public itemRecords; /// An event for tracking the creation of a new Item. event ItemCreated(address indexed itemAddress, address indexed creator); /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /** Construct a new item registry with a specific OpenSea proxy address. @param _proxyRegistryAddress An OpenSea proxy registry address. */ constructor(address _proxyRegistryAddress) public { proxyRegistryAddress = _proxyRegistryAddress; } /** Create a Fee1155 on behalf of the owner calling this function. The Fee1155 immediately mints a single-item collection. @param _uri The item group's metadata URI. @param _royaltyFee The creator's fee to apply to the created item. @param _initialSupply An array of per-item initial supplies which should be minted immediately. @param _maximumSupply An array of per-item maximum supplies. @param _recipients An array of addresses which will receive the initial supply minted for each corresponding item. @param _data Any associated data to use if items are minted this transaction. */ function createItem(string calldata _uri, uint256 _royaltyFee, uint256[] calldata _initialSupply, uint256[] calldata _maximumSupply, address[] calldata _recipients, bytes calldata _data) external nonReentrant returns (Fee1155) { FeeOwner royaltyFeeOwner = new FeeOwner(_royaltyFee, 30000); Fee1155 newItemGroup = new Fee1155(_uri, royaltyFeeOwner, proxyRegistryAddress); newItemGroup.create(_initialSupply, _maximumSupply, _recipients, _data); // Transfer ownership of the new Item to the user then store a reference. royaltyFeeOwner.transferOwnership(msg.sender); newItemGroup.transferOwnership(msg.sender); address itemAddress = address(newItemGroup); itemRecords[msg.sender].push(itemAddress); emit ItemCreated(itemAddress, msg.sender); return newItemGroup; } /** Allow a user to add an existing Item contract to the registry. @param _itemAddress The address of the Item contract to add for this user. */ function addItem(address _itemAddress) external { itemRecords[msg.sender].push(_itemAddress); } /** Get the number of entries in the Item records mapping for the given user. @return The number of Items added for a given address. */ function getItemCount(address _user) external view returns (uint256) { return itemRecords[_user].length; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { _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; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title Represents ownership over a fee of some percentage. @author Tim Clancy */ contract FeeOwner is Ownable { using SafeMath for uint256; /// A version number for this FeeOwner contract's interface. uint256 public version = 1; /// The percent fee due to this contract's owner, represented as 1/1000th of a percent. That is, a 1% fee maps to 1000. uint256 public fee; /// The maximum configurable percent fee due to this contract's owner, represented as 1/1000th of a percent. uint256 public maximumFee; /// An event for tracking modification of the fee. event FeeChanged(uint256 oldFee, uint256 newFee); /** Construct a new FeeOwner by providing specifying a fee. @param _fee The percent fee to apply, represented as 1/1000th of a percent. @param _maximumFee The maximum possible fee that the owner can set. */ constructor(uint256 _fee, uint256 _maximumFee) public { require(_fee <= _maximumFee, "The fee cannot be set above its maximum."); fee = _fee; maximumFee = _maximumFee; } /** Allows the owner of this fee to modify what they take, within bounds. @param newFee The new fee to begin using. */ function changeFee(uint256 newFee) external onlyOwner { require(newFee <= maximumFee, "The fee cannot be set above its original maximum."); emit FeeChanged(fee, newFee); fee = newFee; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; /** @title An OpenSea delegate proxy contract which we include for whitelisting. @author OpenSea */ contract OwnableDelegateProxy { } /** @title An OpenSea proxy registry contract which we include for whitelisting. @author OpenSea */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** @title An ERC-1155 item creation contract which specifies an associated FeeOwner who receives royalties from sales of created items. @author Tim Clancy The fee set by the FeeOwner on this Item is honored by Shop contracts. In addition to the inherited OpenZeppelin dependency, this uses ideas from the original ERC-1155 reference implementation. */ contract Fee1155 is ERC1155, Ownable { using SafeMath for uint256; /// A version number for this fee-bearing 1155 item contract's interface. uint256 public version = 1; /// The ERC-1155 URI for looking up item metadata using {id} substitution. string public metadataUri; /// A user-specified FeeOwner to receive a portion of item sale earnings. FeeOwner public feeOwner; /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A counter to enforce unique IDs for each item group minted. uint256 public nextItemGroupId; /// This mapping tracks the number of unique items within each item group. mapping (uint256 => uint256) public itemGroupSizes; /// A mapping of item IDs to their circulating supplies. mapping (uint256 => uint256) public currentSupply; /// A mapping of item IDs to their maximum supplies; true NFTs are unique. mapping (uint256 => uint256) public maximumSupply; /// A mapping of all addresses approved to mint items on behalf of the owner. mapping (address => bool) public approvedMinters; /// An event for tracking the creation of an item group. event ItemGroupCreated(uint256 itemGroupId, uint256 itemGroupSize, address indexed creator); /// A custom modifier which permits only approved minters to mint items. modifier onlyMinters { require(msg.sender == owner() || approvedMinters[msg.sender], "You are not an approved minter for this item."); _; } /** Construct a new ERC-1155 item with an associated FeeOwner fee. @param _uri The metadata URI to perform token ID substitution in. @param _feeOwner The address of a FeeOwner who receives earnings from this item. @param _proxyRegistryAddress An OpenSea proxy registry address. */ constructor(string memory _uri, FeeOwner _feeOwner, address _proxyRegistryAddress) public ERC1155(_uri) { metadataUri = _uri; feeOwner = _feeOwner; proxyRegistryAddress = _proxyRegistryAddress; nextItemGroupId = 0; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. This function returns true if `_operator` is approved to transfer items owned by `_owner`. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** Allow the item owner to update the metadata URI of this collection. @param _uri The new URI to update to. */ function setURI(string calldata _uri) external onlyOwner { metadataUri = _uri; } /** Allows the owner of this contract to grant or remove approval to an external minter of items. @param _minter The external address allowed to mint items. @param _approval The updated `_minter` approval status. */ function approveMinter(address _minter, bool _approval) external onlyOwner { approvedMinters[_minter] = _approval; } /** This function creates an "item group" which may contain one or more individual items. The items within a group may be any combination of fungible or nonfungible. The distinction between a fungible and a nonfungible item is made by checking the item's possible `_maximumSupply`; nonfungible items will naturally have a maximum supply of one because they are unqiue. Creating an item through this function defines its maximum supply. The size of the item group is inferred from the size of the input arrays. The primary purpose of an item group is to create a collection of nonfungible items where each item within the collection is unique but they all share some data as a group. The primary example of this is something like a series of 100 trading cards where each card is unique with its issue number from 1 to 100 but all otherwise reflect the same metadata. In such an example, the `_maximumSupply` of each item is one and the size of the group would be specified by passing an array with 100 elements in it to this function: [ 1, 1, 1, ... 1 ]. Within an item group, items are 1-indexed with the 0-index of the item group supporting lookup of item group metadata. This 0-index metadata includes lookup via `maximumSupply` of the full count of items in the group should all of the items be minted, lookup via `currentSupply` of the number of items circulating from the group as a whole, and lookup via `groupSizes` of the number of unique items within the group. @param initialSupply An array of per-item initial supplies which should be minted immediately. @param _maximumSupply An array of per-item maximum supplies. @param recipients An array of addresses which will receive the initial supply minted for each corresponding item. @param data Any associated data to use if items are minted this transaction. */ function create(uint256[] calldata initialSupply, uint256[] calldata _maximumSupply, address[] calldata recipients, bytes calldata data) external onlyOwner returns (uint256) { uint256 groupSize = initialSupply.length; require(groupSize > 0, "You cannot create an empty item group."); require(initialSupply.length == _maximumSupply.length, "Initial supply length cannot be mismatched with maximum supply length."); require(initialSupply.length == recipients.length, "Initial supply length cannot be mismatched with recipients length."); // Create an item group of requested size using the next available ID. uint256 shiftedGroupId = nextItemGroupId << 128; itemGroupSizes[shiftedGroupId] = groupSize; emit ItemGroupCreated(shiftedGroupId, groupSize, msg.sender); // Record the supply cap of each item being created in the group. uint256 fullCollectionSize = 0; for (uint256 i = 0; i < groupSize; i++) { uint256 itemInitialSupply = initialSupply[i]; uint256 itemMaximumSupply = _maximumSupply[i]; fullCollectionSize = fullCollectionSize.add(itemMaximumSupply); require(itemMaximumSupply > 0, "You cannot create an item which is never mintable."); require(itemInitialSupply <= itemMaximumSupply, "You cannot create an item which exceeds its own supply cap."); // The item ID is offset by one because the zero index of the group is used to store the group size. uint256 itemId = shiftedGroupId.add(i + 1); maximumSupply[itemId] = itemMaximumSupply; // If this item is being initialized with a supply, mint to the recipient. if (itemInitialSupply > 0) { address itemRecipient = recipients[i]; _mint(itemRecipient, itemId, itemInitialSupply, data); currentSupply[itemId] = itemInitialSupply; } } // Also record the full size of the entire item group. maximumSupply[shiftedGroupId] = fullCollectionSize; // Increment our next item group ID and return our created item group ID. nextItemGroupId = nextItemGroupId.add(1); return shiftedGroupId; } /** Allow the item owner to mint a new item, so long as there is supply left to do so. @param to The address to send the newly-minted items to. @param id The ERC-1155 ID of the item being minted. @param amount The amount of the new item to mint. @param data Any associated data for this minting event that should be passed. */ function mint(address to, uint256 id, uint256 amount, bytes calldata data) external onlyMinters { uint256 groupId = id & GROUP_MASK; require(groupId != id, "You cannot mint an item with an issuance index of 0."); currentSupply[groupId] = currentSupply[groupId].add(amount); uint256 newSupply = currentSupply[id].add(amount); currentSupply[id] = newSupply; require(newSupply <= maximumSupply[id], "You cannot mint an item beyond its permitted maximum supply."); _mint(to, id, amount, data); } /** Allow the item owner to mint a new batch of items, so long as there is supply left to do so for each item. @param to The address to send the newly-minted items to. @param ids The ERC-1155 IDs of the items being minted. @param amounts The amounts of the new items to mint. @param data Any associated data for this minting event that should be passed. */ function mintBatch(address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external onlyMinters { require(ids.length > 0, "You cannot perform an empty mint."); require(ids.length == amounts.length, "Supplied IDs length cannot be mismatched with amounts length."); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 groupId = id & GROUP_MASK; require(groupId != id, "You cannot mint an item with an issuance index of 0."); currentSupply[groupId] = currentSupply[groupId].add(amount); uint256 newSupply = currentSupply[id].add(amount); currentSupply[id] = newSupply; require(newSupply <= maximumSupply[id], "You cannot mint an item beyond its permitted maximum supply."); } _mintBatch(to, ids, amounts, data); } } // 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 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.0 <0.8.0; import "./IERC1155.sol"; import "./IERC1155MetadataURI.sol"; import "./IERC1155Receiver.sol"; import "../../utils/Context.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // 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); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; /** @title A simple Shop contract for selling ERC-1155s for Ether via direct minting. @author Tim Clancy This contract is a limited subset of the Shop1155 contract designed to mint items directly to the user upon purchase. This shop additionally requires the owner to directly approve purchase requests from prospective buyers. */ contract ShopEtherMinter1155Curated is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 1; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A user-specified Fee1155 contract to support selling items from. Fee1155 public item; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// The Shop's inventory of item groups for sale. uint256[] public inventory; /// The Shop's price for each item group. mapping (uint256 => uint256) public prices; /// A mapping of each item group ID to an array of addresses with offers. mapping (uint256 => address[]) public bidders; /// A mapping for each item group ID to a mapping of address-price offers. mapping (uint256 => mapping (address => uint256)) public offers; /** Construct a new Shop by providing it a FeeOwner. @param _item The address of the Fee1155 item that will be minting sales. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. */ constructor(Fee1155 _item, FeeOwner _feeOwner) public { item = _item; feeOwner = _feeOwner; } /** Returns the length of the inventory array. @return the length of the inventory array. */ function getInventoryCount() external view returns (uint256) { return inventory.length; } /** Returns the length of the bidder array on an item group. @return the length of the bidder array on an item group. */ function getBidderCount(uint256 groupId) external view returns (uint256) { return bidders[groupId].length; } /** Allows the Shop owner to list a new set of NFT items for sale. @param _groupIds The item group IDs to list for sale in this shop. @param _prices The corresponding purchase price to mint an item of each group. */ function listItems(uint256[] calldata _groupIds, uint256[] calldata _prices) external onlyOwner { require(_groupIds.length > 0, "You must list at least one item."); require(_groupIds.length == _prices.length, "Items length cannot be mismatched with prices length."); // Iterate through every specified item group to list items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; uint256 price = _prices[i]; inventory.push(groupId); prices[groupId] = price; } } /** Allows the Shop owner to remove items from sale. @param _groupIds The group IDs currently listed in the shop to take off sale. */ function removeItems(uint256[] calldata _groupIds) external onlyOwner { require(_groupIds.length > 0, "You must remove at least one item."); // Iterate through every specified item group to remove items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; prices[groupId] = 0; } } /** Allows any user to place an offer to purchase an item group from this Shop. For this shop, users place an offer automatically at the price set by the Shop owner. This function takes a user's Ether into escrow for the offer. @param _itemGroupIds An array of (unique) item groups for a user to place an offer for. */ function makeOffers(uint256[] calldata _itemGroupIds) public nonReentrant payable { require(_itemGroupIds.length > 0, "You must make an offer for at least one item group."); // Iterate through every specified item to make an offer on items. for (uint256 i = 0; i < _itemGroupIds.length; i++) { uint256 groupId = _itemGroupIds[i]; uint256 price = prices[groupId]; require(price > 0, "You cannot make an offer for an item that is not listed."); // Record an offer for this item. bidders[groupId].push(msg.sender); offers[groupId][msg.sender] = msg.value; } } /** Allows any user to cancel an offer for items from this Shop. This function returns a user's Ether if there is any in escrow for the item group. @param _itemGroupIds An array of (unique) item groups for a user to cancel an offer for. */ function cancelOffers(uint256[] calldata _itemGroupIds) public nonReentrant { require(_itemGroupIds.length > 0, "You must cancel an offer for at least one item group."); // Iterate through every specified item to cancel offers on items. uint256 returnedOfferAmount = 0; for (uint256 i = 0; i < _itemGroupIds.length; i++) { uint256 groupId = _itemGroupIds[i]; uint256 offeredValue = offers[groupId][msg.sender]; returnedOfferAmount = returnedOfferAmount.add(offeredValue); offers[groupId][msg.sender] = 0; } // Return the user's escrowed offer Ether. (bool success, ) = payable(msg.sender).call{ value: returnedOfferAmount }(""); require(success, "Returning canceled offer amount failed."); } /** Allows the Shop owner to accept any valid offer from a user. Once the Shop owner accepts the offer, the Ether is distributed according to fees and the item is minted to the user. @param _groupIds The item group IDs to process offers for. @param _bidders The specific bidder for each item group ID to accept. @param _itemIds The specific item ID within the group to mint for the bidder. @param _amounts The amount of specific item to mint for the bidder. */ function acceptOffers(uint256[] calldata _groupIds, address[] calldata _bidders, uint256[] calldata _itemIds, uint256[] calldata _amounts) public nonReentrant onlyOwner { require(_groupIds.length > 0, "You must accept an offer for at least one item."); require(_groupIds.length == _bidders.length, "Group IDs length cannot be mismatched with bidders length."); require(_groupIds.length == _itemIds.length, "Group IDs length cannot be mismatched with item IDs length."); require(_groupIds.length == _amounts.length, "Group IDs length cannot be mismatched with item amounts length."); // Accept all offers and disperse fees accordingly. uint256 feePercent = feeOwner.fee(); uint256 itemRoyaltyPercent = item.feeOwner().fee(); for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; address bidder = _bidders[i]; uint256 itemId = _itemIds[i]; uint256 amount = _amounts[i]; // Verify that the offer being accepted is still valid. uint256 price = prices[groupId]; require(price > 0, "You cannot accept an offer for an item that is not listed."); uint256 offeredPrice = offers[groupId][bidder]; require(offeredPrice >= price, "You cannot accept an offer for less than the current asking price."); // Split fees for this purchase. uint256 feeValue = offeredPrice.mul(feePercent).div(100000); uint256 royaltyValue = offeredPrice.mul(itemRoyaltyPercent).div(100000); (bool success, ) = payable(feeOwner.owner()).call{ value: feeValue }(""); require(success, "Platform fee transfer failed."); (success, ) = payable(item.feeOwner().owner()).call{ value: royaltyValue }(""); require(success, "Creator royalty transfer failed."); (success, ) = payable(owner()).call{ value: offeredPrice.sub(feeValue).sub(royaltyValue) }(""); require(success, "Shop owner transfer failed."); // Mint the item. item.mint(bidder, itemId, amount, ""); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // 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.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; import "./IERC1155Receiver.sol"; import "../../introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155NFTLockable.sol"; import "./Staker.sol"; /** @title A Shop contract for selling NFTs via direct minting through particular pools with specific participation requirements. @author Tim Clancy This launchpad contract is specifically optimized for SuperFarm direct use. */ contract ShopPlatformLaunchpad1155 is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 2; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A user-specified Fee1155 contract to support selling items from. Fee1155NFTLockable public item; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// A user-specified Staker contract to spend user points on. Staker[] public stakers; /** A limit on the number of items that a particular address may purchase across any number of pools in the launchpad. */ uint256 public globalPurchaseLimit; /// A mapping of addresses to the number of items each has purchased globally. mapping (address => uint256) public globalPurchaseCounts; /// The address of the orignal owner of the item contract. address public originalOwner; /// Whether ownership is locked to disable clawback. bool public ownershipLocked; /// A mapping of item group IDs to their next available issue number minus one. mapping (uint256 => uint256) public nextItemIssues; /// The next available ID to be assumed by the next whitelist added. uint256 public nextWhitelistId; /** A mapping of whitelist IDs to specific Whitelist elements. Whitelists may be shared between pools via specifying their ID in a pool requirement. */ mapping (uint256 => Whitelist) public whitelists; /// The next available ID to be assumed by the next pool added. uint256 public nextPoolId; /// A mapping of pool IDs to pools. mapping (uint256 => Pool) public pools; /** This struct is a source of mapping-free input to the `addPool` function. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. */ struct PoolInput { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; PoolRequirement requirement; } /** This struct tracks information about a single item pool in the Shop. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param purchaseCounts A mapping of addresses to the number of items each has purchased from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. @param itemGroups An array of all item groups currently present in this pool. @param currentPoolVersion A version number hashed with item group IDs before being used as keys to other mappings. This supports efficient invalidation of stale mappings. @param itemCaps A mapping of item group IDs to the maximum number this pool is allowed to mint. @param itemMinted A mapping of item group IDs to the number this pool has currently minted. @param itemPricesLength A mapping of item group IDs to the number of price assets available to purchase with. @param itemPrices A mapping of item group IDs to a mapping of available PricePair assets available to purchase with. */ struct Pool { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; mapping (address => uint256) purchaseCounts; PoolRequirement requirement; uint256[] itemGroups; uint256 currentPoolVersion; mapping (bytes32 => uint256) itemCaps; mapping (bytes32 => uint256) itemMinted; mapping (bytes32 => uint256) itemPricesLength; mapping (bytes32 => mapping (uint256 => PricePair)) itemPrices; } /** This struct tracks information about a prerequisite for a user to participate in a pool. @param requiredType A sentinel value for the specific type of asset being required. 0 = a pool which requires no specific assets to participate. 1 = an ERC-20 token, see `requiredAsset`. 2 = an NFT item, see `requiredAsset`. @param requiredAsset Some more specific information about the asset to require. If the `requiredType` is 1, we use this address to find the ERC-20 token that we should be specifically requiring holdings of. If the `requiredType` is 2, we use this address to find the item contract that we should be specifically requiring holdings of. @param requiredAmount The amount of the specified `requiredAsset` required. @param whitelistId The ID of an address whitelist to restrict participants in this pool. To participate, a purchaser must have their address present in the corresponding whitelist. Other requirements from `requiredType` apply. An ID of 0 is a sentinel value for no whitelist: a public pool. */ struct PoolRequirement { uint256 requiredType; address requiredAsset; uint256 requiredAmount; uint256 whitelistId; } /** This struct tracks information about a single asset with associated price that an item is being sold in the shop for. @param assetType A sentinel value for the specific type of asset being used. 0 = non-transferrable points from a Staker; see `asset`. 1 = Ether. 2 = an ERC-20 token, see `asset`. @param asset Some more specific information about the asset to charge in. If the `assetType` is 0, we convert the given address to an integer index for finding a specific Staker from `stakers`. If the `assetType` is 1, we ignore this field. If the `assetType` is 2, we use this address to find the ERC-20 token that we should be specifically charging with. @param price The amount of the specified `assetType` and `asset` to charge. */ struct PricePair { uint256 assetType; address asset; uint256 price; } /** This struct is a source of mapping-free input to the `addWhitelist` function. @param expiryBlock A block number after which this whitelist is automatically considered inactive, no matter the value of `isActive`. @param isActive Whether or not this whitelist is actively restricting purchases in blocks before `expiryBlock`. @param addresses An array of addresses to whitelist for participation in a purchase. */ struct WhitelistInput { uint256 expiryBlock; bool isActive; address[] addresses; } /** This struct tracks information about a single whitelist known to this launchpad. Whitelists may be shared across potentially-multiple item pools. @param expiryBlock A block number after which this whitelist is automatically considered inactive, no matter the value of `isActive`. @param isActive Whether or not this whitelist is actively restricting purchases in blocks before `expiryBlock`. @param currentWhitelistVersion A version number hashed with item group IDs before being used as keys to other mappings. This supports efficient invalidation of stale mappings. @param addresses A mapping of hashed addresses to a flag indicating whether this whitelist allows the address to participate in a purchase. */ struct Whitelist { uint256 expiryBlock; bool isActive; uint256 currentWhitelistVersion; mapping (bytes32 => bool) addresses; } /** This struct tracks information about a single item being sold in a pool. @param groupId The group ID of the specific NFT in the collection being sold by a pool. @param cap The maximum number of items that a pool may mint of the specified `groupId`. @param minted The number of items that a pool has currently minted of the specified `groupId`. @param prices The PricePair options that may be used to purchase this item from its pool. */ struct PoolItem { uint256 groupId; uint256 cap; uint256 minted; PricePair[] prices; } /** This struct contains the information gleaned from the `getPool` and `getPools` functions; it represents a single pool's data. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. @param itemMetadataUri The metadata URI of the item collection being sold by this launchpad. @param items An array of PoolItems representing each item for sale in the pool. */ struct PoolOutput { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; PoolRequirement requirement; string itemMetadataUri; PoolItem[] items; } /** This struct contains the information gleaned from the `getPool` and `getPools` functions; it represents a single pool's data. It also includes additional information relevant to a user's address lookup. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. @param itemMetadataUri The metadata URI of the item collection being sold by this launchpad. @param items An array of PoolItems representing each item for sale in the pool. @param purchaseCount The amount of items purchased from this pool by the specified address. @param whitelistStatus Whether or not the specified address is whitelisted for this pool. */ struct PoolAddressOutput { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; PoolRequirement requirement; string itemMetadataUri; PoolItem[] items; uint256 purchaseCount; bool whitelistStatus; } /// An event to track the original item contract owner clawing back ownership. event OwnershipClawback(); /// An event to track the original item contract owner locking future clawbacks. event OwnershipLocked(); /// An event to track the complete replacement of a pool's data. event PoolUpdated(uint256 poolId, PoolInput pool, uint256[] groupIds, uint256[] amounts, PricePair[][] pricePairs); /// An event to track the complete replacement of addresses in a whitelist. event WhitelistUpdated(uint256 whitelistId, address[] addresses); /// An event to track the addition of addresses to a whitelist. event WhitelistAddition(uint256 whitelistId, address[] addresses); /// An event to track the removal of addresses from a whitelist. event WhitelistRemoval(uint256 whitelistId, address[] addresses); // An event to track activating or deactivating a whitelist. event WhitelistActiveUpdate(uint256 whitelistId, bool isActive); // An event to track the purchase of items from a pool. event ItemPurchased(uint256 poolId, uint256[] itemIds, uint256 assetId, uint256[] amounts, address user); /// @dev a modifier which allows only `originalOwner` to call a function. modifier onlyOriginalOwner() { require(originalOwner == _msgSender(), "You are not the original owner of this contract."); _; } /** Construct a new Shop by providing it a FeeOwner. @param _item The address of the Fee1155NFTLockable item that will be minting sales. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. @param _stakers The addresses of any Stakers to permit spending points from. @param _globalPurchaseLimit A global limit on the number of items that a single address may purchase across all pools in the launchpad. */ constructor(Fee1155NFTLockable _item, FeeOwner _feeOwner, Staker[] memory _stakers, uint256 _globalPurchaseLimit) public { item = _item; feeOwner = _feeOwner; stakers = _stakers; globalPurchaseLimit = _globalPurchaseLimit; nextWhitelistId = 1; originalOwner = item.owner(); ownershipLocked = false; } /** A function which allows the caller to retrieve information about specific pools, the items for sale within, and the collection this launchpad uses. @param poolIds An array of pool IDs to retrieve information about. */ function getPools(uint256[] calldata poolIds) external view returns (PoolOutput[] memory) { PoolOutput[] memory poolOutputs = new PoolOutput[](poolIds.length); for (uint256 i = 0; i < poolIds.length; i++) { uint256 poolId = poolIds[i]; // Process output for each pool. PoolItem[] memory poolItems = new PoolItem[](pools[poolId].itemGroups.length); for (uint256 j = 0; j < pools[poolId].itemGroups.length; j++) { uint256 itemGroupId = pools[poolId].itemGroups[j]; bytes32 itemKey = keccak256(abi.encodePacked(pools[poolId].currentPoolVersion, itemGroupId)); // Parse each price the item is sold at. PricePair[] memory itemPrices = new PricePair[](pools[poolId].itemPricesLength[itemKey]); for (uint256 k = 0; k < pools[poolId].itemPricesLength[itemKey]; k++) { itemPrices[k] = pools[poolId].itemPrices[itemKey][k]; } // Track the item. poolItems[j] = PoolItem({ groupId: itemGroupId, cap: pools[poolId].itemCaps[itemKey], minted: pools[poolId].itemMinted[itemKey], prices: itemPrices }); } // Track the pool. poolOutputs[i] = PoolOutput({ name: pools[poolId].name, startBlock: pools[poolId].startBlock, endBlock: pools[poolId].endBlock, purchaseLimit: pools[poolId].purchaseLimit, requirement: pools[poolId].requirement, itemMetadataUri: item.metadataUri(), items: poolItems }); } // Return the pools. return poolOutputs; } /** A function which allows the caller to retrieve the number of items specific addresses have purchased from specific pools. @param poolIds The IDs of the pools to check for addresses in `purchasers`. @param purchasers The addresses to check the purchase counts for. */ function getPurchaseCounts(uint256[] calldata poolIds, address[] calldata purchasers) external view returns (uint256[][] memory) { uint256[][] memory purchaseCounts; for (uint256 i = 0; i < poolIds.length; i++) { uint256 poolId = poolIds[i]; for (uint256 j = 0; j < purchasers.length; j++) { address purchaser = purchasers[j]; purchaseCounts[j][i] = pools[poolId].purchaseCounts[purchaser]; } } return purchaseCounts; } /** A function which allows the caller to retrieve information about specific pools, the items for sale within, and the collection this launchpad uses. A provided address differentiates this function from `getPools`; the added address enables this function to retrieve pool data as well as whitelisting and purchase count details for the provided address. @param poolIds An array of pool IDs to retrieve information about. @param userAddress An address which enables this function to support additional relevant data lookups. */ function getPoolsWithAddress(uint256[] calldata poolIds, address userAddress) external view returns (PoolAddressOutput[] memory) { PoolAddressOutput[] memory poolOutputs = new PoolAddressOutput[](poolIds.length); for (uint256 i = 0; i < poolIds.length; i++) { uint256 poolId = poolIds[i]; // Process output for each pool. PoolItem[] memory poolItems = new PoolItem[](pools[poolId].itemGroups.length); for (uint256 j = 0; j < pools[poolId].itemGroups.length; j++) { uint256 itemGroupId = pools[poolId].itemGroups[j]; bytes32 itemKey = keccak256(abi.encodePacked(pools[poolId].currentPoolVersion, itemGroupId)); // Parse each price the item is sold at. PricePair[] memory itemPrices = new PricePair[](pools[poolId].itemPricesLength[itemKey]); for (uint256 k = 0; k < pools[poolId].itemPricesLength[itemKey]; k++) { itemPrices[k] = pools[poolId].itemPrices[itemKey][k]; } // Track the item. poolItems[j] = PoolItem({ groupId: itemGroupId, cap: pools[poolId].itemCaps[itemKey], minted: pools[poolId].itemMinted[itemKey], prices: itemPrices }); } // Track the pool. uint256 whitelistId = pools[poolId].requirement.whitelistId; bytes32 addressKey = keccak256(abi.encode(whitelists[whitelistId].currentWhitelistVersion, userAddress)); poolOutputs[i] = PoolAddressOutput({ name: pools[poolId].name, startBlock: pools[poolId].startBlock, endBlock: pools[poolId].endBlock, purchaseLimit: pools[poolId].purchaseLimit, requirement: pools[poolId].requirement, itemMetadataUri: item.metadataUri(), items: poolItems, purchaseCount: pools[poolId].purchaseCounts[userAddress], whitelistStatus: whitelists[whitelistId].addresses[addressKey] }); } // Return the pools. return poolOutputs; } /** A function which allows the original owner of the item contract to revoke ownership from the launchpad. */ function ownershipClawback() external onlyOriginalOwner { require(!ownershipLocked, "Ownership transfers have been locked."); item.transferOwnership(originalOwner); // Emit an event that the original owner of the item contract has clawed the contract back. emit OwnershipClawback(); } /** A function which allows the original owner of this contract to lock all future ownership clawbacks. */ function lockOwnership() external onlyOriginalOwner { ownershipLocked = true; // Emit an event that the contract's ownership transferrance is locked. emit OwnershipLocked(); } /** Allow the owner of the Shop to add a new pool of items to purchase. @param pool The PoolInput full of data defining the pool's operation. @param _groupIds The specific Fee1155 item group IDs to sell in this pool, keyed to `_amounts`. @param _amounts The maximum amount of each particular groupId that can be sold by this pool. @param _pricePairs The asset address to price pairings to use for selling each item. */ function addPool(PoolInput calldata pool, uint256[] calldata _groupIds, uint256[] calldata _amounts, PricePair[][] memory _pricePairs) external onlyOwner { updatePool(nextPoolId, pool, _groupIds, _amounts, _pricePairs); // Increment the ID which will be used by the next pool added. nextPoolId = nextPoolId.add(1); } /** Allow the owner of the Shop to update an existing pool of items. @param poolId The ID of the pool to update. @param pool The PoolInput full of data defining the pool's operation. @param _groupIds The specific Fee1155 item group IDs to sell in this pool, keyed to `_amounts`. @param _amounts The maximum amount of each particular groupId that can be sold by this pool. @param _pricePairs The asset address to price pairings to use for selling each item. */ function updatePool(uint256 poolId, PoolInput calldata pool, uint256[] calldata _groupIds, uint256[] calldata _amounts, PricePair[][] memory _pricePairs) public onlyOwner { require(poolId <= nextPoolId, "You cannot update a non-existent pool."); require(pool.endBlock >= pool.startBlock, "You cannot create a pool which ends before it starts."); require(_groupIds.length > 0, "You must list at least one item group."); require(_groupIds.length == _amounts.length, "Item groups length cannot be mismatched with mintable amounts length."); require(_groupIds.length == _pricePairs.length, "Item groups length cannot be mismatched with price pair inputlength."); // Immediately store some given information about this pool. uint256 newPoolVersion = pools[poolId].currentPoolVersion.add(1); pools[poolId] = Pool({ name: pool.name, startBlock: pool.startBlock, endBlock: pool.endBlock, purchaseLimit: pool.purchaseLimit, itemGroups: _groupIds, currentPoolVersion: newPoolVersion, requirement: pool.requirement }); // Store the amount of each item group that this pool may mint. for (uint256 i = 0; i < _groupIds.length; i++) { require(_amounts[i] > 0, "You cannot add an item with no mintable amount."); bytes32 itemKey = keccak256(abi.encode(newPoolVersion, _groupIds[i])); pools[poolId].itemCaps[itemKey] = _amounts[i]; // Store future purchase information for the item group. for (uint256 j = 0; j < _pricePairs[i].length; j++) { pools[poolId].itemPrices[itemKey][j] = _pricePairs[i][j]; } pools[poolId].itemPricesLength[itemKey] = _pricePairs[i].length; } // Emit an event indicating that a pool has been updated. emit PoolUpdated(poolId, pool, _groupIds, _amounts, _pricePairs); } /** Allow the owner to add a new whitelist. @param whitelist The WhitelistInput full of data defining the new whitelist. */ function addWhitelist(WhitelistInput memory whitelist) external onlyOwner { updateWhitelist(nextWhitelistId, whitelist); // Increment the ID which will be used by the next whitelist added. nextWhitelistId = nextWhitelistId.add(1); } /** Allow the owner to update a whitelist. @param whitelistId The whitelist ID to replace with the new whitelist. @param whitelist The WhitelistInput full of data defining the new whitelist. */ function updateWhitelist(uint256 whitelistId, WhitelistInput memory whitelist) public onlyOwner { uint256 newWhitelistVersion = whitelists[whitelistId].currentWhitelistVersion.add(1); // Immediately store some given information about this whitelist. whitelists[whitelistId] = Whitelist({ expiryBlock: whitelist.expiryBlock, isActive: whitelist.isActive, currentWhitelistVersion: newWhitelistVersion }); // Invalidate the old mapping and store the new participation flags. for (uint256 i = 0; i < whitelist.addresses.length; i++) { bytes32 addressKey = keccak256(abi.encode(newWhitelistVersion, whitelist.addresses[i])); whitelists[whitelistId].addresses[addressKey] = true; } // Emit an event to track the new, replaced state of the whitelist. emit WhitelistUpdated(whitelistId, whitelist.addresses); } /** Allow the owner to add specified addresses to a whitelist. @param whitelistId The ID of the whitelist to add users to. @param addresses The array of addresses to add. */ function addToWhitelist(uint256 whitelistId, address[] calldata addresses) public onlyOwner { uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; for (uint256 i = 0; i < addresses.length; i++) { bytes32 addressKey = keccak256(abi.encode(whitelistVersion, addresses[i])); whitelists[whitelistId].addresses[addressKey] = true; } // Emit an event to track the addition of new addresses to the whitelist. emit WhitelistAddition(whitelistId, addresses); } /** Allow the owner to remove specified addresses from a whitelist. @param whitelistId The ID of the whitelist to remove users from. @param addresses The array of addresses to remove. */ function removeFromWhitelist(uint256 whitelistId, address[] calldata addresses) public onlyOwner { uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; for (uint256 i = 0; i < addresses.length; i++) { bytes32 addressKey = keccak256(abi.encode(whitelistVersion, addresses[i])); whitelists[whitelistId].addresses[addressKey] = false; } // Emit an event to track the removal of addresses from the whitelist. emit WhitelistRemoval(whitelistId, addresses); } /** Allow the owner to manually set the active status of a specific whitelist. @param whitelistId The ID of the whitelist to update the active flag for. @param isActive The boolean flag to enable or disable the whitelist. */ function setWhitelistActive(uint256 whitelistId, bool isActive) public onlyOwner { whitelists[whitelistId].isActive = isActive; // Emit an event to track whitelist activation status changes. emit WhitelistActiveUpdate(whitelistId, isActive); } /** A function which allows the caller to retrieve whether or not addresses can participate in some given whitelists. @param whitelistIds The IDs of the whitelists to check for addresses. @param addresses The addresses to check whitelist eligibility for. */ function getWhitelistStatus(uint256[] calldata whitelistIds, address[] calldata addresses) external view returns (bool[][] memory) { bool[][] memory whitelistStatus; for (uint256 i = 0; i < whitelistIds.length; i++) { uint256 whitelistId = whitelistIds[i]; uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; for (uint256 j = 0; j < addresses.length; j++) { bytes32 addressKey = keccak256(abi.encode(whitelistVersion, addresses[j])); whitelistStatus[j][i] = whitelists[whitelistId].addresses[addressKey]; } } return whitelistStatus; } /** Allow a user to purchase an item from a pool. @param poolId The ID of the particular pool that the user would like to purchase from. @param groupId The item group ID that the user would like to purchase. @param assetId The type of payment asset that the user would like to purchase with. @param amount The amount of item that the user would like to purchase. */ function mintFromPool(uint256 poolId, uint256 groupId, uint256 assetId, uint256 amount) external nonReentrant payable { require(amount > 0, "You must purchase at least one item."); require(poolId < nextPoolId, "You can only purchase items from an active pool."); // Verify that the asset being used in the purchase is valid. bytes32 itemKey = keccak256(abi.encode(pools[poolId].currentPoolVersion, groupId)); require(assetId < pools[poolId].itemPricesLength[itemKey], "Your specified asset ID is not valid."); // Verify that the pool is still running its sale. require(block.number >= pools[poolId].startBlock && block.number <= pools[poolId].endBlock, "This pool is not currently running its sale."); // Verify that the pool is respecting per-address global purchase limits. uint256 userGlobalPurchaseAmount = amount.add(globalPurchaseCounts[msg.sender]); require(userGlobalPurchaseAmount <= globalPurchaseLimit, "You may not purchase any more items from this sale."); // Verify that the pool is respecting per-address pool purchase limits. uint256 userPoolPurchaseAmount = amount.add(pools[poolId].purchaseCounts[msg.sender]); require(userPoolPurchaseAmount <= pools[poolId].purchaseLimit, "You may not purchase any more items from this pool."); // Verify that the pool is either public, whitelist-expired, or an address is whitelisted. { uint256 whitelistId = pools[poolId].requirement.whitelistId; uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; bytes32 addressKey = keccak256(abi.encode(whitelistVersion, msg.sender)); bool addressWhitelisted = whitelists[whitelistId].addresses[addressKey]; require(whitelistId == 0 || block.number > whitelists[whitelistId].expiryBlock || addressWhitelisted || !whitelists[whitelistId].isActive, "You are not whitelisted on this pool."); } // Verify that the pool is not depleted by the user's purchase. uint256 newCirculatingTotal = pools[poolId].itemMinted[itemKey].add(amount); require(newCirculatingTotal <= pools[poolId].itemCaps[itemKey], "There are not enough items available for you to purchase."); // Verify that the user meets any requirements gating participation in this pool. PoolRequirement memory poolRequirement = pools[poolId].requirement; if (poolRequirement.requiredType == 1) { IERC20 requiredToken = IERC20(poolRequirement.requiredAsset); require(requiredToken.balanceOf(msg.sender) >= poolRequirement.requiredAmount, "You do not have enough required token to participate in this pool."); } // TODO: supporting item gate requirement requires upgrading the Fee1155 contract. // else if (poolRequirement.requiredType == 2) { // Fee1155 requiredItem = Fee1155(poolRequirement.requiredAsset); // require(requiredItem.balanceOf(msg.sender) >= poolRequirement.requiredAmount, // "You do not have enough required item to participate in this pool."); // } // Process payment for the user. // If the sentinel value for the point asset type is found, sell for points. // This involves converting the asset from an address to a Staker index. PricePair memory sellingPair = pools[poolId].itemPrices[itemKey][assetId]; if (sellingPair.assetType == 0) { uint256 stakerIndex = uint256(sellingPair.asset); stakers[stakerIndex].spendPoints(msg.sender, sellingPair.price.mul(amount)); // If the sentinel value for the Ether asset type is found, sell for Ether. } else if (sellingPair.assetType == 1) { uint256 etherPrice = sellingPair.price.mul(amount); require(msg.value >= etherPrice, "You did not send enough Ether to complete this purchase."); (bool success, ) = payable(owner()).call{ value: msg.value }(""); require(success, "Shop owner transfer failed."); // Otherwise, attempt to sell for an ERC20 token. } else { IERC20 sellingAsset = IERC20(sellingPair.asset); uint256 tokenPrice = sellingPair.price.mul(amount); require(sellingAsset.balanceOf(msg.sender) >= tokenPrice, "You do not have enough token to complete this purchase."); sellingAsset.safeTransferFrom(msg.sender, owner(), tokenPrice); } // If payment is successful, mint each of the user's purchased items. uint256[] memory itemIds = new uint256[](amount); uint256[] memory amounts = new uint256[](amount); uint256 nextIssueNumber = nextItemIssues[groupId]; { uint256 shiftedGroupId = groupId << 128; for (uint256 i = 1; i <= amount; i++) { uint256 itemId = shiftedGroupId.add(nextIssueNumber).add(i); itemIds[i - 1] = itemId; amounts[i - 1] = 1; } } // Mint the items. item.createNFT(msg.sender, itemIds, amounts, ""); // Update the tracker for available item issue numbers. nextItemIssues[groupId] = nextIssueNumber.add(amount); // Update the count of circulating items from this pool. pools[poolId].itemMinted[itemKey] = newCirculatingTotal; // Update the pool's count of items that a user has purchased. pools[poolId].purchaseCounts[msg.sender] = userPoolPurchaseAmount; // Update the global count of items that a user has purchased. globalPurchaseCounts[msg.sender] = userGlobalPurchaseAmount; // Emit an event indicating a successful purchase. emit ItemPurchased(poolId, itemIds, assetId, amounts, msg.sender); } /** Sweep all of a particular ERC-20 token from the contract. @param _token The token to sweep the balance from. */ function sweep(IERC20 _token) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.safeTransferFrom(address(this), msg.sender, balance); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; /** @title An OpenSea delegate proxy contract which we include for whitelisting. @author OpenSea */ contract OwnableDelegateProxy { } /** @title An OpenSea proxy registry contract which we include for whitelisting. @author OpenSea */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** @title An ERC-1155 item creation contract which specifies an associated FeeOwner who receives royalties from sales of created items. @author Tim Clancy The fee set by the FeeOwner on this Item is honored by Shop contracts. In addition to the inherited OpenZeppelin dependency, this uses ideas from the original ERC-1155 reference implementation. */ contract Fee1155NFTLockable is ERC1155, Ownable { using SafeMath for uint256; /// A version number for this fee-bearing 1155 item contract's interface. uint256 public version = 1; /// The ERC-1155 URI for looking up item metadata using {id} substitution. string public metadataUri; /// A user-specified FeeOwner to receive a portion of item sale earnings. FeeOwner public feeOwner; /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /// A counter to enforce unique IDs for each item group minted. uint256 public nextItemGroupId; /// This mapping tracks the number of unique items within each item group. mapping (uint256 => uint256) public itemGroupSizes; /// Whether or not the item collection has been locked to further minting. bool public locked; /// An event for tracking the creation of an item group. event ItemGroupCreated(uint256 itemGroupId, uint256 itemGroupSize, address indexed creator); /** Construct a new ERC-1155 item with an associated FeeOwner fee. @param _uri The metadata URI to perform token ID substitution in. @param _feeOwner The address of a FeeOwner who receives earnings from this item. */ constructor(string memory _uri, FeeOwner _feeOwner, address _proxyRegistryAddress) public ERC1155(_uri) { metadataUri = _uri; feeOwner = _feeOwner; proxyRegistryAddress = _proxyRegistryAddress; nextItemGroupId = 0; locked = false; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. This function returns true if `_operator` is approved to transfer items owned by `_owner`. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** Allow the item owner to update the metadata URI of this collection. @param _uri The new URI to update to. */ function setURI(string calldata _uri) external onlyOwner { metadataUri = _uri; } /** Allow the item owner to forever lock this contract to further item minting. */ function lock() external onlyOwner { locked = true; } /** Create a new NFT item group of a specific size. NFTs within a group share a group ID in the upper 128-bits of their full item ID. Within a group NFTs can be distinguished for the purposes of serializing issue numbers. @param recipient The address to receive all NFTs within the newly-created group. @param ids The item IDs for the new items to create. @param amounts The amount of each corresponding item ID to create. @param data Any associated data to use on items minted in this transaction. */ function createNFT(address recipient, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external onlyOwner returns (uint256) { require(!locked, "You cannot create more NFTs on a locked collection."); require(ids.length > 0, "You cannot create an empty item group."); require(ids.length == amounts.length, "IDs length cannot be mismatched with amounts length."); // Create an item group of requested size using the next available ID. uint256 shiftedGroupId = nextItemGroupId << 128; itemGroupSizes[shiftedGroupId] = ids.length; // Mint the entire batch of items. _mintBatch(recipient, ids, amounts, data); // Increment our next item group ID and return our created item group ID. nextItemGroupId = nextItemGroupId.add(1); emit ItemGroupCreated(shiftedGroupId, ids.length, msg.sender); return shiftedGroupId; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title An asset staking contract. @author Tim Clancy This staking contract disburses tokens from its internal reservoir according to a fixed emission schedule. Assets can be assigned varied staking weights. This code is inspired by and modified from Sushi's Master Chef contract. https://github.com/sushiswap/sushiswap/blob/master/contracts/MasterChef.sol */ contract Staker is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // A user-specified, descriptive name for this Staker. string public name; // The token to disburse. IERC20 public token; // The amount of the disbursed token deposited by users. This is used for the // special case where a staking pool has been created for the disbursed token. // This is required to prevent the Staker itself from reducing emissions. uint256 public totalTokenDeposited; // A flag signalling whether the contract owner can add or set developers. bool public canAlterDevelopers; // An array of developer addresses for finding shares in the share mapping. address[] public developerAddresses; // A mapping of developer addresses to their percent share of emissions. // Share percentages are represented as 1/1000th of a percent. That is, a 1% // share of emissions should map an address to 1000. mapping (address => uint256) public developerShares; // A flag signalling whether or not the contract owner can alter emissions. bool public canAlterTokenEmissionSchedule; bool public canAlterPointEmissionSchedule; // The token emission schedule of the Staker. This emission schedule maps a // block number to the amount of tokens or points that should be disbursed with every // block beginning at said block number. struct EmissionPoint { uint256 blockNumber; uint256 rate; } // An array of emission schedule key blocks for finding emission rate changes. uint256 public tokenEmissionBlockCount; mapping (uint256 => EmissionPoint) public tokenEmissionBlocks; uint256 public pointEmissionBlockCount; mapping (uint256 => EmissionPoint) public pointEmissionBlocks; // Store the very earliest possible emission block for quick reference. uint256 MAX_INT = 2**256 - 1; uint256 internal earliestTokenEmissionBlock; uint256 internal earliestPointEmissionBlock; // Information for each pool that can be staked in. // - token: the address of the ERC20 asset that is being staked in the pool. // - strength: the relative token emission strength of this pool. // - lastRewardBlock: the last block number where token distribution occurred. // - tokensPerShare: accumulated tokens per share times 1e12. // - pointsPerShare: accumulated points per share times 1e12. struct PoolInfo { IERC20 token; uint256 tokenStrength; uint256 tokensPerShare; uint256 pointStrength; uint256 pointsPerShare; uint256 lastRewardBlock; } IERC20[] public poolTokens; // Stored information for each available pool per its token address. mapping (IERC20 => PoolInfo) public poolInfo; // Information for each user per staking pool: // - amount: the amount of the pool asset being provided by the user. // - tokenPaid: the value of the user's total earning that has been paid out. // -- pending reward = (user.amount * pool.tokensPerShare) - user.rewardDebt. // - pointPaid: the value of the user's total point earnings that has been paid out. struct UserInfo { uint256 amount; uint256 tokenPaid; uint256 pointPaid; } // Stored information for each user staking in each pool. mapping (IERC20 => mapping (address => UserInfo)) public userInfo; // The total sum of the strength of all pools. uint256 public totalTokenStrength; uint256 public totalPointStrength; // The total amount of the disbursed token ever emitted by this Staker. uint256 public totalTokenDisbursed; // Users additionally accrue non-token points for participating via staking. mapping (address => uint256) public userPoints; mapping (address => uint256) public userSpentPoints; // A map of all external addresses that are permitted to spend user points. mapping (address => bool) public approvedPointSpenders; // Events for depositing assets into the Staker and later withdrawing them. event Deposit(address indexed user, IERC20 indexed token, uint256 amount); event Withdraw(address indexed user, IERC20 indexed token, uint256 amount); // An event for tracking when a user has spent points. event SpentPoints(address indexed source, address indexed user, uint256 amount); /** Construct a new Staker by providing it a name and the token to disburse. @param _name The name of the Staker contract. @param _token The token to reward stakers in this contract with. */ constructor(string memory _name, IERC20 _token) public { name = _name; token = _token; token.approve(address(this), MAX_INT); canAlterDevelopers = true; canAlterTokenEmissionSchedule = true; earliestTokenEmissionBlock = MAX_INT; canAlterPointEmissionSchedule = true; earliestPointEmissionBlock = MAX_INT; } /** Add a new developer to the Staker or overwrite an existing one. This operation requires that developer address addition is not locked. @param _developerAddress The additional developer's address. @param _share The share in 1/1000th of a percent of each token emission sent to this new developer. */ function addDeveloper(address _developerAddress, uint256 _share) external onlyOwner { require(canAlterDevelopers, "This Staker has locked the addition of developers; no more may be added."); developerAddresses.push(_developerAddress); developerShares[_developerAddress] = _share; } /** Permanently forfeits owner ability to alter the state of Staker developers. Once called, this function is intended to give peace of mind to the Staker's developers and community that the fee structure is now immutable. */ function lockDevelopers() external onlyOwner { canAlterDevelopers = false; } /** A developer may at any time update their address or voluntarily reduce their share of emissions by calling this function from their current address. Note that updating a developer's share to zero effectively removes them. @param _newDeveloperAddress An address to update this developer's address. @param _newShare The new share in 1/1000th of a percent of each token emission sent to this developer. */ function updateDeveloper(address _newDeveloperAddress, uint256 _newShare) external { uint256 developerShare = developerShares[msg.sender]; require(developerShare > 0, "You are not a developer of this Staker."); require(_newShare <= developerShare, "You cannot increase your developer share."); developerShares[msg.sender] = 0; developerAddresses.push(_newDeveloperAddress); developerShares[_newDeveloperAddress] = _newShare; } /** Set new emission details to the Staker or overwrite existing ones. This operation requires that emission schedule alteration is not locked. @param _tokenSchedule An array of EmissionPoints defining the token schedule. @param _pointSchedule An array of EmissionPoints defining the point schedule. */ function setEmissions(EmissionPoint[] memory _tokenSchedule, EmissionPoint[] memory _pointSchedule) external onlyOwner { if (_tokenSchedule.length > 0) { require(canAlterTokenEmissionSchedule, "This Staker has locked the alteration of token emissions."); tokenEmissionBlockCount = _tokenSchedule.length; for (uint256 i = 0; i < tokenEmissionBlockCount; i++) { tokenEmissionBlocks[i] = _tokenSchedule[i]; if (earliestTokenEmissionBlock > _tokenSchedule[i].blockNumber) { earliestTokenEmissionBlock = _tokenSchedule[i].blockNumber; } } } require(tokenEmissionBlockCount > 0, "You must set the token emission schedule."); if (_pointSchedule.length > 0) { require(canAlterPointEmissionSchedule, "This Staker has locked the alteration of point emissions."); pointEmissionBlockCount = _pointSchedule.length; for (uint256 i = 0; i < pointEmissionBlockCount; i++) { pointEmissionBlocks[i] = _pointSchedule[i]; if (earliestPointEmissionBlock > _pointSchedule[i].blockNumber) { earliestPointEmissionBlock = _pointSchedule[i].blockNumber; } } } require(tokenEmissionBlockCount > 0, "You must set the point emission schedule."); } /** Permanently forfeits owner ability to alter the emission schedule. Once called, this function is intended to give peace of mind to the Staker's developers and community that the inflation rate is now immutable. */ function lockTokenEmissions() external onlyOwner { canAlterTokenEmissionSchedule = false; } /** Permanently forfeits owner ability to alter the emission schedule. Once called, this function is intended to give peace of mind to the Staker's developers and community that the inflation rate is now immutable. */ function lockPointEmissions() external onlyOwner { canAlterPointEmissionSchedule = false; } /** Returns the length of the developer address array. @return the length of the developer address array. */ function getDeveloperCount() external view returns (uint256) { return developerAddresses.length; } /** Returns the length of the staking pool array. @return the length of the staking pool array. */ function getPoolCount() external view returns (uint256) { return poolTokens.length; } /** Returns the amount of token that has not been disbursed by the Staker yet. @return the amount of token that has not been disbursed by the Staker yet. */ function getRemainingToken() external view returns (uint256) { return token.balanceOf(address(this)); } /** Allows the contract owner to add a new asset pool to the Staker or overwrite an existing one. @param _token The address of the asset to base this staking pool off of. @param _tokenStrength The relative strength of the new asset for earning token. @param _pointStrength The relative strength of the new asset for earning points. */ function addPool(IERC20 _token, uint256 _tokenStrength, uint256 _pointStrength) external onlyOwner { require(tokenEmissionBlockCount > 0 && pointEmissionBlockCount > 0, "Staking pools cannot be addded until an emission schedule has been defined."); uint256 lastTokenRewardBlock = block.number > earliestTokenEmissionBlock ? block.number : earliestTokenEmissionBlock; uint256 lastPointRewardBlock = block.number > earliestPointEmissionBlock ? block.number : earliestPointEmissionBlock; uint256 lastRewardBlock = lastTokenRewardBlock > lastPointRewardBlock ? lastTokenRewardBlock : lastPointRewardBlock; if (address(poolInfo[_token].token) == address(0)) { poolTokens.push(_token); totalTokenStrength = totalTokenStrength.add(_tokenStrength); totalPointStrength = totalPointStrength.add(_pointStrength); poolInfo[_token] = PoolInfo({ token: _token, tokenStrength: _tokenStrength, tokensPerShare: 0, pointStrength: _pointStrength, pointsPerShare: 0, lastRewardBlock: lastRewardBlock }); } else { totalTokenStrength = totalTokenStrength.sub(poolInfo[_token].tokenStrength).add(_tokenStrength); poolInfo[_token].tokenStrength = _tokenStrength; totalPointStrength = totalPointStrength.sub(poolInfo[_token].pointStrength).add(_pointStrength); poolInfo[_token].pointStrength = _pointStrength; } } /** Uses the emission schedule to calculate the total amount of staking reward token that was emitted between two specified block numbers. @param _fromBlock The block to begin calculating emissions from. @param _toBlock The block to calculate total emissions up to. */ function getTotalEmittedTokens(uint256 _fromBlock, uint256 _toBlock) public view returns (uint256) { require(_toBlock >= _fromBlock, "Tokens cannot be emitted from a higher block to a lower block."); uint256 totalEmittedTokens = 0; uint256 workingRate = 0; uint256 workingBlock = _fromBlock; for (uint256 i = 0; i < tokenEmissionBlockCount; ++i) { uint256 emissionBlock = tokenEmissionBlocks[i].blockNumber; uint256 emissionRate = tokenEmissionBlocks[i].rate; if (_toBlock < emissionBlock) { totalEmittedTokens = totalEmittedTokens.add(_toBlock.sub(workingBlock).mul(workingRate)); return totalEmittedTokens; } else if (workingBlock < emissionBlock) { totalEmittedTokens = totalEmittedTokens.add(emissionBlock.sub(workingBlock).mul(workingRate)); workingBlock = emissionBlock; } workingRate = emissionRate; } if (workingBlock < _toBlock) { totalEmittedTokens = totalEmittedTokens.add(_toBlock.sub(workingBlock).mul(workingRate)); } return totalEmittedTokens; } /** Uses the emission schedule to calculate the total amount of points emitted between two specified block numbers. @param _fromBlock The block to begin calculating emissions from. @param _toBlock The block to calculate total emissions up to. */ function getTotalEmittedPoints(uint256 _fromBlock, uint256 _toBlock) public view returns (uint256) { require(_toBlock >= _fromBlock, "Points cannot be emitted from a higher block to a lower block."); uint256 totalEmittedPoints = 0; uint256 workingRate = 0; uint256 workingBlock = _fromBlock; for (uint256 i = 0; i < pointEmissionBlockCount; ++i) { uint256 emissionBlock = pointEmissionBlocks[i].blockNumber; uint256 emissionRate = pointEmissionBlocks[i].rate; if (_toBlock < emissionBlock) { totalEmittedPoints = totalEmittedPoints.add(_toBlock.sub(workingBlock).mul(workingRate)); return totalEmittedPoints; } else if (workingBlock < emissionBlock) { totalEmittedPoints = totalEmittedPoints.add(emissionBlock.sub(workingBlock).mul(workingRate)); workingBlock = emissionBlock; } workingRate = emissionRate; } if (workingBlock < _toBlock) { totalEmittedPoints = totalEmittedPoints.add(_toBlock.sub(workingBlock).mul(workingRate)); } return totalEmittedPoints; } /** Update the pool corresponding to the specified token address. @param _token The address of the asset to update the corresponding pool for. */ function updatePool(IERC20 _token) internal { PoolInfo storage pool = poolInfo[_token]; if (block.number <= pool.lastRewardBlock) { return; } uint256 poolTokenSupply = pool.token.balanceOf(address(this)); if (address(_token) == address(token)) { poolTokenSupply = totalTokenDeposited; } if (poolTokenSupply <= 0) { pool.lastRewardBlock = block.number; return; } // Calculate tokens and point rewards for this pool. uint256 totalEmittedTokens = getTotalEmittedTokens(pool.lastRewardBlock, block.number); uint256 tokensReward = totalEmittedTokens.mul(pool.tokenStrength).div(totalTokenStrength).mul(1e12); uint256 totalEmittedPoints = getTotalEmittedPoints(pool.lastRewardBlock, block.number); uint256 pointsReward = totalEmittedPoints.mul(pool.pointStrength).div(totalPointStrength).mul(1e30); // Directly pay developers their corresponding share of tokens and points. for (uint256 i = 0; i < developerAddresses.length; ++i) { address developer = developerAddresses[i]; uint256 share = developerShares[developer]; uint256 devTokens = tokensReward.mul(share).div(100000); tokensReward = tokensReward - devTokens; uint256 devPoints = pointsReward.mul(share).div(100000); pointsReward = pointsReward - devPoints; token.safeTransferFrom(address(this), developer, devTokens.div(1e12)); userPoints[developer] = userPoints[developer].add(devPoints.div(1e30)); } // Update the pool rewards per share to pay users the amount remaining. pool.tokensPerShare = pool.tokensPerShare.add(tokensReward.div(poolTokenSupply)); pool.pointsPerShare = pool.pointsPerShare.add(pointsReward.div(poolTokenSupply)); pool.lastRewardBlock = block.number; } /** A function to easily see the amount of token rewards pending for a user on a given pool. Returns the pending reward token amount. @param _token The address of a particular staking pool asset to check for a pending reward. @param _user The user address to check for a pending reward. @return the pending reward token amount. */ function getPendingTokens(IERC20 _token, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_token]; UserInfo storage user = userInfo[_token][_user]; uint256 tokensPerShare = pool.tokensPerShare; uint256 poolTokenSupply = pool.token.balanceOf(address(this)); if (address(_token) == address(token)) { poolTokenSupply = totalTokenDeposited; } if (block.number > pool.lastRewardBlock && poolTokenSupply > 0) { uint256 totalEmittedTokens = getTotalEmittedTokens(pool.lastRewardBlock, block.number); uint256 tokensReward = totalEmittedTokens.mul(pool.tokenStrength).div(totalTokenStrength).mul(1e12); tokensPerShare = tokensPerShare.add(tokensReward.div(poolTokenSupply)); } return user.amount.mul(tokensPerShare).div(1e12).sub(user.tokenPaid); } /** A function to easily see the amount of point rewards pending for a user on a given pool. Returns the pending reward point amount. @param _token The address of a particular staking pool asset to check for a pending reward. @param _user The user address to check for a pending reward. @return the pending reward token amount. */ function getPendingPoints(IERC20 _token, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_token]; UserInfo storage user = userInfo[_token][_user]; uint256 pointsPerShare = pool.pointsPerShare; uint256 poolTokenSupply = pool.token.balanceOf(address(this)); if (address(_token) == address(token)) { poolTokenSupply = totalTokenDeposited; } if (block.number > pool.lastRewardBlock && poolTokenSupply > 0) { uint256 totalEmittedPoints = getTotalEmittedPoints(pool.lastRewardBlock, block.number); uint256 pointsReward = totalEmittedPoints.mul(pool.pointStrength).div(totalPointStrength).mul(1e30); pointsPerShare = pointsPerShare.add(pointsReward.div(poolTokenSupply)); } return user.amount.mul(pointsPerShare).div(1e30).sub(user.pointPaid); } /** Return the number of points that the user has available to spend. @return the number of points that the user has available to spend. */ function getAvailablePoints(address _user) public view returns (uint256) { uint256 concreteTotal = userPoints[_user]; uint256 pendingTotal = 0; for (uint256 i = 0; i < poolTokens.length; ++i) { IERC20 poolToken = poolTokens[i]; uint256 _pendingPoints = getPendingPoints(poolToken, _user); pendingTotal = pendingTotal.add(_pendingPoints); } uint256 spentTotal = userSpentPoints[_user]; return concreteTotal.add(pendingTotal).sub(spentTotal); } /** Return the total number of points that the user has ever accrued. @return the total number of points that the user has ever accrued. */ function getTotalPoints(address _user) external view returns (uint256) { uint256 concreteTotal = userPoints[_user]; uint256 pendingTotal = 0; for (uint256 i = 0; i < poolTokens.length; ++i) { IERC20 poolToken = poolTokens[i]; uint256 _pendingPoints = getPendingPoints(poolToken, _user); pendingTotal = pendingTotal.add(_pendingPoints); } return concreteTotal.add(pendingTotal); } /** Return the total number of points that the user has ever spent. @return the total number of points that the user has ever spent. */ function getSpentPoints(address _user) external view returns (uint256) { return userSpentPoints[_user]; } /** Deposit some particular assets to a particular pool on the Staker. @param _token The asset to stake into its corresponding pool. @param _amount The amount of the provided asset to stake. */ function deposit(IERC20 _token, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_token]; require(pool.tokenStrength > 0 || pool.pointStrength > 0, "You cannot deposit assets into an inactive pool."); UserInfo storage user = userInfo[_token][msg.sender]; updatePool(_token); if (user.amount > 0) { uint256 pendingTokens = user.amount.mul(pool.tokensPerShare).div(1e12).sub(user.tokenPaid); token.safeTransferFrom(address(this), msg.sender, pendingTokens); totalTokenDisbursed = totalTokenDisbursed.add(pendingTokens); uint256 pendingPoints = user.amount.mul(pool.pointsPerShare).div(1e30).sub(user.pointPaid); userPoints[msg.sender] = userPoints[msg.sender].add(pendingPoints); } pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); if (address(_token) == address(token)) { totalTokenDeposited = totalTokenDeposited.add(_amount); } user.amount = user.amount.add(_amount); user.tokenPaid = user.amount.mul(pool.tokensPerShare).div(1e12); user.pointPaid = user.amount.mul(pool.pointsPerShare).div(1e30); emit Deposit(msg.sender, _token, _amount); } /** Withdraw some particular assets from a particular pool on the Staker. @param _token The asset to withdraw from its corresponding staking pool. @param _amount The amount of the provided asset to withdraw. */ function withdraw(IERC20 _token, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_token]; UserInfo storage user = userInfo[_token][msg.sender]; require(user.amount >= _amount, "You cannot withdraw that much of the specified token; you are not owed it."); updatePool(_token); uint256 pendingTokens = user.amount.mul(pool.tokensPerShare).div(1e12).sub(user.tokenPaid); token.safeTransferFrom(address(this), msg.sender, pendingTokens); totalTokenDisbursed = totalTokenDisbursed.add(pendingTokens); uint256 pendingPoints = user.amount.mul(pool.pointsPerShare).div(1e30).sub(user.pointPaid); userPoints[msg.sender] = userPoints[msg.sender].add(pendingPoints); if (address(_token) == address(token)) { totalTokenDeposited = totalTokenDeposited.sub(_amount); } user.amount = user.amount.sub(_amount); user.tokenPaid = user.amount.mul(pool.tokensPerShare).div(1e12); user.pointPaid = user.amount.mul(pool.pointsPerShare).div(1e30); pool.token.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _token, _amount); } /** Allows the owner of this Staker to grant or remove approval to an external spender of the points that users accrue from staking resources. @param _spender The external address allowed to spend user points. @param _approval The updated user approval status. */ function approvePointSpender(address _spender, bool _approval) external onlyOwner { approvedPointSpenders[_spender] = _approval; } /** Allows an approved spender of points to spend points on behalf of a user. @param _user The user whose points are being spent. @param _amount The amount of the user's points being spent. */ function spendPoints(address _user, uint256 _amount) external { require(approvedPointSpenders[msg.sender], "You are not permitted to spend user points."); uint256 _userPoints = getAvailablePoints(_user); require(_userPoints >= _amount, "The user does not have enough points to spend the requested amount."); userSpentPoints[_user] = userSpentPoints[_user].add(_amount); emit SpentPoints(msg.sender, _user, _amount); } /** Sweep all of a particular ERC-20 token from the contract. @param _token The token to sweep the balance from. */ function sweep(IERC20 _token) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.safeTransferFrom(address(this), msg.sender, balance); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./Token.sol"; import "./Staker.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Stakers. @author Tim Clancy This is the governing registry of all SuperFarm Staker assets. */ contract FarmStakerRecords is Ownable, ReentrancyGuard { /// A struct used to specify token and pool strengths for adding a pool. struct PoolData { IERC20 poolToken; uint256 tokenStrength; uint256 pointStrength; } /// A version number for this record contract's interface. uint256 public version = 1; /// A mapping for an array of all Stakers deployed by a particular address. mapping (address => address[]) public farmRecords; /// An event for tracking the creation of a new Staker. event FarmCreated(address indexed farmAddress, address indexed creator); /** Create a Staker on behalf of the owner calling this function. The Staker supports immediate specification of the emission schedule and pool strength. @param _name The name of the Staker to create. @param _token The Token to reward stakers in the Staker with. @param _tokenSchedule An array of EmissionPoints defining the token schedule. @param _pointSchedule An array of EmissionPoints defining the point schedule. @param _initialPools An array of pools to initially add to the new Staker. */ function createFarm(string calldata _name, IERC20 _token, Staker.EmissionPoint[] memory _tokenSchedule, Staker.EmissionPoint[] memory _pointSchedule, PoolData[] calldata _initialPools) nonReentrant external returns (Staker) { Staker newStaker = new Staker(_name, _token); // Establish the emissions schedule and add the token pools. newStaker.setEmissions(_tokenSchedule, _pointSchedule); for (uint256 i = 0; i < _initialPools.length; i++) { newStaker.addPool(_initialPools[i].poolToken, _initialPools[i].tokenStrength, _initialPools[i].pointStrength); } // Transfer ownership of the new Staker to the user then store a reference. newStaker.transferOwnership(msg.sender); address stakerAddress = address(newStaker); farmRecords[msg.sender].push(stakerAddress); emit FarmCreated(stakerAddress, msg.sender); return newStaker; } /** Allow a user to add an existing Staker contract to the registry. @param _farmAddress The address of the Staker contract to add for this user. */ function addFarm(address _farmAddress) external { farmRecords[msg.sender].push(_farmAddress); } /** Get the number of entries in the Staker records mapping for the given user. @return The number of Stakers added for a given address. */ function getFarmCount(address _user) external view returns (uint256) { return farmRecords[_user].length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** @title A basic ERC-20 token with voting functionality. @author Tim Clancy This contract is used when deploying SuperFarm ERC-20 tokens. This token is created with a fixed, immutable cap and includes voting rights. Voting functionality is copied and modified from Sushi, and in turn from YAM: https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol Which is in turn copied and modified from COMPOUND: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol */ contract Token is ERC20Capped, Ownable { /// A version number for this Token contract's interface. uint256 public version = 1; /** Construct a new Token by providing it a name, ticker, and supply cap. @param _name The name of the new Token. @param _ticker The ticker symbol of the new Token. @param _cap The supply cap of the new Token. */ constructor (string memory _name, string memory _ticker, uint256 _cap) public ERC20(_name, _ticker) ERC20Capped(_cap) { } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** Allows Token creator to mint `_amount` of this Token to the address `_to`. New tokens of this Token cannot be minted if it would exceed the supply cap. Users are delegated votes when they are minted Token. @param _to the address to mint Tokens to. @param _amount the amount of new Token to mint. */ function mint(address _to, uint256 _amount) external onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** Allows users to transfer tokens to a recipient, moving delegated votes with the transfer. @param recipient The address to transfer tokens to. @param amount The amount of tokens to send to `recipient`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); _moveDelegates(_delegates[msg.sender], _delegates[recipient], amount); return true; } /// @dev A mapping to record delegates for each address. mapping (address => address) internal _delegates; /// A checkpoint structure to mark some number of votes from a given block. struct Checkpoint { uint32 fromBlock; uint256 votes; } /// A mapping to record indexed Checkpoint votes for each address. mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// A mapping to record the number of Checkpoints for each address. mapping (address => uint32) public numCheckpoints; /// The EIP-712 typehash for the contract's domain. bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// 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)"); /// A mapping to record per-address states for signing / validating signatures. mapping (address => uint) public nonces; /// An event emitted when an address changes its delegate. event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// An event emitted when the vote balance of a delegated address changes. event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** Return the address delegated to by `delegator`. @return The address delegated to by `delegator`. */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** Delegate votes from `msg.sender` to `delegatee`. @param delegatee The address to delegate votes to. */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** Delegate votes from signatory to `delegatee`. @param delegatee The address to delegate votes to. @param nonce The contract state required for signature matching. @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) external { 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), "Invalid signature."); require(nonce == nonces[signatory]++, "Invalid nonce."); require(now <= expiry, "Signature expired."); return _delegate(signatory, delegatee); } /** Get the current votes balance for the address `account`. @param account The address to get the votes balance of. @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; } /** Determine the prior number of votes for an address as of a block number. @dev The block number must be a finalized block or else this function will revert to prevent misinformation. @param account The address 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) external view returns (uint256) { require(blockNumber < block.number, "The specified block is not yet finalized."); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check the most recent balance. if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Then check the 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; } /** An internal function to actually perform the delegation of votes. @param delegator The address delegating to `delegatee`. @param delegatee The address receiving delegated votes. */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; /* console.log('a-', currentDelegate, delegator, delegatee); */ emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } /** An internal function to move delegated vote amounts between addresses. @param srcRep the previous representative who received delegated votes. @param dstRep the new representative to receive these delegated votes. @param amount the amount of delegated votes to move between representatives. */ function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { // Decrease the number of votes delegated to the previous representative. if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } // Increase the number of votes delegated to the new representative. 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); } } } /** An internal function to write a checkpoint of modified vote amounts. This function is guaranteed to add at most one checkpoint per block. @param delegatee The address whose vote count is changed. @param nCheckpoints The number of checkpoints by address `delegatee`. @param oldVotes The prior vote count of address `delegatee`. @param newVotes The new vote count of address `delegatee`. */ function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal { uint32 blockNumber = safe32(block.number, "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); } /** A function to safely limit a number to less than 2^32. @param n the number to limit. @param errorMessage the error message to revert with should `n` be too large. @return The number `n` limited to 32 bits. */ function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** A function to return the ID of the contract's particular network or chain. @return The ID of the contract's network or chain. */ function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20Capped is ERC20 { using SafeMath for uint256; uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap_) internal { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= cap(), "ERC20Capped: cap exceeded"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.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 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 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 virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @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: * * - `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 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 virtual { _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 { } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./Token.sol"; /** @title A vault for securely holding tokens. @author Tim Clancy The purpose of this contract is to hold a single type of ERC-20 token securely behind a Compound Timelock governed by a Gnosis MultiSigWallet. Tokens may only leave the vault with multisignature permission and after passing through a mandatory timelock. The justification for the timelock is such that, if the multisignature wallet is ever compromised, the team will have two days to act in mitigating the potential damage from the attacker's `sentTokens` call. Such mitigation efforts may include calling `panic` from a separate, uncompromised and non-timelocked multisignature wallet, or finding some way to issue a new token entirely. */ contract TokenVault is Ownable, ReentrancyGuard { using SafeMath for uint256; /// A version number for this TokenVault contract's interface. uint256 public version = 1; /// A user-specified, descriptive name for this TokenVault. string public name; /// The token to hold safe. Token public token; /** The panic owner is an optional address allowed to immediately send the contents of the vault to the address specified in `panicDestination`. The intention of this system is to support a series of cascading vaults secured by their own multisignature wallets. If, for instance, vault one is compromised via its attached multisignature wallet, vault two could intercede to save the tokens from vault one before the malicious token send clears the owning timelock. */ address public panicOwner; /// An optional address where tokens may be immediately sent by `panicOwner`. address public panicDestination; /** A counter to limit the number of times a vault can panic before burning the underlying supply of tokens. This limit is in place to protect against a situation where multiple vaults linked in a circle are all compromised. In the event of such an attack, this still gives the original multisignature holders the chance to burn the tokens by repeatedly calling `panic` before the attacker can use `sendTokens`. */ uint256 public panicLimit; /// A counter for the number of times this vault has panicked. uint256 public panicCounter; /// A flag to determine whether or not this vault can alter its `panicOwner` and `panicDestination`. bool public canAlterPanicDetails; /// An event for tracking a change in panic details. event PanicDetailsChange(address indexed panicOwner, address indexed panicDestination); /// An event for tracking a lock on alteration of panic details. event PanicDetailsLocked(); /// An event for tracking a disbursement of tokens. event TokenSend(uint256 tokenAmount); /// An event for tracking a panic transfer of tokens. event PanicTransfer(uint256 panicCounter, uint256 tokenAmount, address indexed destination); /// An event for tracking a panic burn of tokens. event PanicBurn(uint256 panicCounter, uint256 tokenAmount); /// @dev a modifier which allows only `panicOwner` to call a function. modifier onlyPanicOwner() { require(panicOwner == _msgSender(), "TokenVault: caller is not the panic owner"); _; } /** Construct a new TokenVault by providing it a name and the token to disburse. @param _name The name of the TokenVault. @param _token The token to store and disburse. @param _panicOwner The address to grant emergency withdrawal powers to. @param _panicDestination The destination to withdraw to in emergency. @param _panicLimit A limit for the number of times `panic` can be called before tokens burn. */ constructor(string memory _name, Token _token, address _panicOwner, address _panicDestination, uint256 _panicLimit) public { name = _name; token = _token; panicOwner = _panicOwner; panicDestination = _panicDestination; panicLimit = _panicLimit; panicCounter = 0; canAlterPanicDetails = true; uint256 MAX_INT = 2**256 - 1; token.approve(address(this), MAX_INT); } /** Allows the owner of the TokenVault to update the `panicOwner` and `panicDestination` details governing its panic functionality. @param _panicOwner The new panic owner to set. @param _panicDestination The new emergency destination to send tokens to. */ function changePanicDetails(address _panicOwner, address _panicDestination) external nonReentrant onlyOwner { require(canAlterPanicDetails, "You cannot change panic details on a vault which is locked."); panicOwner = _panicOwner; panicDestination = _panicDestination; emit PanicDetailsChange(panicOwner, panicDestination); } /** Allows the owner of the TokenVault to lock the vault to all future panic detail changes. */ function lock() external nonReentrant onlyOwner { canAlterPanicDetails = false; emit PanicDetailsLocked(); } /** Allows the TokenVault owner to send tokens out of the vault. @param _recipients The array of addresses to receive tokens. @param _amounts The array of amounts sent to each address in `_recipients`. */ function sendTokens(address[] calldata _recipients, uint256[] calldata _amounts) external nonReentrant onlyOwner { require(_recipients.length > 0, "You must send tokens to at least one recipient."); require(_recipients.length == _amounts.length, "Recipients length cannot be mismatched with amounts length."); // Iterate through every specified recipient and send tokens. uint256 totalAmount = 0; for (uint256 i = 0; i < _recipients.length; i++) { address recipient = _recipients[i]; uint256 amount = _amounts[i]; token.transfer(recipient, amount); totalAmount = totalAmount.add(amount); } emit TokenSend(totalAmount); } /** Allow the TokenVault's `panicOwner` to immediately send its contents to a predefined `panicDestination`. This can be used to circumvent the timelock in case of an emergency. */ function panic() external nonReentrant onlyPanicOwner { uint256 totalBalance = token.balanceOf(address(this)); // If the panic limit is reached, burn the tokens. if (panicCounter == panicLimit) { token.burn(totalBalance); emit PanicBurn(panicCounter, totalBalance); // Otherwise, drain the vault to the panic destination. } else { if (panicDestination == address(0)) { token.burn(totalBalance); emit PanicBurn(panicCounter, totalBalance); } else { token.transfer(panicDestination, totalBalance); emit PanicTransfer(panicCounter, totalBalance, panicDestination); } panicCounter = panicCounter.add(1); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title A token vesting contract for streaming claims. @author SuperFarm This vesting contract allows users to claim vested tokens with every block. */ contract VestStream is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint64; using SafeERC20 for IERC20; /// The token to disburse in vesting. IERC20 public token; // Information for a particular token claim. // - totalAmount: the total size of the token claim. // - startTime: the timestamp in seconds when the vest begins. // - endTime: the timestamp in seconds when the vest completely matures. // - lastCLaimTime: the timestamp in seconds of the last time the claim was utilized. // - amountClaimed: the total amount claimed from the entire claim. struct Claim { uint256 totalAmount; uint64 startTime; uint64 endTime; uint64 lastClaimTime; uint256 amountClaimed; } // A mapping of addresses to the claim received. mapping(address => Claim) private claims; /// An event for tracking the creation of a token vest claim. event ClaimCreated(address creator, address beneficiary); /// An event for tracking a user claiming some of their vested tokens. event Claimed(address beneficiary, uint256 amount); /** Construct a new VestStream by providing it a token to disburse. @param _token The token to vest to claimants in this contract. */ constructor(IERC20 _token) public { token = _token; uint256 MAX_INT = 2**256 - 1; token.approve(address(this), MAX_INT); } /** A function which allows the caller to retrieve information about a specific claim via its beneficiary. @param beneficiary the beneficiary to query claims for. */ function getClaim(address beneficiary) external view returns (Claim memory) { require(beneficiary != address(0), "The zero address may not be a claim beneficiary."); return claims[beneficiary]; } /** A function which allows the caller to retrieve information about a specific claim's remaining claimable amount. @param beneficiary the beneficiary to query claims for. */ function claimableAmount(address beneficiary) public view returns (uint256) { Claim memory claim = claims[beneficiary]; // Early-out if the claim has not started yet. if (claim.startTime == 0 || block.timestamp < claim.startTime) { return 0; } // Calculate the current releasable token amount. uint64 currentTimestamp = uint64(block.timestamp) > claim.endTime ? claim.endTime : uint64(block.timestamp); uint256 claimPercent = currentTimestamp.sub(claim.startTime).mul(1e18).div(claim.endTime.sub(claim.startTime)); uint256 claimAmount = claim.totalAmount.mul(claimPercent).div(1e18); // Reduce the unclaimed amount by the amount already claimed. uint256 unclaimedAmount = claimAmount.sub(claim.amountClaimed); return unclaimedAmount; } /** Sweep all of a particular ERC-20 token from the contract. @param _token The token to sweep the balance from. */ function sweep(IERC20 _token) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.safeTransferFrom(address(this), msg.sender, balance); } /** A function which allows the caller to create toke vesting claims for some beneficiaries. The disbursement token will be taken from the claim creator. @param _beneficiaries an array of addresses to construct token claims for. @param _totalAmounts the total amount of tokens to be disbursed to each beneficiary. @param _startTime a timestamp when this claim is to begin vesting. @param _endTime a timestamp when this claim is to reach full maturity. */ function createClaim(address[] memory _beneficiaries, uint256[] memory _totalAmounts, uint64 _startTime, uint64 _endTime) external onlyOwner { require(_beneficiaries.length > 0, "You must specify at least one beneficiary for a claim."); require(_beneficiaries.length == _totalAmounts.length, "Beneficiaries and their amounts may not be mismatched."); require(_endTime >= _startTime, "You may not create a claim which ends before it starts."); // After validating the details for this token claim, initialize a claim for // each specified beneficiary. for (uint i = 0; i < _beneficiaries.length; i++) { address _beneficiary = _beneficiaries[i]; uint256 _totalAmount = _totalAmounts[i]; require(_beneficiary != address(0), "The zero address may not be a beneficiary."); require(_totalAmount > 0, "You may not create a zero-token claim."); // Establish a claim for this particular beneficiary. Claim memory claim = Claim({ totalAmount: _totalAmount, startTime: _startTime, endTime: _endTime, lastClaimTime: _startTime, amountClaimed: 0 }); claims[_beneficiary] = claim; emit ClaimCreated(msg.sender, _beneficiary); } } /** A function which allows the caller to send a claim's unclaimed amount to the beneficiary of the claim. @param beneficiary the beneficiary to claim for. */ function claim(address beneficiary) external nonReentrant { Claim memory _claim = claims[beneficiary]; // Verify that the claim is still active. require(_claim.lastClaimTime < _claim.endTime, "This claim has already been completely claimed."); // Calculate the current releasable token amount. uint64 currentTimestamp = uint64(block.timestamp) > _claim.endTime ? _claim.endTime : uint64(block.timestamp); uint256 claimPercent = currentTimestamp.sub(_claim.startTime).mul(1e18).div(_claim.endTime.sub(_claim.startTime)); uint256 claimAmount = _claim.totalAmount.mul(claimPercent).div(1e18); // Reduce the unclaimed amount by the amount already claimed. uint256 unclaimedAmount = claimAmount.sub(_claim.amountClaimed); // Transfer the unclaimed tokens to the beneficiary. token.safeTransferFrom(address(this), beneficiary, unclaimedAmount); // Update the amount currently claimed by the user. _claim.amountClaimed = claimAmount; // Update the last time the claim was utilized. _claim.lastClaimTime = currentTimestamp; // Update the claim structure being tracked. claims[beneficiary] = _claim; // Emit an event for this token claim. emit Claimed(beneficiary, unclaimedAmount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title An OpenSea mock proxy contract which we use to test whitelisting. @author OpenSea */ contract MockProxyRegistry is Ownable { using SafeMath for uint256; /// A mapping of testing proxies. mapping(address => address) public proxies; /** Allow the registry owner to set a proxy on behalf of an address. @param _address The address that the proxy will act on behalf of. @param _proxyForAddress The proxy that will act on behalf of the address. */ function setProxy(address _address, address _proxyForAddress) external onlyOwner { proxies[_address] = _proxyForAddress; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; /** @title A simple Shop contract for selling ERC-1155s for Ether via direct minting. @author Tim Clancy This contract is a limited subset of the Shop1155 contract designed to mint items directly to the user upon purchase. */ contract ShopEtherMinter1155 is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 1; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A user-specified Fee1155 contract to support selling items from. Fee1155 public item; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// The Shop's inventory of item groups for sale. uint256[] public inventory; /// The Shop's price for each item group. mapping (uint256 => uint256) public prices; /** Construct a new Shop by providing it a FeeOwner. @param _item The address of the Fee1155 item that will be minting sales. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. */ constructor(Fee1155 _item, FeeOwner _feeOwner) public { item = _item; feeOwner = _feeOwner; } /** Returns the length of the inventory array. @return the length of the inventory array. */ function getInventoryCount() external view returns (uint256) { return inventory.length; } /** Allows the Shop owner to list a new set of NFT items for sale. @param _groupIds The item group IDs to list for sale in this shop. @param _prices The corresponding purchase price to mint an item of each group. */ function listItems(uint256[] calldata _groupIds, uint256[] calldata _prices) external onlyOwner { require(_groupIds.length > 0, "You must list at least one item."); require(_groupIds.length == _prices.length, "Items length cannot be mismatched with prices length."); // Iterate through every specified item group to list items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; uint256 price = _prices[i]; inventory.push(groupId); prices[groupId] = price; } } /** Allows the Shop owner to remove items from sale. @param _groupIds The group IDs currently listed in the shop to take off sale. */ function removeItems(uint256[] calldata _groupIds) external onlyOwner { require(_groupIds.length > 0, "You must remove at least one item."); // Iterate through every specified item group to remove items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; prices[groupId] = 0; } } /** Allows any user to purchase items from this Shop. Users supply specfic item IDs within the groups listed for sale and supply the corresponding amount of Ether to cover the purchase prices. @param _itemIds The specific item IDs to purchase from this shop. */ function purchaseItems(uint256[] calldata _itemIds) public nonReentrant payable { require(_itemIds.length > 0, "You must purchase at least one item."); // Iterate through every specified item to list items. uint256 feePercent = feeOwner.fee(); uint256 itemRoyaltyPercent = item.feeOwner().fee(); for (uint256 i = 0; i < _itemIds.length; i++) { uint256 itemId = _itemIds[i]; uint256 groupId = itemId & GROUP_MASK; uint256 price = prices[groupId]; require(price > 0, "You cannot purchase an item that is not listed."); // Split fees for this purchase. uint256 feeValue = price.mul(feePercent).div(100000); uint256 royaltyValue = price.mul(itemRoyaltyPercent).div(100000); (bool success, ) = payable(feeOwner.owner()).call{ value: feeValue }(""); require(success, "Platform fee transfer failed."); (success, ) = payable(item.feeOwner().owner()).call{ value: royaltyValue }(""); require(success, "Creator royalty transfer failed."); (success, ) = payable(owner()).call{ value: price.sub(feeValue).sub(royaltyValue) }(""); require(success, "Shop owner transfer failed."); // Mint the item. item.mint(msg.sender, itemId, 1, ""); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // TRUFFLE import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract SuperVestCliff { using SafeMath for uint256; using Address for address; address public tokenAddress; event Claimed( address owner, address beneficiary, uint256 amount, uint256 index ); event ClaimCreated(address owner, address beneficiary, uint256 index); struct Claim { address owner; address beneficiary; uint256[] timePeriods; uint256[] tokenAmounts; uint256 totalAmount; uint256 amountClaimed; uint256 periodsClaimed; } Claim[] private claims; mapping(address => uint256[]) private _ownerClaims; mapping(address => uint256[]) private _beneficiaryClaims; constructor(address _tokenAddress) public { tokenAddress = _tokenAddress; } /** * Get Owner Claims * * @param owner - Claim Owner Address */ function ownerClaims(address owner) external view returns (uint256[] memory) { require(owner != address(0), "Owner address cannot be 0"); return _ownerClaims[owner]; } /** * Get Beneficiary Claims * * @param beneficiary - Claim Owner Address */ function beneficiaryClaims(address beneficiary) external view returns (uint256[] memory) { require(beneficiary != address(0), "Beneficiary address cannot be 0"); return _beneficiaryClaims[beneficiary]; } /** * Get Amount Claimed * * @param index - Claim Index */ function claimed(uint256 index) external view returns (uint256) { return claims[index].amountClaimed; } /** * Get Total Claim Amount * * @param index - Claim Index */ function totalAmount(uint256 index) external view returns (uint256) { return claims[index].totalAmount; } /** * Get Time Periods of Claim * * @param index - Claim Index */ function timePeriods(uint256 index) external view returns (uint256[] memory) { return claims[index].timePeriods; } /** * Get Token Amounts of Claim * * @param index - Claim Index */ function tokenAmounts(uint256 index) external view returns (uint256[] memory) { return claims[index].tokenAmounts; } /** * Create a Claim - To Vest Tokens to Beneficiary * * @param _beneficiary - Tokens will be claimed by _beneficiary * @param _timePeriods - uint256 Array of Epochs * @param _tokenAmounts - uin256 Array of Amounts to transfer at each time period */ function createClaim( address _beneficiary, uint256[] memory _timePeriods, uint256[] memory _tokenAmounts ) public returns (bool) { require( _timePeriods.length == _tokenAmounts.length, "_timePeriods & _tokenAmounts length mismatch" ); require(tokenAddress.isContract(), "Invalid tokenAddress"); require(_beneficiary != address(0), "Cannot Vest to address 0"); // Calculate total amount uint256 _totalAmount = 0; for (uint256 i = 0; i < _tokenAmounts.length; i++) { _totalAmount = _totalAmount.add(_tokenAmounts[i]); } require(_totalAmount > 0, "Provide Token Amounts to Vest"); require( ERC20(tokenAddress).allowance(msg.sender, address(this)) >= _totalAmount, "Provide token allowance to SuperVestCliff contract" ); // Transfer Tokens to SuperStreamClaim ERC20(tokenAddress).transferFrom( msg.sender, address(this), _totalAmount ); // Create Claim Claim memory claim = Claim({ owner: msg.sender, beneficiary: _beneficiary, timePeriods: _timePeriods, tokenAmounts: _tokenAmounts, totalAmount: _totalAmount, amountClaimed: 0, periodsClaimed: 0 }); claims.push(claim); uint256 index = claims.length - 1; // Map Claim Index to Owner & Beneficiary _ownerClaims[msg.sender].push(index); _beneficiaryClaims[_beneficiary].push(index); emit ClaimCreated(msg.sender, _beneficiary, index); return true; } /** * Claim Tokens * * @param index - Index of the Claim */ function claim(uint256 index) external { Claim storage claim = claims[index]; // Check if msg.sender is the beneficiary require( claim.beneficiary == msg.sender, "Only beneficiary can claim tokens" ); // Check if anything is left to release require( claim.periodsClaimed < claim.timePeriods.length, "Nothing to release" ); // Calculate releasable amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); claim.periodsClaimed = claim.periodsClaimed.add(1); } else { break; } } // If there is any amount to release require(amount > 0, "Nothing to release"); // Transfer Tokens from Owner to Beneficiary ERC20(tokenAddress).transfer(claim.beneficiary, amount); claim.amountClaimed = claim.amountClaimed.add(amount); emit Claimed(claim.owner, claim.beneficiary, amount, index); } /** * Get Amount of tokens that can be claimed * * @param index - Index of the Claim */ function claimableAmount(uint256 index) public view returns (uint256) { Claim storage claim = claims[index]; // Calculate Claimable Amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); } else { break; } } return amount; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // TRUFFLE import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract SuperNFTVestStream { using SafeMath for uint256; using Address for address; address public tokenAddress; address public nftAddress; event Claimed( address owner, uint256 nftId, address beneficiary, uint256 amount, uint256 index ); event ClaimCreated( address owner, uint256 nftId, uint256 totalAmount, uint256 index ); struct Claim { address owner; uint256 nftId; uint256[] timePeriods; uint256[] tokenAmounts; uint256 totalAmount; uint256 amountClaimed; uint256 periodsClaimed; } Claim[] private claims; struct StreamInfo { uint256 startTime; bool notOverflow; uint256 startDiff; uint256 diff; uint256 amountPerBlock; uint256[] _timePeriods; uint256[] _tokenAmounts; } mapping(address => uint256[]) private _ownerClaims; mapping(uint256 => uint256[]) private _nftClaims; constructor(address _tokenAddress, address _nftAddress) public { require( _tokenAddress.isContract(), "_tokenAddress must be a contract address" ); require( _nftAddress.isContract(), "_nftAddress must be a contract address" ); tokenAddress = _tokenAddress; nftAddress = _nftAddress; } /** * Get Owner Claims * * @param owner - Claim Owner Address */ function ownerClaims(address owner) external view returns (uint256[] memory) { require(owner != address(0), "Owner address cannot be 0"); return _ownerClaims[owner]; } /** * Get NFT Claims * * @param nftId - NFT ID */ function nftClaims(uint256 nftId) external view returns (uint256[] memory) { require(nftId != 0, "nftId cannot be 0"); return _nftClaims[nftId]; } /** * Get Amount Claimed * * @param index - Claim Index */ function claimed(uint256 index) external view returns (uint256) { return claims[index].amountClaimed; } /** * Get Total Claim Amount * * @param index - Claim Index */ function totalAmount(uint256 index) external view returns (uint256) { return claims[index].totalAmount; } /** * Get Time Periods of Claim * * @param index - Claim Index */ function timePeriods(uint256 index) external view returns (uint256[] memory) { return claims[index].timePeriods; } /** * Get Token Amounts of Claim * * @param index - Claim Index */ function tokenAmounts(uint256 index) external view returns (uint256[] memory) { return claims[index].tokenAmounts; } /** * Create a Claim - To Vest Tokens to NFT * * @param _nftId - Tokens will be claimed by owner of _nftId * @param _startBlock - Block Number to start vesting from * @param _stopBlock - Block Number to end vesting at (Release all tokens) * @param _totalAmount - Total Amount to be Vested * @param _blockTime - Block Time (used for predicting _timePeriods) */ function createClaim( uint256 _nftId, uint256 _startBlock, uint256 _stopBlock, uint256 _totalAmount, uint256 _blockTime ) external returns (bool) { require(_nftId != 0, "Cannot Vest to NFT 0"); require( _stopBlock > _startBlock, "_stopBlock must be greater than _startBlock" ); require(tokenAddress.isContract(), "Invalid tokenAddress"); require(_totalAmount > 0, "Provide Token Amounts to Vest"); require( ERC20(tokenAddress).allowance(msg.sender, address(this)) >= _totalAmount, "Provide token allowance to SuperNFTVestStream contract" ); // Calculate estimated epoch for _startBlock StreamInfo memory streamInfo = StreamInfo(0, false, 0, 0, 0, new uint256[](0), new uint256[](0)); (streamInfo.notOverflow, streamInfo.startDiff) = _startBlock.trySub( block.number ); if (streamInfo.notOverflow) { // If Not Overflow streamInfo.startTime = block.timestamp.add( _blockTime.mul(streamInfo.startDiff) ); } else { // If Overflow streamInfo.startDiff = block.number.sub(_startBlock); streamInfo.startTime = block.timestamp.sub( _blockTime.mul(streamInfo.startDiff) ); } // Calculate _timePeriods & _tokenAmounts streamInfo.diff = _stopBlock.sub(_startBlock); streamInfo.amountPerBlock = _totalAmount.div(streamInfo.diff); streamInfo._timePeriods = new uint256[](streamInfo.diff); streamInfo._tokenAmounts = new uint256[](streamInfo.diff); streamInfo._timePeriods[0] = streamInfo.startTime; streamInfo._tokenAmounts[0] = streamInfo.amountPerBlock; for (uint256 i = 1; i < streamInfo.diff; i++) { streamInfo._timePeriods[i] = streamInfo._timePeriods[i - 1].add( _blockTime ); streamInfo._tokenAmounts[i] = streamInfo.amountPerBlock; } // Transfer Tokens to SuperVestStream ERC20(tokenAddress).transferFrom( msg.sender, address(this), _totalAmount ); // Create Claim Claim memory claim = Claim({ owner: msg.sender, nftId: _nftId, timePeriods: streamInfo._timePeriods, tokenAmounts: streamInfo._tokenAmounts, totalAmount: _totalAmount, amountClaimed: 0, periodsClaimed: 0 }); claims.push(claim); uint256 index = claims.length - 1; // Map Claim Index to Owner & Beneficiary _ownerClaims[msg.sender].push(index); _nftClaims[_nftId].push(index); emit ClaimCreated(msg.sender, _nftId, _totalAmount, index); return true; } /** * Claim Tokens * * @param index - Index of the Claim */ function claim(uint256 index) external { Claim storage claim = claims[index]; // Check if msg.sender is the owner of the NFT require( msg.sender == ERC721(nftAddress).ownerOf(claim.nftId), "msg.sender must own the NFT" ); // Check if anything is left to release require( claim.periodsClaimed < claim.timePeriods.length, "Nothing to release" ); // Calculate releasable amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); claim.periodsClaimed = claim.periodsClaimed.add(1); } else { break; } } // If there is any amount to release require(amount > 0, "Nothing to release"); // Transfer Tokens from Owner to Beneficiary ERC20(tokenAddress).transfer(msg.sender, amount); claim.amountClaimed = claim.amountClaimed.add(amount); emit Claimed(claim.owner, claim.nftId, msg.sender, amount, index); } /** * Get Amount of tokens that can be claimed * * @param index - Index of the Claim */ function claimableAmount(uint256 index) public view returns (uint256) { Claim storage claim = claims[index]; // Calculate Claimable Amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); } else { break; } } return amount; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 _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)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @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 || ERC721.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 _tokenOwners.contains(tokenId); } /** * @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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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"); // internal 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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, 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), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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 { } } // 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.2 <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.6.2 <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.6.0 <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.6.0 <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; // 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]; } // 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); } // 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)))); } // 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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // TRUFFLE import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract SuperNFTVestCliff { using SafeMath for uint256; using Address for address; address public tokenAddress; address public nftAddress; event Claimed( address owner, uint256 nftId, address beneficiary, uint256 amount, uint256 index ); event ClaimCreated( address owner, uint256 nftId, uint256 totalAmount, uint256 index ); struct Claim { address owner; uint256 nftId; uint256[] timePeriods; uint256[] tokenAmounts; uint256 totalAmount; uint256 amountClaimed; uint256 periodsClaimed; } Claim[] private claims; mapping(address => uint256[]) private _ownerClaims; mapping(uint256 => uint256[]) private _nftClaims; constructor(address _tokenAddress, address _nftAddress) public { require( _tokenAddress.isContract(), "_tokenAddress must be a contract address" ); require( _nftAddress.isContract(), "_nftAddress must be a contract address" ); tokenAddress = _tokenAddress; nftAddress = _nftAddress; } /** * Get Owner Claims * * @param owner - Claim Owner Address */ function ownerClaims(address owner) external view returns (uint256[] memory) { require(owner != address(0), "Owner address cannot be 0"); return _ownerClaims[owner]; } /** * Get NFT Claims * * @param nftId - NFT ID */ function nftClaims(uint256 nftId) external view returns (uint256[] memory) { require(nftId != 0, "nftId cannot be 0"); return _nftClaims[nftId]; } /** * Get Amount Claimed * * @param index - Claim Index */ function claimed(uint256 index) external view returns (uint256) { return claims[index].amountClaimed; } /** * Get Total Claim Amount * * @param index - Claim Index */ function totalAmount(uint256 index) external view returns (uint256) { return claims[index].totalAmount; } /** * Get Time Periods of Claim * * @param index - Claim Index */ function timePeriods(uint256 index) external view returns (uint256[] memory) { return claims[index].timePeriods; } /** * Get Token Amounts of Claim * * @param index - Claim Index */ function tokenAmounts(uint256 index) external view returns (uint256[] memory) { return claims[index].tokenAmounts; } /** * Create a Claim - To Vest Tokens to NFT * * @param _nftId - Tokens will be claimed by owner of _nftId * @param _timePeriods - uint256 Array of Epochs * @param _tokenAmounts - uin256 Array of Amounts to transfer at each time period */ function createClaim( uint256 _nftId, uint256[] memory _timePeriods, uint256[] memory _tokenAmounts ) public returns (bool) { require(_nftId != 0, "Cannot Vest to NFT 0"); require( _timePeriods.length == _tokenAmounts.length, "_timePeriods & _tokenAmounts length mismatch" ); // Calculate total amount uint256 _totalAmount = 0; for (uint256 i = 0; i < _tokenAmounts.length; i++) { _totalAmount = _totalAmount.add(_tokenAmounts[i]); } require(_totalAmount > 0, "Provide Token Amounts to Vest"); require( ERC20(tokenAddress).allowance(msg.sender, address(this)) >= _totalAmount, "Provide token allowance to SuperStreamClaim contract" ); // Transfer Tokens to SuperStreamClaim ERC20(tokenAddress).transferFrom( msg.sender, address(this), _totalAmount ); // Create Claim Claim memory claim = Claim({ owner: msg.sender, nftId: _nftId, timePeriods: _timePeriods, tokenAmounts: _tokenAmounts, totalAmount: _totalAmount, amountClaimed: 0, periodsClaimed: 0 }); claims.push(claim); uint256 index = claims.length.sub(1); // Map Claim Index to Owner & Beneficiary _ownerClaims[msg.sender].push(index); _nftClaims[_nftId].push(index); emit ClaimCreated(msg.sender, _nftId, _totalAmount, index); return true; } /** * Claim Tokens * * @param index - Index of the Claim */ function claim(uint256 index) external { Claim storage claim = claims[index]; // Check if msg.sender is the owner of the NFT require( msg.sender == ERC721(nftAddress).ownerOf(claim.nftId), "msg.sender must own the NFT" ); // Check if anything is left to release require( claim.periodsClaimed < claim.timePeriods.length, "Nothing to release" ); // Calculate releasable amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); claim.periodsClaimed = claim.periodsClaimed.add(1); } else { break; } } // If there is any amount to release require(amount > 0, "Nothing to release"); // Transfer Tokens from Owner to Beneficiary ERC20(tokenAddress).transfer(msg.sender, amount); claim.amountClaimed = claim.amountClaimed.add(amount); emit Claimed(claim.owner, claim.nftId, msg.sender, amount, index); } /** * Get Amount of tokens that can be claimed * * @param index - Index of the Claim */ function claimableAmount(uint256 index) public view returns (uint256) { Claim storage claim = claims[index]; // Calculate Claimable Amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); } else { break; } } return amount; } } pragma solidity ^0.6.2; // REMIX // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/token/ERC721/ERC721.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/token/ERC20/ERC20.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/utils/Counters.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/utils/EnumerableSet.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/math/SafeMath.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/utils/Address.sol"; // TRUFFLE import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; // SuperNFT SMART CONTRACT contract SuperNFT is ERC721 { using EnumerableSet for EnumerableSet.UintSet; using Counters for Counters.Counter; Counters.Counter private _tokenIds; mapping(string => uint8) hashes; /** * Mint + Issue NFT * * @param recipient - NFT will be issued to recipient * @param hash - Artwork IPFS hash * @param data - Artwork URI/Data */ function issueToken( address recipient, string memory hash, string memory data ) public returns (uint256) { require(hashes[hash] != 1); hashes[hash] = 1; _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _mint(recipient, newTokenId); _setTokenURI(newTokenId, data); return newTokenId; } constructor() public ERC721("SUPER NFT", "SNFT") {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. 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;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; 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 { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; /** @title An OpenSea delegate proxy contract which we include for whitelisting. @author OpenSea */ contract OwnableDelegateProxy { } /** @title An OpenSea proxy registry contract which we include for whitelisting. @author OpenSea */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** @title An ERC-1155 item creation contract which specifies an associated FeeOwner who receives royalties from sales of created items. @author Tim Clancy The fee set by the FeeOwner on this Item is honored by Shop contracts. In addition to the inherited OpenZeppelin dependency, this uses ideas from the original ERC-1155 reference implementation. */ contract Fee1155NFT is ERC1155, Ownable { using SafeMath for uint256; /// A version number for this fee-bearing 1155 item contract's interface. uint256 public version = 1; /// The ERC-1155 URI for looking up item metadata using {id} substitution. string public metadataUri; /// A user-specified FeeOwner to receive a portion of item sale earnings. FeeOwner public feeOwner; /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /// A counter to enforce unique IDs for each item group minted. uint256 public nextItemGroupId; /// This mapping tracks the number of unique items within each item group. mapping (uint256 => uint256) public itemGroupSizes; /// An event for tracking the creation of an item group. event ItemGroupCreated(uint256 itemGroupId, uint256 itemGroupSize, address indexed creator); /** Construct a new ERC-1155 item with an associated FeeOwner fee. @param _uri The metadata URI to perform token ID substitution in. @param _feeOwner The address of a FeeOwner who receives earnings from this item. */ constructor(string memory _uri, FeeOwner _feeOwner, address _proxyRegistryAddress) public ERC1155(_uri) { metadataUri = _uri; feeOwner = _feeOwner; proxyRegistryAddress = _proxyRegistryAddress; nextItemGroupId = 0; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. This function returns true if `_operator` is approved to transfer items owned by `_owner`. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** Allow the item owner to update the metadata URI of this collection. @param _uri The new URI to update to. */ function setURI(string calldata _uri) external onlyOwner { metadataUri = _uri; } /** Create a new NFT item group of a specific size. NFTs within a group share a group ID in the upper 128-bits of their full item ID. Within a group NFTs can be distinguished for the purposes of serializing issue numbers. @param recipient The address to receive all NFTs within the newly-created group. @param groupSize The number of individual NFTs to create within the group. @param data Any associated data to use on items minted in this transaction. */ function createNFT(address recipient, uint256 groupSize, bytes calldata data) external onlyOwner returns (uint256) { require(groupSize > 0, "You cannot create an empty item group."); // Create an item group of requested size using the next available ID. uint256 shiftedGroupId = nextItemGroupId << 128; itemGroupSizes[shiftedGroupId] = groupSize; // Record the supply cap of each item being created in the group. uint256[] memory itemIds = new uint256[](groupSize); uint256[] memory amounts = new uint256[](groupSize); for (uint256 i = 1; i <= groupSize; i++) { itemIds[i - 1] = shiftedGroupId.add(i); amounts[i - 1] = 1; } // Mint the entire batch of items. _mintBatch(recipient, itemIds, amounts, data); // Increment our next item group ID and return our created item group ID. nextItemGroupId = nextItemGroupId.add(1); emit ItemGroupCreated(shiftedGroupId, groupSize, msg.sender); return shiftedGroupId; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; import "./Staker.sol"; /** @title A simple Shop contract for selling ERC-1155s for points, Ether, or ERC-20 tokens. @author Tim Clancy This contract allows its owner to list NFT items for sale. NFT items are purchased by users using points spent on a corresponding Staker contract. The Shop must be approved by the owner of the Staker contract. */ contract Shop1155 is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 1; /// A user-specified, descriptive name for this Shop. string public name; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// A user-specified Staker contract to spend user points on. Staker[] public stakers; /** This struct tracks information about a single asset with associated price that an item is being sold in the shop for. @param assetType A sentinel value for the specific type of asset being used. 0 = non-transferrable points from a Staker; see `asset`. 1 = Ether. 2 = an ERC-20 token, see `asset`. @param asset Some more specific information about the asset to charge in. If the `assetType` is 0, we convert the given address to an integer index for finding a specific Staker from `stakers`. If the `assetType` is 1, we ignore this field. If the `assetType` is 2, we use this address to find the ERC-20 token that we should be specifically charging with. @param price The amount of the specified `assetType` and `asset` to charge. */ struct PricePair { uint256 assetType; address asset; uint256 price; } /** This struct tracks information about each item of inventory in the Shop. @param token The address of a Fee1155 collection contract containing the item we want to sell. @param id The specific ID of the item within the Fee1155 from `token`. @param amount The amount of this specific item on sale in the Shop. */ struct ShopItem { Fee1155 token; uint256 id; uint256 amount; } // The Shop's inventory of items for sale. uint256 nextItemId; mapping (uint256 => ShopItem) public inventory; mapping (uint256 => uint256) public pricePairLengths; mapping (uint256 => mapping (uint256 => PricePair)) public prices; /** Construct a new Shop by providing it a name, FeeOwner, optional Stakers. Any attached Staker contracts must also approve this Shop to spend points. @param _name The name of the Shop contract. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. @param _stakers The addresses of any Stakers to permit spending points from. */ constructor(string memory _name, FeeOwner _feeOwner, Staker[] memory _stakers) public { name = _name; feeOwner = _feeOwner; stakers = _stakers; nextItemId = 0; } /** Returns the length of the Staker array. @return the length of the Staker array. */ function getStakerCount() external view returns (uint256) { return stakers.length; } /** Returns the number of items in the Shop's inventory. @return the number of items in the Shop's inventory. */ function getInventoryCount() external view returns (uint256) { return nextItemId; } /** Allows the Shop owner to add newly-supported Stakers for point spending. @param _stakers The array of new Stakers to add. */ function addStakers(Staker[] memory _stakers) external onlyOwner { for (uint256 i = 0; i < _stakers.length; i++) { stakers.push(_stakers[i]); } } /** Allows the Shop owner to list a new set of NFT items for sale. @param _pricePairs The asset address to price pairings to use for selling each item. @param _items The array of Fee1155 item contracts to sell from. @param _ids The specific Fee1155 item IDs to sell. @param _amounts The amount of inventory being listed for each item. */ function listItems(PricePair[] memory _pricePairs, Fee1155[] calldata _items, uint256[][] calldata _ids, uint256[][] calldata _amounts) external nonReentrant onlyOwner { require(_items.length > 0, "You must list at least one item."); require(_items.length == _ids.length, "Items length cannot be mismatched with IDs length."); require(_items.length == _amounts.length, "Items length cannot be mismatched with amounts length."); // Iterate through every specified Fee1155 contract to list items. for (uint256 i = 0; i < _items.length; i++) { Fee1155 item = _items[i]; uint256[] memory ids = _ids[i]; uint256[] memory amounts = _amounts[i]; require(ids.length > 0, "You must specify at least one item ID."); require(ids.length == amounts.length, "Item IDs length cannot be mismatched with amounts length."); // For each Fee1155 contract, add the requested item IDs to the Shop. for (uint256 j = 0; j < ids.length; j++) { uint256 id = ids[j]; uint256 amount = amounts[j]; require(amount > 0, "You cannot list an item with no starting amount."); inventory[nextItemId + j] = ShopItem({ token: item, id: id, amount: amount }); for (uint k = 0; k < _pricePairs.length; k++) { prices[nextItemId + j][k] = _pricePairs[k]; } pricePairLengths[nextItemId + j] = _pricePairs.length; } nextItemId = nextItemId.add(ids.length); // Batch transfer the listed items to the Shop contract. item.safeBatchTransferFrom(msg.sender, address(this), ids, amounts, ""); } } /** Allows the Shop owner to remove items. @param _itemId The id of the specific inventory item of this shop to remove. @param _amount The amount of the specified item to remove. */ function removeItem(uint256 _itemId, uint256 _amount) external nonReentrant onlyOwner { ShopItem storage item = inventory[_itemId]; require(item.amount >= _amount && item.amount != 0, "There is not enough of your desired item to remove."); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); } /** Allows the Shop owner to adjust the prices of an NFT item set. @param _itemId The id of the specific inventory item of this shop to adjust. @param _pricePairs The asset-price pairs at which to sell a single instance of the item. */ function changeItemPrice(uint256 _itemId, PricePair[] memory _pricePairs) external onlyOwner { for (uint i = 0; i < _pricePairs.length; i++) { prices[_itemId][i] = _pricePairs[i]; } pricePairLengths[_itemId] = _pricePairs.length; } /** Allows any user to purchase an item from this Shop provided they have enough of the asset being used to purchase with. @param _itemId The ID of the specific inventory item of this shop to buy. @param _amount The amount of the specified item to purchase. @param _assetId The index of the asset from the item's asset-price pairs to attempt this purchase using. */ function purchaseItem(uint256 _itemId, uint256 _amount, uint256 _assetId) external nonReentrant payable { ShopItem storage item = inventory[_itemId]; require(item.amount >= _amount && item.amount != 0, "There is not enough of your desired item in stock to purchase."); require(_assetId < pricePairLengths[_itemId], "Your specified asset ID is not valid."); PricePair memory sellingPair = prices[_itemId][_assetId]; // If the sentinel value for the point asset type is found, sell for points. // This involves converting the asset from an address to a Staker index. if (sellingPair.assetType == 0) { uint256 stakerIndex = uint256(sellingPair.asset); stakers[stakerIndex].spendPoints(msg.sender, sellingPair.price.mul(_amount)); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); // If the sentinel value for the Ether asset type is found, sell for Ether. } else if (sellingPair.assetType == 1) { uint256 etherPrice = sellingPair.price.mul(_amount); require(msg.value >= etherPrice, "You did not send enough Ether to complete this purchase."); uint256 feePercent = feeOwner.fee(); uint256 feeValue = msg.value.mul(feePercent).div(100000); uint256 itemRoyaltyPercent = item.token.feeOwner().fee(); uint256 royaltyValue = msg.value.mul(itemRoyaltyPercent).div(100000); (bool success, ) = payable(feeOwner.owner()).call{ value: feeValue }(""); require(success, "Platform fee transfer failed."); (success, ) = payable(item.token.feeOwner().owner()).call{ value: royaltyValue }(""); require(success, "Creator royalty transfer failed."); (success, ) = payable(owner()).call{ value: msg.value.sub(feeValue).sub(royaltyValue) }(""); require(success, "Shop owner transfer failed."); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); // Otherwise, attempt to sell for an ERC20 token. } else { IERC20 sellingAsset = IERC20(sellingPair.asset); uint256 tokenPrice = sellingPair.price.mul(_amount); require(sellingAsset.balanceOf(msg.sender) >= tokenPrice, "You do not have enough token to complete this purchase."); uint256 feePercent = feeOwner.fee(); uint256 feeValue = tokenPrice.mul(feePercent).div(100000); uint256 itemRoyaltyPercent = item.token.feeOwner().fee(); uint256 royaltyValue = tokenPrice.mul(itemRoyaltyPercent).div(100000); sellingAsset.safeTransferFrom(msg.sender, feeOwner.owner(), feeValue); sellingAsset.safeTransferFrom(msg.sender, item.token.feeOwner().owner(), royaltyValue); sellingAsset.safeTransferFrom(msg.sender, owner(), tokenPrice.sub(feeValue).sub(royaltyValue)); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./FeeOwner.sol"; import "./Shop1155.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Shops. @author Tim Clancy This is the governing registry of all SuperFarm Shop assets. */ contract FarmShopRecords is Ownable, ReentrancyGuard { /// A version number for this record contract's interface. uint256 public version = 1; /// The current platform fee owner to force when creating Shops. FeeOwner public platformFeeOwner; /// A mapping for an array of all Shop1155s deployed by a particular address. mapping (address => address[]) public shopRecords; /// An event for tracking the creation of a new Shop. event ShopCreated(address indexed shopAddress, address indexed creator); /** Construct a new registry of SuperFarm records with a specified platform fee owner. @param _feeOwner The address of the FeeOwner due a portion of all Shop earnings. */ constructor(FeeOwner _feeOwner) public { platformFeeOwner = _feeOwner; } /** Allows the registry owner to update the platform FeeOwner to use upon Shop creation. @param _feeOwner The address of the FeeOwner to make the new platform fee owner. */ function changePlatformFeeOwner(FeeOwner _feeOwner) external onlyOwner { platformFeeOwner = _feeOwner; } /** Create a Shop1155 on behalf of the owner calling this function. The Shop supports immediately registering attached Stakers if provided. @param _name The name of the Shop to create. @param _stakers An array of Stakers to attach to the new Shop. */ function createShop(string calldata _name, Staker[] calldata _stakers) external nonReentrant returns (Shop1155) { Shop1155 newShop = new Shop1155(_name, platformFeeOwner, _stakers); // Transfer ownership of the new Shop to the user then store a reference. newShop.transferOwnership(msg.sender); address shopAddress = address(newShop); shopRecords[msg.sender].push(shopAddress); emit ShopCreated(shopAddress, msg.sender); return newShop; } /** Get the number of entries in the Shop records mapping for the given user. @return The number of Shops added for a given address. */ function getShopCount(address _user) external view returns (uint256) { return shopRecords[_user].length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./Token.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Tokens. @author Tim Clancy This is the governing registry of all SuperFarm Token assets. */ contract FarmTokenRecords is Ownable, ReentrancyGuard { /// A version number for this record contract's interface. uint256 public version = 1; /// A mapping for an array of all Tokens deployed by a particular address. mapping (address => address[]) public tokenRecords; /// An event for tracking the creation of a new Token. event TokenCreated(address indexed tokenAddress, address indexed creator); /** Create a Token on behalf of the owner calling this function. The Token supports immediate minting at the time of creation to particular addresses. @param _name The name of the Token to create. @param _ticker The ticker symbol of the Token to create. @param _cap The supply cap of the Token. @param _directMintAddresses An array of addresses to mint directly to. @param _directMintAmounts An array of Token amounts to mint to keyed addresses. */ function createToken(string calldata _name, string calldata _ticker, uint256 _cap, address[] calldata _directMintAddresses, uint256[] calldata _directMintAmounts) external nonReentrant returns (Token) { require(_directMintAddresses.length == _directMintAmounts.length, "Direct mint addresses length cannot be mismatched with mint amounts length."); // Create the token and optionally mint any specified addresses. Token newToken = new Token(_name, _ticker, _cap); for (uint256 i = 0; i < _directMintAddresses.length; i++) { address directMintAddress = _directMintAddresses[i]; uint256 directMintAmount = _directMintAmounts[i]; newToken.mint(directMintAddress, directMintAmount); } // Transfer ownership of the new Token to the user then store a reference. newToken.transferOwnership(msg.sender); address tokenAddress = address(newToken); tokenRecords[msg.sender].push(tokenAddress); emit TokenCreated(tokenAddress, msg.sender); return newToken; } /** Allow a user to add an existing Token contract to the registry. @param _tokenAddress The address of the Token contract to add for this user. */ function addToken(address _tokenAddress) external { tokenRecords[msg.sender].push(_tokenAddress); } /** Get the number of entries in the Token records mapping for the given user. @return The number of Tokens added for a given address. */ function getTokenCount(address _user) external view returns (uint256) { return tokenRecords[_user].length; } } // SPDX-License-Identifier: BSD-3-Clause // Modified from https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return 'Transaction reverted silently'; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; 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, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { return block.timestamp; } }
A version number for this record contract's interface. A mapping for an array of all Tokens deployed by a particular address. An event for tracking the creation of a new Token.*/ Create the token and optionally mint any specified addresses.
function createToken(string calldata _name, string calldata _ticker, uint256 _cap, address[] calldata _directMintAddresses, uint256[] calldata _directMintAmounts) external nonReentrant returns (Token) { require(_directMintAddresses.length == _directMintAmounts.length, "Direct mint addresses length cannot be mismatched with mint amounts length."); Token newToken = new Token(_name, _ticker, _cap); for (uint256 i = 0; i < _directMintAddresses.length; i++) { address directMintAddress = _directMintAddresses[i]; uint256 directMintAmount = _directMintAmounts[i]; newToken.mint(directMintAddress, directMintAmount); } address tokenAddress = address(newToken); tokenRecords[msg.sender].push(tokenAddress); emit TokenCreated(tokenAddress, msg.sender); return newToken; } @param _tokenAddress The address of the Token contract to add for this user.
1,272,632
[ 1, 4625, 348, 7953, 560, 30, 225, 432, 1177, 1300, 364, 333, 1409, 6835, 1807, 1560, 18, 432, 2874, 364, 392, 526, 434, 777, 13899, 19357, 635, 279, 6826, 1758, 18, 1922, 871, 364, 11093, 326, 6710, 434, 279, 394, 3155, 4509, 19, 1788, 326, 1147, 471, 8771, 312, 474, 1281, 1269, 6138, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 752, 1345, 12, 1080, 745, 892, 389, 529, 16, 533, 745, 892, 389, 88, 5448, 16, 2254, 5034, 389, 5909, 16, 1758, 8526, 745, 892, 389, 7205, 49, 474, 7148, 16, 2254, 5034, 8526, 745, 892, 389, 7205, 49, 474, 6275, 87, 13, 3903, 1661, 426, 8230, 970, 1135, 261, 1345, 13, 288, 203, 565, 2583, 24899, 7205, 49, 474, 7148, 18, 2469, 422, 389, 7205, 49, 474, 6275, 87, 18, 2469, 16, 203, 1377, 315, 5368, 312, 474, 6138, 769, 2780, 506, 7524, 11073, 598, 312, 474, 30980, 769, 1199, 1769, 203, 203, 565, 3155, 394, 1345, 273, 394, 3155, 24899, 529, 16, 389, 88, 5448, 16, 389, 5909, 1769, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 7205, 49, 474, 7148, 18, 2469, 31, 277, 27245, 288, 203, 1377, 1758, 2657, 49, 474, 1887, 273, 389, 7205, 49, 474, 7148, 63, 77, 15533, 203, 1377, 2254, 5034, 2657, 49, 474, 6275, 273, 389, 7205, 49, 474, 6275, 87, 63, 77, 15533, 203, 1377, 394, 1345, 18, 81, 474, 12, 7205, 49, 474, 1887, 16, 2657, 49, 474, 6275, 1769, 203, 565, 289, 203, 203, 565, 1758, 1147, 1887, 273, 1758, 12, 2704, 1345, 1769, 203, 565, 1147, 6499, 63, 3576, 18, 15330, 8009, 6206, 12, 2316, 1887, 1769, 203, 565, 3626, 3155, 6119, 12, 2316, 1887, 16, 1234, 18, 15330, 1769, 203, 565, 327, 394, 1345, 31, 203, 225, 289, 203, 203, 203, 565, 632, 891, 389, 2316, 1887, 1021, 1758, 434, 326, 3155, 6835, 358, 527, 364, 333, 729, 18, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { address oraclizeAddr = OAR.getAddress(); if (oraclizeAddr == 0){ oraclize_setNetwork(networkID_auto); oraclizeAddr = OAR.getAddress(); } oraclize = OraclizeI(oraclizeAddr); _ } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _ } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); return true; } if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){ OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd); return true; } if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); return true; } return false; } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } } // </ORACLIZE_API> library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint 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 Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /** * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /** * @dev Returns a slice containing the entire bytes32, interpreted as a * null-termintaed utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /** * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal returns (slice) { return slice(self._len, self._ptr); } /** * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /** * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal returns (uint) { // Starting at ptr-31 means the LSB will be the byte we care about var ptr = self._ptr - 31; var end = ptr + self._len; for (uint len = 0; ptr < end; len++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } return len; } /** * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal returns (bool) { return self._len == 0; } /** * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; var selfptr = self._ptr; var otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); var diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /** * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal returns (bool) { return compare(self, other) == 0; } /** * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint len; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { len = 1; } else if(b < 0xE0) { len = 2; } else if(b < 0xF0) { len = 3; } else { len = 4; } // Check for truncated codepoints if (len > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += len; self._len -= len; rune._len = len; return rune; } /** * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal returns (slice ret) { nextRune(self, ret); } /** * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint len; uint div = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } var b = word / div; if (b < 0x80) { ret = b; len = 1; } else if(b < 0xE0) { ret = b & 0x1F; len = 2; } else if(b < 0xF0) { ret = b & 0x0F; len = 3; } else { ret = b & 0x07; len = 4; } // Check for truncated codepoints if (len > self._len) { return 0; } for (uint i = 1; i < len; i++) { div = div / 256; b = (word / div) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /** * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal returns (bytes32 ret) { assembly { ret := sha3(mload(add(self, 32)), mload(self)) } } /** * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /** * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /** * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } var selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /** * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } var selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 69 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) ptr := add(selfptr, sub(selflen, needlelen)) loop: jumpi(ret, eq(and(mload(ptr), mask), needledata)) ptr := sub(ptr, 1) jumpi(loop, gt(add(ptr, 1), selfptr)) ptr := selfptr jump(exit) ret: ptr := add(ptr, needlelen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /** * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /** * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /** * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /** * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /** * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice self, slice needle, slice token) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /** * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal returns (slice token) { rsplit(self, needle, token); } /** * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint count) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { count++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /** * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /** * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice self, slice other) internal returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /** * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal returns (string) { if (parts.length == 0) return ""; uint len = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) len += parts[i]._len; var ret = new string(len); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() internal{ suicide(owner); } } contract Pray4Prey is mortal, usingOraclize { using strings for *; /**the balances in wei being held by each player */ mapping(address => uint128) winBalances; /**list of all players*/ address[] public players; /** the number of players (may be != players.length, since players can leave the game)*/ uint16 public numPlayers; /** animals[0] -> list of the owners of the animals of type 0, animals[1] animals type 1 etc (using a mapping instead of a multidimensional array for lower gas consumptions) */ mapping(uint8 => address[]) animals; /** the cost of each animal type */ uint128[] public costs; /** the value of each animal type (cost - fee), so it's not necessary to compute it each time*/ uint128[] public values; /** internal array of the probability factors, so it's not necessary to compute it each time*/ uint8[] probabilityFactors; /** the fee to be paid each time an animal is bought in percent*/ uint8[] public fees; /** the indices of the animals per type per player */ // mapping(address => mapping(uint8 => uint16[])) animalIndices; // mapping(address => mapping(uint8 => uint16)) numAnimalsXPlayerXType; /** total number of animals in the game (!=sum of the lengths of the prey animals arrays, since those arrays contain holes) */ uint16 public numAnimals; /** The maximum of animals allowed in the game */ uint16 public maxAnimals; /** number of animals per player */ mapping(address => uint8) numAnimalsXPlayer; /** number of animals per type */ mapping(uint8 => uint16) numAnimalsXType; /** the query string getting the random numbers from oraclize**/ string randomQuery; /** the timestamp of the next attack **/ uint public nextAttackTimestamp; /** gas provided for oraclize callback (attack)**/ uint32 public oraclizeGas; /** the id of the next oraclize callback*/ bytes32 nextAttackId; /** is fired when new animals are purchased (who bought how many animals of which type?) */ event newPurchase(address player, uint8 animalType, uint8 amount); /** is fired when a player leaves the game */ event newExit(address player, uint256 totalBalance); /** is fired when an attack occures*/ event newAttack(); /** expected parameters: the costs per animal type and the game fee in percent * assumes that the cheapest animal is stored in [0] */ function Pray4Prey(uint128[] animalCosts, uint8[] gameFees) { costs = animalCosts; fees = gameFees; for(uint8 i = 0; i< costs.length; i++){ values.push(costs[i]-costs[i]/100*fees[i]); probabilityFactors.push(uint8(costs[costs.length-i-1]/costs[0])); } maxAnimals = 3000; randomQuery = "https://www.random.org/integers/?num=10&min=0&max=10000&col=1&base=10&format=plain&rnd=new"; oraclizeGas=550000; } /** The fallback function runs whenever someone sends ether Depending of the value of the transaction the sender is either granted a prey or the transaction is discarded and no ether accepted In the first case fees have to be paid*/ function (){ for(uint8 i = 0; i < costs.length; i++) if(msg.value==costs[i]) addAnimals(i); if(msg.value==1000000000000000) exit(); else throw; } /** buy animals of a given type * as many animals as possible are bought with msg.value, rest is added to the winBalance of the sender */ function addAnimals(uint8 animalType){ uint8 amount = uint8(msg.value/costs[animalType]); if(animalType >= costs.length || msg.value<costs[animalType] || numAnimalsXPlayer[msg.sender]+amount>50 || numAnimals+amount>=maxAnimals) throw; //if type exists, enough ether was transferred, the player doesn't posess to many animals already (else exit is too costly) and there are less than 10000 animals in the game if(numAnimalsXPlayer[msg.sender]==0)//new player addPlayer(); for(uint8 j = 0; j<amount; j++){ addAnimal(animalType); } numAnimals+=amount; numAnimalsXPlayer[msg.sender]+=amount; //numAnimalsXPlayerXType[msg.sender][animalType]+=amount; winBalances[msg.sender]+=uint128(msg.value*(100-fees[animalType])/100); newPurchase(msg.sender, animalType, j); } /** * adds a single animal of the given type */ function addAnimal(uint8 animalType) internal{ if(numAnimalsXType[animalType]<animals[animalType].length) animals[animalType][numAnimalsXType[animalType]]=msg.sender; else animals[animalType].push(msg.sender); numAnimalsXType[animalType]++; } /** * adds an address to the list of players * before calling you need to check if the address is already in the game * */ function addPlayer() internal{ if(numPlayers<players.length) players[numPlayers]=msg.sender; else players.push(msg.sender); numPlayers++; } /** * removes a given address from the player array * */ function deletePlayer(address playerAddress) internal{ for(uint16 i = 0; i < numPlayers; i++) if(players[i]==playerAddress){ numPlayers--; players[i]=players[numPlayers]; delete players[numPlayers]; return; } } /** leave the game * pays out the sender's winBalance and removes him and his animals from the game * */ function exit(){ cleanUp(msg.sender);//delete the animals newExit(msg.sender, winBalances[msg.sender]); //fire the event to notify the client if(!payout(msg.sender)) throw; delete winBalances[msg.sender]; deletePlayer(msg.sender); } /** * Deletes the animals of a given player * */ function cleanUp(address playerAddress) internal{ for(uint8 animalType = 0; animalType< costs.length; animalType++){//costs.length == num animal types if(numAnimalsXType[animalType]>0){ for(uint16 i = 0; i < numAnimalsXType[animalType]; i++){ if(animals[animalType][i] == playerAddress){ replaceAnimal(animalType,i, true); } } } } numAnimals-=numAnimalsXPlayer[playerAddress]; delete numAnimalsXPlayer[playerAddress]; } /** * Replaces the animal at the given index with the last animal in the array * */ function replaceAnimal(uint8 animalType, uint16 index, bool exit) internal{ if(exit){//delete all animals at the end of the array that belong to the same player while(animals[animalType][numAnimalsXType[animalType]-1]==animals[animalType][index]){ numAnimalsXType[animalType]--; delete animals[animalType][numAnimalsXType[animalType]]; if(numAnimalsXType[animalType]==index) return; } } numAnimalsXType[animalType]--; animals[animalType][index]=animals[animalType][numAnimalsXType[animalType]]; delete animals[animalType][numAnimalsXType[animalType]];//actually there's no need for the delete, since the index will not be accessed since it's higher than numAnimalsXType[animalType] } /** * pays out the given player and removes his fishes. * amount = winbalance + sum(fishvalues) * returns true if payout was successful * */ function payout(address playerAddress) internal returns(bool){ return playerAddress.send(winBalances[playerAddress]); } /** * manually triggers the attack. cannot be called afterwards, except * by the owner if and only if the attack wasn't launched as supposed, signifying * an error ocurred during the last invocation of oraclize, or there wasn't enough ether to pay the gas * */ function triggerAttackManually(uint32 inseconds){ if(!(msg.sender==owner && nextAttackTimestamp < now+300)) throw; triggerAttack(inseconds); } /** * sends a query to oraclize in order to get random numbers in 'inseconds' seconds */ function triggerAttack(uint32 inseconds) internal{ nextAttackTimestamp = now+inseconds; nextAttackId = oraclize_query(nextAttackTimestamp, "URL", randomQuery, oraclizeGas+6000*numPlayers); } /** * The actual predator attack. * The predator kills up to 10 animals, but in case there are less than 100 animals in the game up to 10% get eaten. * */ function __callback(bytes32 myid, string result) { if (msg.sender != oraclize_cbAddress()||myid!=nextAttackId) throw; // just to be sure the calling address is the Oraclize authorized one and the callback is the expected one uint16[] memory ranges = new uint16[](costs.length+1); ranges[0] = 0; for(uint8 animalType = 0; animalType < costs.length; animalType ++){ ranges[animalType+1] = ranges[animalType]+uint16(probabilityFactors[animalType]*numAnimalsXType[animalType]); } uint128 pot; uint16 random; uint16 howmany = numAnimals<100?(numAnimals<10?1:numAnimals/10):10;//do not kill more than 10%, but at least one uint16[] memory randomNumbers = getNumbersFromString(result,"\n", howmany); for(uint8 i = 0; i < howmany; i++){ random = mapToNewRange(randomNumbers[i], ranges[costs.length]); for(animalType = 0; animalType < costs.length; animalType ++) if (random < ranges[animalType+1]){ pot+= killAnimal(animalType, (random-ranges[animalType])/probabilityFactors[animalType]); break; } } numAnimals-=howmany; newAttack(); if(pot>uint128(oraclizeGas*tx.gasprice)) distribute(uint128(pot-oraclizeGas*tx.gasprice));//distribute the pot minus the oraclize gas costs triggerAttack(timeTillNextAttack()); } /** * the frequency of the shark attacks depends on the number of animals in the game. * many animals -> many shark attacks * at least one attack in 24 hours * */ function timeTillNextAttack() constant internal returns(uint32){ return (86400/(1+numAnimals/100)); } /** * kills the animal of the given type at the given index. * */ function killAnimal(uint8 animalType, uint16 index) internal returns(uint128){ address preyOwner = animals[animalType][index]; replaceAnimal(animalType,index,false); numAnimalsXPlayer[preyOwner]--; //numAnimalsXPlayerXType[preyOwner][animalType]--; //if the player still owns prey, the value of the animalType1 alone goes into the pot if(numAnimalsXPlayer[preyOwner]>0){ winBalances[preyOwner]-=values[animalType]; return values[animalType]; } //owner does not have anymore prey, his winBlanace goes into the pot else{ uint128 bounty = winBalances[preyOwner]; delete winBalances[preyOwner]; deletePlayer(preyOwner); return bounty; } } /** distributes the given amount among the players depending on the number of fishes they possess*/ function distribute(uint128 amount) internal{ uint128 share = amount/numAnimals; for(uint16 i = 0; i < numPlayers; i++){ winBalances[players[i]]+=share*numAnimalsXPlayer[players[i]]; } } /** * allows the owner to collect the accumulated fees * sends the given amount to the owner's address if the amount does not exceed the * fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid) * */ function collectFees(uint128 amount){ if(!(msg.sender==owner)) throw; uint collectedFees = getFees(); if(amount + 100 finney < collectedFees){ if(!owner.send(amount)) throw; } } /** * pays out the players and kills the game. * */ function stop(){ if(!(msg.sender==owner)) throw; for(uint16 i = 0; i< numPlayers; i++){ payout(players[i]); } kill(); } /** * adds a new animal type to the game * max. number of animal types: 100 * the cost may not be lower than costs[0] * */ function addAnimalType(uint128 cost, uint8 fee){ if(!(msg.sender==owner)||cost<costs[0]||costs.length>=100) throw; costs.push(cost); fees.push(fee); values.push(cost/100*fee); probabilityFactors.push(uint8(cost/costs[0])); } /****************** GETTERS *************************/ function getWinBalancesOf(address playerAddress) constant returns(uint128){ return winBalances[playerAddress]; } function getAnimals(uint8 animalType) constant returns(address[]){ return animals[animalType]; } function getFees() constant returns(uint){ uint reserved = 0; for(uint16 j = 0; j< numPlayers; j++) reserved+=winBalances[players[j]]; return address(this).balance - reserved; } function getNumAnimalsXType(uint8 animalType) constant returns(uint16){ return numAnimalsXType[animalType]; } function getNumAnimalsXPlayer(address playerAddress) constant returns(uint16){ return numAnimalsXPlayer[playerAddress]; } /* function getNumAnimalsXPlayerXType(address playerAddress, uint8 animalType) constant returns(uint16){ return numAnimalsXPlayerXType[playerAddress][animalType]; } */ /****************** SETTERS *************************/ function setOraclizeGas(uint32 newGas){ if(!(msg.sender==owner)) throw; oraclizeGas = newGas; } function setMaxAnimals(uint16 number){ if(!(msg.sender==owner)) throw; maxAnimals = number; } /************* HELPERS ****************/ /** * maps a given number to the new range (old range 10000) * */ function mapToNewRange(uint number, uint range) constant internal returns (uint16 randomNumber) { return uint16(number*range / 10000); } /** * converts a string of numbers being separated by a given delimiter into an array of numbers (#howmany) */ function getNumbersFromString(string s, string delimiter, uint16 howmany) constant internal returns(uint16[] numbers){ strings.slice memory myresult = s.toSlice(); strings.slice memory delim = delimiter.toSlice(); numbers = new uint16[](howmany); for(uint8 i = 0; i < howmany; i++){ numbers[i]= uint16(parseInt(myresult.split(delim).toString())); } return numbers; } }
* The actual predator attack. The predator kills up to 10 animals, but in case there are less than 100 animals in the game up to 10% get eaten. /
function __callback(bytes32 myid, string result) { uint16[] memory ranges = new uint16[](costs.length+1); ranges[0] = 0; for(uint8 animalType = 0; animalType < costs.length; animalType ++){ ranges[animalType+1] = ranges[animalType]+uint16(probabilityFactors[animalType]*numAnimalsXType[animalType]); } uint128 pot; uint16 random; uint16[] memory randomNumbers = getNumbersFromString(result,"\n", howmany); for(uint8 i = 0; i < howmany; i++){ random = mapToNewRange(randomNumbers[i], ranges[costs.length]); for(animalType = 0; animalType < costs.length; animalType ++) if (random < ranges[animalType+1]){ pot+= killAnimal(animalType, (random-ranges[animalType])/probabilityFactors[animalType]); break; } } numAnimals-=howmany; newAttack(); if(pot>uint128(oraclizeGas*tx.gasprice)) triggerAttack(timeTillNextAttack()); for(uint8 i = 0; i < howmany; i++){ random = mapToNewRange(randomNumbers[i], ranges[costs.length]); for(animalType = 0; animalType < costs.length; animalType ++) if (random < ranges[animalType+1]){ pot+= killAnimal(animalType, (random-ranges[animalType])/probabilityFactors[animalType]); break; } } numAnimals-=howmany; newAttack(); if(pot>uint128(oraclizeGas*tx.gasprice)) triggerAttack(timeTillNextAttack()); }
12,738,241
[ 1, 4625, 348, 7953, 560, 30, 380, 1021, 3214, 3479, 639, 13843, 18, 1021, 3479, 639, 8673, 87, 731, 358, 1728, 10536, 1031, 16, 1496, 316, 648, 1915, 854, 5242, 2353, 2130, 10536, 1031, 316, 326, 7920, 731, 358, 1728, 9, 336, 20729, 275, 18, 342, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1001, 3394, 12, 3890, 1578, 3399, 350, 16, 533, 563, 13, 288, 203, 540, 203, 3639, 2254, 2313, 8526, 3778, 7322, 273, 394, 2254, 2313, 8526, 12, 12398, 87, 18, 2469, 15, 21, 1769, 203, 3639, 7322, 63, 20, 65, 273, 374, 31, 203, 3639, 364, 12, 11890, 28, 392, 2840, 559, 273, 374, 31, 392, 2840, 559, 411, 22793, 18, 2469, 31, 392, 2840, 559, 965, 15329, 203, 5411, 7322, 63, 304, 2840, 559, 15, 21, 65, 273, 7322, 63, 304, 2840, 559, 3737, 11890, 2313, 12, 22390, 23535, 63, 304, 2840, 559, 5772, 2107, 979, 11366, 60, 559, 63, 304, 2840, 559, 19226, 7010, 3639, 289, 1377, 203, 3639, 2254, 10392, 5974, 31, 203, 3639, 2254, 2313, 2744, 31, 540, 203, 3639, 2254, 2313, 8526, 3778, 2744, 10072, 273, 336, 10072, 9193, 12, 2088, 10837, 64, 82, 3113, 3661, 9353, 1769, 203, 3639, 364, 12, 11890, 28, 277, 273, 374, 31, 277, 411, 3661, 9353, 31, 277, 27245, 95, 203, 5411, 2744, 273, 21178, 1908, 2655, 12, 9188, 10072, 63, 77, 6487, 7322, 63, 12398, 87, 18, 2469, 19226, 203, 5411, 364, 12, 304, 2840, 559, 273, 374, 31, 392, 2840, 559, 411, 22793, 18, 2469, 31, 392, 2840, 559, 965, 13, 203, 7734, 309, 261, 9188, 411, 7322, 63, 304, 2840, 559, 15, 21, 5717, 95, 203, 10792, 5974, 15, 33, 8673, 979, 2840, 12, 304, 2840, 559, 16, 261, 9188, 17, 14530, 63, 304, 2840, 559, 5717, 19, 22390, 23535, 63, 304, 2840, 559, 19226, 203, 10792, 898, 31, 203, 7734, 289, 203, 3639, 289, 203, 3639, 818, 979, 11366, 17, 33, 13606, 9353, 31, 203, 3639, 394, 3075, 484, 5621, 203, 3639, 309, 12, 13130, 34, 11890, 10392, 12, 280, 10150, 554, 27998, 14, 978, 18, 31604, 8694, 3719, 203, 3639, 3080, 3075, 484, 12, 957, 56, 737, 2134, 3075, 484, 10663, 203, 3639, 364, 12, 11890, 28, 277, 273, 374, 31, 277, 411, 3661, 9353, 31, 277, 27245, 95, 203, 5411, 2744, 273, 21178, 1908, 2655, 12, 9188, 10072, 63, 77, 6487, 7322, 63, 12398, 87, 18, 2469, 19226, 203, 5411, 364, 12, 304, 2840, 559, 273, 374, 31, 392, 2840, 559, 411, 22793, 18, 2469, 31, 392, 2840, 559, 965, 13, 203, 7734, 309, 261, 9188, 411, 7322, 63, 304, 2840, 559, 15, 21, 5717, 95, 203, 10792, 5974, 15, 33, 8673, 979, 2840, 12, 304, 2840, 559, 16, 261, 9188, 17, 14530, 63, 304, 2840, 559, 5717, 19, 22390, 23535, 63, 304, 2840, 559, 19226, 203, 10792, 898, 31, 203, 7734, 289, 203, 3639, 289, 203, 3639, 818, 979, 11366, 17, 33, 13606, 9353, 31, 203, 3639, 394, 3075, 484, 5621, 203, 3639, 309, 12, 13130, 34, 11890, 10392, 12, 280, 10150, 554, 27998, 14, 978, 18, 31604, 8694, 3719, 203, 3639, 3080, 3075, 484, 12, 957, 56, 737, 2134, 3075, 484, 10663, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 // 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.7.0; pragma experimental ABIEncoderV2; import "./BaseWeightedPool.sol"; /** * @dev Basic Weighted Pool with immutable weights. */ contract WeightedPool is BaseWeightedPool { using FixedPoint for uint256; uint256 private constant _MAX_TOKENS = 20; uint256 private immutable _totalTokens; IERC20 internal immutable _token0; IERC20 internal immutable _token1; IERC20 internal immutable _token2; IERC20 internal immutable _token3; IERC20 internal immutable _token4; IERC20 internal immutable _token5; IERC20 internal immutable _token6; IERC20 internal immutable _token7; IERC20 internal immutable _token8; IERC20 internal immutable _token9; IERC20 internal immutable _token10; IERC20 internal immutable _token11; IERC20 internal immutable _token12; IERC20 internal immutable _token13; IERC20 internal immutable _token14; IERC20 internal immutable _token15; IERC20 internal immutable _token16; IERC20 internal immutable _token17; IERC20 internal immutable _token18; IERC20 internal immutable _token19; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; uint256 internal immutable _scalingFactor2; uint256 internal immutable _scalingFactor3; uint256 internal immutable _scalingFactor4; uint256 internal immutable _scalingFactor5; uint256 internal immutable _scalingFactor6; uint256 internal immutable _scalingFactor7; uint256 internal immutable _scalingFactor8; uint256 internal immutable _scalingFactor9; uint256 internal immutable _scalingFactor10; uint256 internal immutable _scalingFactor11; uint256 internal immutable _scalingFactor12; uint256 internal immutable _scalingFactor13; uint256 internal immutable _scalingFactor14; uint256 internal immutable _scalingFactor15; uint256 internal immutable _scalingFactor16; uint256 internal immutable _scalingFactor17; uint256 internal immutable _scalingFactor18; uint256 internal immutable _scalingFactor19; // The protocol fees will always be charged using the token associated with the max weight in the pool. // Since these Pools will register tokens only once, we can assume this index will be constant. uint256 internal immutable _maxWeightTokenIndex; uint256 internal immutable _normalizedWeight0; uint256 internal immutable _normalizedWeight1; uint256 internal immutable _normalizedWeight2; uint256 internal immutable _normalizedWeight3; uint256 internal immutable _normalizedWeight4; uint256 internal immutable _normalizedWeight5; uint256 internal immutable _normalizedWeight6; uint256 internal immutable _normalizedWeight7; uint256 internal immutable _normalizedWeight8; uint256 internal immutable _normalizedWeight9; uint256 internal immutable _normalizedWeight10; uint256 internal immutable _normalizedWeight11; uint256 internal immutable _normalizedWeight12; uint256 internal immutable _normalizedWeight13; uint256 internal immutable _normalizedWeight14; uint256 internal immutable _normalizedWeight15; uint256 internal immutable _normalizedWeight16; uint256 internal immutable _normalizedWeight17; uint256 internal immutable _normalizedWeight18; uint256 internal immutable _normalizedWeight19; constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory normalizedWeights, address[] memory assetManagers, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BaseWeightedPool( vault, name, symbol, tokens, assetManagers, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { uint256 numTokens = tokens.length; InputHelpers.ensureInputLengthMatch(numTokens, normalizedWeights.length); _totalTokens = numTokens; // Ensure each normalized weight is above them minimum and find the token index of the maximum weight uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= WeightedMath._MIN_WEIGHT, Errors.MIN_WEIGHT); normalizedSum = normalizedSum.add(normalizedWeight); if (normalizedWeight > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeight; } } // Ensure that the normalized weights sum to ONE _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _maxWeightTokenIndex = maxWeightTokenIndex; _normalizedWeight0 = normalizedWeights[0]; _normalizedWeight1 = normalizedWeights[1]; _normalizedWeight2 = numTokens > 2 ? normalizedWeights[2] : 0; _normalizedWeight3 = numTokens > 3 ? normalizedWeights[3] : 0; _normalizedWeight4 = numTokens > 4 ? normalizedWeights[4] : 0; _normalizedWeight5 = numTokens > 5 ? normalizedWeights[5] : 0; _normalizedWeight6 = numTokens > 6 ? normalizedWeights[6] : 0; _normalizedWeight7 = numTokens > 7 ? normalizedWeights[7] : 0; _normalizedWeight8 = numTokens > 8 ? normalizedWeights[8] : 0; _normalizedWeight9 = numTokens > 9 ? normalizedWeights[9] : 0; _normalizedWeight10 = numTokens > 10 ? normalizedWeights[10] : 0; _normalizedWeight11 = numTokens > 11 ? normalizedWeights[11] : 0; _normalizedWeight12 = numTokens > 12 ? normalizedWeights[12] : 0; _normalizedWeight13 = numTokens > 13 ? normalizedWeights[13] : 0; _normalizedWeight14 = numTokens > 14 ? normalizedWeights[14] : 0; _normalizedWeight15 = numTokens > 15 ? normalizedWeights[15] : 0; _normalizedWeight16 = numTokens > 16 ? normalizedWeights[16] : 0; _normalizedWeight17 = numTokens > 17 ? normalizedWeights[17] : 0; _normalizedWeight18 = numTokens > 18 ? normalizedWeights[18] : 0; _normalizedWeight19 = numTokens > 19 ? normalizedWeights[19] : 0; // Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments _token0 = tokens[0]; _token1 = tokens[1]; _token2 = numTokens > 2 ? tokens[2] : IERC20(0); _token3 = numTokens > 3 ? tokens[3] : IERC20(0); _token4 = numTokens > 4 ? tokens[4] : IERC20(0); _token5 = numTokens > 5 ? tokens[5] : IERC20(0); _token6 = numTokens > 6 ? tokens[6] : IERC20(0); _token7 = numTokens > 7 ? tokens[7] : IERC20(0); _token8 = numTokens > 8 ? tokens[8] : IERC20(0); _token9 = numTokens > 9 ? tokens[9] : IERC20(0); _token10 = numTokens > 10 ? tokens[10] : IERC20(0); _token11 = numTokens > 11 ? tokens[11] : IERC20(0); _token12 = numTokens > 12 ? tokens[12] : IERC20(0); _token13 = numTokens > 13 ? tokens[13] : IERC20(0); _token14 = numTokens > 14 ? tokens[14] : IERC20(0); _token15 = numTokens > 15 ? tokens[15] : IERC20(0); _token16 = numTokens > 16 ? tokens[16] : IERC20(0); _token17 = numTokens > 17 ? tokens[17] : IERC20(0); _token18 = numTokens > 18 ? tokens[18] : IERC20(0); _token19 = numTokens > 19 ? tokens[19] : IERC20(0); _scalingFactor0 = _computeScalingFactor(tokens[0]); _scalingFactor1 = _computeScalingFactor(tokens[1]); _scalingFactor2 = numTokens > 2 ? _computeScalingFactor(tokens[2]) : 0; _scalingFactor3 = numTokens > 3 ? _computeScalingFactor(tokens[3]) : 0; _scalingFactor4 = numTokens > 4 ? _computeScalingFactor(tokens[4]) : 0; _scalingFactor5 = numTokens > 5 ? _computeScalingFactor(tokens[5]) : 0; _scalingFactor6 = numTokens > 6 ? _computeScalingFactor(tokens[6]) : 0; _scalingFactor7 = numTokens > 7 ? _computeScalingFactor(tokens[7]) : 0; _scalingFactor8 = numTokens > 8 ? _computeScalingFactor(tokens[8]) : 0; _scalingFactor9 = numTokens > 9 ? _computeScalingFactor(tokens[9]) : 0; _scalingFactor10 = numTokens > 10 ? _computeScalingFactor(tokens[10]) : 0; _scalingFactor11 = numTokens > 11 ? _computeScalingFactor(tokens[11]) : 0; _scalingFactor12 = numTokens > 12 ? _computeScalingFactor(tokens[12]) : 0; _scalingFactor13 = numTokens > 13 ? _computeScalingFactor(tokens[13]) : 0; _scalingFactor14 = numTokens > 14 ? _computeScalingFactor(tokens[14]) : 0; _scalingFactor15 = numTokens > 15 ? _computeScalingFactor(tokens[15]) : 0; _scalingFactor16 = numTokens > 16 ? _computeScalingFactor(tokens[16]) : 0; _scalingFactor17 = numTokens > 17 ? _computeScalingFactor(tokens[17]) : 0; _scalingFactor18 = numTokens > 18 ? _computeScalingFactor(tokens[18]) : 0; _scalingFactor19 = numTokens > 19 ? _computeScalingFactor(tokens[19]) : 0; } function _getNormalizedWeight(IERC20 token) internal view virtual override returns (uint256) { // prettier-ignore if (token == _token0) { return _normalizedWeight0; } else if (token == _token1) { return _normalizedWeight1; } else if (token == _token2) { return _normalizedWeight2; } else if (token == _token3) { return _normalizedWeight3; } else if (token == _token4) { return _normalizedWeight4; } else if (token == _token5) { return _normalizedWeight5; } else if (token == _token6) { return _normalizedWeight6; } else if (token == _token7) { return _normalizedWeight7; } else if (token == _token8) { return _normalizedWeight8; } else if (token == _token9) { return _normalizedWeight9; } else if (token == _token10) { return _normalizedWeight10; } else if (token == _token11) { return _normalizedWeight11; } else if (token == _token12) { return _normalizedWeight12; } else if (token == _token13) { return _normalizedWeight13; } else if (token == _token14) { return _normalizedWeight14; } else if (token == _token15) { return _normalizedWeight15; } else if (token == _token16) { return _normalizedWeight16; } else if (token == _token17) { return _normalizedWeight17; } else if (token == _token18) { return _normalizedWeight18; } else if (token == _token19) { return _normalizedWeight19; } else { _revert(Errors.INVALID_TOKEN); } } function _getNormalizedWeights() internal view virtual override returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory normalizedWeights = new uint256[](totalTokens); // prettier-ignore { normalizedWeights[0] = _normalizedWeight0; normalizedWeights[1] = _normalizedWeight1; if (totalTokens > 2) { normalizedWeights[2] = _normalizedWeight2; } else { return normalizedWeights; } if (totalTokens > 3) { normalizedWeights[3] = _normalizedWeight3; } else { return normalizedWeights; } if (totalTokens > 4) { normalizedWeights[4] = _normalizedWeight4; } else { return normalizedWeights; } if (totalTokens > 5) { normalizedWeights[5] = _normalizedWeight5; } else { return normalizedWeights; } if (totalTokens > 6) { normalizedWeights[6] = _normalizedWeight6; } else { return normalizedWeights; } if (totalTokens > 7) { normalizedWeights[7] = _normalizedWeight7; } else { return normalizedWeights; } if (totalTokens > 8) { normalizedWeights[8] = _normalizedWeight8; } else { return normalizedWeights; } if (totalTokens > 9) { normalizedWeights[9] = _normalizedWeight9; } else { return normalizedWeights; } if (totalTokens > 10) { normalizedWeights[10] = _normalizedWeight10; } else { return normalizedWeights; } if (totalTokens > 11) { normalizedWeights[11] = _normalizedWeight11; } else { return normalizedWeights; } if (totalTokens > 12) { normalizedWeights[12] = _normalizedWeight12; } else { return normalizedWeights; } if (totalTokens > 13) { normalizedWeights[13] = _normalizedWeight13; } else { return normalizedWeights; } if (totalTokens > 14) { normalizedWeights[14] = _normalizedWeight14; } else { return normalizedWeights; } if (totalTokens > 15) { normalizedWeights[15] = _normalizedWeight15; } else { return normalizedWeights; } if (totalTokens > 16) { normalizedWeights[16] = _normalizedWeight16; } else { return normalizedWeights; } if (totalTokens > 17) { normalizedWeights[17] = _normalizedWeight17; } else { return normalizedWeights; } if (totalTokens > 18) { normalizedWeights[18] = _normalizedWeight18; } else { return normalizedWeights; } if (totalTokens > 19) { normalizedWeights[19] = _normalizedWeight19; } else { return normalizedWeights; } } return normalizedWeights; } function _getNormalizedWeightsAndMaxWeightIndex() internal view virtual override returns (uint256[] memory, uint256) { return (_getNormalizedWeights(), _maxWeightTokenIndex); } function _getMaxTokens() internal pure virtual override returns (uint256) { return _MAX_TOKENS; } function _getTotalTokens() internal view virtual override returns (uint256) { return _totalTokens; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. */ function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { // prettier-ignore if (token == _token0) { return _scalingFactor0; } else if (token == _token1) { return _scalingFactor1; } else if (token == _token2) { return _scalingFactor2; } else if (token == _token3) { return _scalingFactor3; } else if (token == _token4) { return _scalingFactor4; } else if (token == _token5) { return _scalingFactor5; } else if (token == _token6) { return _scalingFactor6; } else if (token == _token7) { return _scalingFactor7; } else if (token == _token8) { return _scalingFactor8; } else if (token == _token9) { return _scalingFactor9; } else if (token == _token10) { return _scalingFactor10; } else if (token == _token11) { return _scalingFactor11; } else if (token == _token12) { return _scalingFactor12; } else if (token == _token13) { return _scalingFactor13; } else if (token == _token14) { return _scalingFactor14; } else if (token == _token15) { return _scalingFactor15; } else if (token == _token16) { return _scalingFactor16; } else if (token == _token17) { return _scalingFactor17; } else if (token == _token18) { return _scalingFactor18; } else if (token == _token19) { return _scalingFactor19; } else { _revert(Errors.INVALID_TOKEN); } } function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory scalingFactors = new uint256[](totalTokens); // prettier-ignore { scalingFactors[0] = _scalingFactor0; scalingFactors[1] = _scalingFactor1; if (totalTokens > 2) { scalingFactors[2] = _scalingFactor2; } else { return scalingFactors; } if (totalTokens > 3) { scalingFactors[3] = _scalingFactor3; } else { return scalingFactors; } if (totalTokens > 4) { scalingFactors[4] = _scalingFactor4; } else { return scalingFactors; } if (totalTokens > 5) { scalingFactors[5] = _scalingFactor5; } else { return scalingFactors; } if (totalTokens > 6) { scalingFactors[6] = _scalingFactor6; } else { return scalingFactors; } if (totalTokens > 7) { scalingFactors[7] = _scalingFactor7; } else { return scalingFactors; } if (totalTokens > 8) { scalingFactors[8] = _scalingFactor8; } else { return scalingFactors; } if (totalTokens > 9) { scalingFactors[9] = _scalingFactor9; } else { return scalingFactors; } if (totalTokens > 10) { scalingFactors[10] = _scalingFactor10; } else { return scalingFactors; } if (totalTokens > 11) { scalingFactors[11] = _scalingFactor11; } else { return scalingFactors; } if (totalTokens > 12) { scalingFactors[12] = _scalingFactor12; } else { return scalingFactors; } if (totalTokens > 13) { scalingFactors[13] = _scalingFactor13; } else { return scalingFactors; } if (totalTokens > 14) { scalingFactors[14] = _scalingFactor14; } else { return scalingFactors; } if (totalTokens > 15) { scalingFactors[15] = _scalingFactor15; } else { return scalingFactors; } if (totalTokens > 16) { scalingFactors[16] = _scalingFactor16; } else { return scalingFactors; } if (totalTokens > 17) { scalingFactors[17] = _scalingFactor17; } else { return scalingFactors; } if (totalTokens > 18) { scalingFactors[18] = _scalingFactor18; } else { return scalingFactors; } if (totalTokens > 19) { scalingFactors[19] = _scalingFactor19; } else { return scalingFactors; } } return scalingFactors; } }
Ensure each normalized weight is above them minimum and find the token index of the maximum weight
{ uint256 numTokens = tokens.length; InputHelpers.ensureInputLengthMatch(numTokens, normalizedWeights.length); _totalTokens = numTokens; uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= WeightedMath._MIN_WEIGHT, Errors.MIN_WEIGHT); normalizedSum = normalizedSum.add(normalizedWeight); if (normalizedWeight > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeight; } } _maxWeightTokenIndex = maxWeightTokenIndex; _normalizedWeight0 = normalizedWeights[0]; _normalizedWeight1 = normalizedWeights[1]; _normalizedWeight2 = numTokens > 2 ? normalizedWeights[2] : 0; _normalizedWeight3 = numTokens > 3 ? normalizedWeights[3] : 0; _normalizedWeight4 = numTokens > 4 ? normalizedWeights[4] : 0; _normalizedWeight5 = numTokens > 5 ? normalizedWeights[5] : 0; _normalizedWeight6 = numTokens > 6 ? normalizedWeights[6] : 0; _normalizedWeight7 = numTokens > 7 ? normalizedWeights[7] : 0; _normalizedWeight8 = numTokens > 8 ? normalizedWeights[8] : 0; _normalizedWeight9 = numTokens > 9 ? normalizedWeights[9] : 0; _normalizedWeight10 = numTokens > 10 ? normalizedWeights[10] : 0; _normalizedWeight11 = numTokens > 11 ? normalizedWeights[11] : 0; _normalizedWeight12 = numTokens > 12 ? normalizedWeights[12] : 0; _normalizedWeight13 = numTokens > 13 ? normalizedWeights[13] : 0; _normalizedWeight14 = numTokens > 14 ? normalizedWeights[14] : 0; _normalizedWeight15 = numTokens > 15 ? normalizedWeights[15] : 0; _normalizedWeight16 = numTokens > 16 ? normalizedWeights[16] : 0; _normalizedWeight17 = numTokens > 17 ? normalizedWeights[17] : 0; _normalizedWeight18 = numTokens > 18 ? normalizedWeights[18] : 0; _normalizedWeight19 = numTokens > 19 ? normalizedWeights[19] : 0; _token1 = tokens[1]; _token2 = numTokens > 2 ? tokens[2] : IERC20(0); _token3 = numTokens > 3 ? tokens[3] : IERC20(0); _token4 = numTokens > 4 ? tokens[4] : IERC20(0); _token5 = numTokens > 5 ? tokens[5] : IERC20(0); _token6 = numTokens > 6 ? tokens[6] : IERC20(0); _token7 = numTokens > 7 ? tokens[7] : IERC20(0); _token8 = numTokens > 8 ? tokens[8] : IERC20(0); _token9 = numTokens > 9 ? tokens[9] : IERC20(0); _token10 = numTokens > 10 ? tokens[10] : IERC20(0); _token11 = numTokens > 11 ? tokens[11] : IERC20(0); _token12 = numTokens > 12 ? tokens[12] : IERC20(0); _token13 = numTokens > 13 ? tokens[13] : IERC20(0); _token14 = numTokens > 14 ? tokens[14] : IERC20(0); _token15 = numTokens > 15 ? tokens[15] : IERC20(0); _token16 = numTokens > 16 ? tokens[16] : IERC20(0); _token17 = numTokens > 17 ? tokens[17] : IERC20(0); _token18 = numTokens > 18 ? tokens[18] : IERC20(0); _token19 = numTokens > 19 ? tokens[19] : IERC20(0); _scalingFactor0 = _computeScalingFactor(tokens[0]); _scalingFactor1 = _computeScalingFactor(tokens[1]); _scalingFactor2 = numTokens > 2 ? _computeScalingFactor(tokens[2]) : 0; _scalingFactor3 = numTokens > 3 ? _computeScalingFactor(tokens[3]) : 0; _scalingFactor4 = numTokens > 4 ? _computeScalingFactor(tokens[4]) : 0; _scalingFactor5 = numTokens > 5 ? _computeScalingFactor(tokens[5]) : 0; _scalingFactor6 = numTokens > 6 ? _computeScalingFactor(tokens[6]) : 0; _scalingFactor7 = numTokens > 7 ? _computeScalingFactor(tokens[7]) : 0; _scalingFactor8 = numTokens > 8 ? _computeScalingFactor(tokens[8]) : 0; _scalingFactor9 = numTokens > 9 ? _computeScalingFactor(tokens[9]) : 0; _scalingFactor10 = numTokens > 10 ? _computeScalingFactor(tokens[10]) : 0; _scalingFactor11 = numTokens > 11 ? _computeScalingFactor(tokens[11]) : 0; _scalingFactor12 = numTokens > 12 ? _computeScalingFactor(tokens[12]) : 0; _scalingFactor13 = numTokens > 13 ? _computeScalingFactor(tokens[13]) : 0; _scalingFactor14 = numTokens > 14 ? _computeScalingFactor(tokens[14]) : 0; _scalingFactor15 = numTokens > 15 ? _computeScalingFactor(tokens[15]) : 0; _scalingFactor16 = numTokens > 16 ? _computeScalingFactor(tokens[16]) : 0; _scalingFactor17 = numTokens > 17 ? _computeScalingFactor(tokens[17]) : 0; _scalingFactor18 = numTokens > 18 ? _computeScalingFactor(tokens[18]) : 0; _scalingFactor19 = numTokens > 19 ? _computeScalingFactor(tokens[19]) : 0; }
15,870,290
[ 1, 4625, 348, 7953, 560, 30, 225, 7693, 225, 1517, 5640, 3119, 353, 5721, 2182, 5224, 471, 1104, 326, 1147, 770, 434, 326, 4207, 3119, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 818, 5157, 273, 2430, 18, 2469, 31, 203, 3639, 2741, 13375, 18, 15735, 1210, 1782, 2060, 12, 2107, 5157, 16, 5640, 16595, 18, 2469, 1769, 203, 203, 3639, 389, 4963, 5157, 273, 818, 5157, 31, 203, 203, 3639, 2254, 5034, 5640, 3495, 273, 374, 31, 203, 3639, 2254, 5034, 943, 6544, 1345, 1016, 273, 374, 31, 203, 3639, 2254, 5034, 943, 15577, 6544, 273, 374, 31, 203, 3639, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 818, 5157, 31, 277, 27245, 288, 203, 5411, 2254, 5034, 5640, 6544, 273, 5640, 16595, 63, 77, 15533, 203, 5411, 389, 6528, 12, 17762, 6544, 1545, 15437, 329, 10477, 6315, 6236, 67, 29988, 16, 9372, 18, 6236, 67, 29988, 1769, 203, 203, 5411, 5640, 3495, 273, 5640, 3495, 18, 1289, 12, 17762, 6544, 1769, 203, 5411, 309, 261, 17762, 6544, 405, 943, 15577, 6544, 13, 288, 203, 7734, 943, 6544, 1345, 1016, 273, 277, 31, 203, 7734, 943, 15577, 6544, 273, 5640, 6544, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 389, 1896, 6544, 1345, 1016, 273, 943, 6544, 1345, 1016, 31, 203, 203, 3639, 389, 17762, 6544, 20, 273, 5640, 16595, 63, 20, 15533, 203, 3639, 389, 17762, 6544, 21, 273, 5640, 16595, 63, 21, 15533, 203, 3639, 389, 17762, 6544, 22, 273, 818, 5157, 405, 576, 692, 5640, 16595, 63, 22, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 23, 273, 818, 5157, 405, 890, 692, 5640, 16595, 63, 23, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 24, 273, 818, 5157, 405, 1059, 692, 5640, 16595, 63, 24, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 25, 273, 818, 5157, 405, 1381, 692, 5640, 16595, 63, 25, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 26, 273, 818, 5157, 405, 1666, 692, 5640, 16595, 63, 26, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 27, 273, 818, 5157, 405, 2371, 692, 5640, 16595, 63, 27, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 28, 273, 818, 5157, 405, 1725, 692, 5640, 16595, 63, 28, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 29, 273, 818, 5157, 405, 2468, 692, 5640, 16595, 63, 29, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 2163, 273, 818, 5157, 405, 1728, 692, 5640, 16595, 63, 2163, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 2499, 273, 818, 5157, 405, 4648, 692, 5640, 16595, 63, 2499, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 2138, 273, 818, 5157, 405, 2593, 692, 5640, 16595, 63, 2138, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 3437, 273, 818, 5157, 405, 5958, 692, 5640, 16595, 63, 3437, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 3461, 273, 818, 5157, 405, 5045, 692, 5640, 16595, 63, 3461, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 3600, 273, 818, 5157, 405, 4711, 692, 5640, 16595, 63, 3600, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 2313, 273, 818, 5157, 405, 2872, 692, 5640, 16595, 63, 2313, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 4033, 273, 818, 5157, 405, 8043, 692, 5640, 16595, 63, 4033, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 2643, 273, 818, 5157, 405, 6549, 692, 5640, 16595, 63, 2643, 65, 294, 374, 31, 203, 3639, 389, 17762, 6544, 3657, 273, 818, 5157, 405, 5342, 692, 5640, 16595, 63, 3657, 65, 294, 374, 31, 203, 203, 3639, 389, 2316, 21, 273, 2430, 63, 21, 15533, 203, 3639, 389, 2316, 22, 273, 818, 5157, 405, 576, 692, 2430, 63, 22, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 23, 273, 818, 5157, 405, 890, 692, 2430, 63, 23, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 24, 273, 818, 5157, 405, 1059, 692, 2430, 63, 24, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 25, 273, 818, 5157, 405, 1381, 692, 2430, 63, 25, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 26, 273, 818, 5157, 405, 1666, 692, 2430, 63, 26, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 27, 273, 818, 5157, 405, 2371, 692, 2430, 63, 27, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 28, 273, 818, 5157, 405, 1725, 692, 2430, 63, 28, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 29, 273, 818, 5157, 405, 2468, 692, 2430, 63, 29, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 2163, 273, 818, 5157, 405, 1728, 692, 2430, 63, 2163, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 2499, 273, 818, 5157, 405, 4648, 692, 2430, 63, 2499, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 2138, 273, 818, 5157, 405, 2593, 692, 2430, 63, 2138, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 3437, 273, 818, 5157, 405, 5958, 692, 2430, 63, 3437, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 3461, 273, 818, 5157, 405, 5045, 692, 2430, 63, 3461, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 3600, 273, 818, 5157, 405, 4711, 692, 2430, 63, 3600, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 2313, 273, 818, 5157, 405, 2872, 692, 2430, 63, 2313, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 4033, 273, 818, 5157, 405, 8043, 692, 2430, 63, 4033, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 2643, 273, 818, 5157, 405, 6549, 692, 2430, 63, 2643, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 3639, 389, 2316, 3657, 273, 818, 5157, 405, 5342, 692, 2430, 63, 3657, 65, 294, 467, 654, 39, 3462, 12, 20, 1769, 203, 203, 3639, 389, 24576, 6837, 20, 273, 389, 9200, 8471, 6837, 12, 7860, 63, 20, 19226, 203, 3639, 389, 24576, 6837, 21, 273, 2 ]
pragma solidity ^0.4.19; /// @title Version contract Version { string public semanticVersion; /// @notice Constructor saves a public version of the deployed Contract. /// @param _version Semantic version of the contract. function Version(string _version) internal { semanticVersion = _version; } } /// @title Factory contract Factory is Version { event FactoryAddedContract(address indexed _contract); modifier contractHasntDeployed(address _contract) { require(contracts[_contract] == false); _; } mapping(address => bool) public contracts; function Factory(string _version) internal Version(_version) {} function hasBeenDeployed(address _contract) public constant returns (bool) { return contracts[_contract]; } function addContract(address _contract) internal contractHasntDeployed(_contract) returns (bool) { contracts[_contract] = true; FactoryAddedContract(_contract); return true; } } contract PaymentAddress { event PaymentMade(address indexed _payer, address indexed _collector, uint256 _value); address public collector; bytes4 public identifier; function PaymentAddress(address _collector, bytes4 _identifier) public { collector = _collector; identifier = _identifier; } function () public payable { collector.transfer(msg.value); PaymentMade(msg.sender, collector, msg.value); } } contract PaymentAddressFactory is Factory { // index of created contracts mapping (bytes4 => address) public paymentAddresses; function PaymentAddressFactory() public Factory("1.0.0") {} // deploy a new contract function newPaymentAddress(address _collector, bytes4 _identifier) public returns(address newContract) { require(paymentAddresses[_identifier] == address(0x0)); PaymentAddress paymentAddress = new PaymentAddress(_collector, _identifier); paymentAddresses[_identifier] = paymentAddress; addContract(paymentAddress); return paymentAddress; } }
index of created contracts deploy a new contract
contract PaymentAddressFactory is Factory { mapping (bytes4 => address) public paymentAddresses; function newPaymentAddress(address _collector, bytes4 _identifier) public returns(address newContract) function PaymentAddressFactory() public Factory("1.0.0") {} { require(paymentAddresses[_identifier] == address(0x0)); PaymentAddress paymentAddress = new PaymentAddress(_collector, _identifier); paymentAddresses[_identifier] = paymentAddress; addContract(paymentAddress); return paymentAddress; } }
7,930,165
[ 1, 4625, 348, 7953, 560, 30, 225, 770, 434, 2522, 20092, 7286, 279, 394, 6835, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12022, 1887, 1733, 353, 7822, 288, 203, 565, 2874, 261, 3890, 24, 516, 1758, 13, 1071, 5184, 7148, 31, 203, 203, 203, 565, 445, 394, 6032, 1887, 12, 2867, 389, 21356, 16, 1731, 24, 389, 5644, 13, 203, 3639, 1071, 203, 3639, 1135, 12, 2867, 394, 8924, 13, 203, 565, 445, 12022, 1887, 1733, 1435, 1071, 7822, 2932, 21, 18, 20, 18, 20, 7923, 2618, 203, 565, 288, 203, 3639, 2583, 12, 9261, 7148, 63, 67, 5644, 65, 422, 1758, 12, 20, 92, 20, 10019, 203, 3639, 12022, 1887, 5184, 1887, 273, 394, 12022, 1887, 24899, 21356, 16, 389, 5644, 1769, 203, 3639, 5184, 7148, 63, 67, 5644, 65, 273, 5184, 1887, 31, 203, 3639, 527, 8924, 12, 9261, 1887, 1769, 203, 3639, 327, 5184, 1887, 31, 203, 565, 289, 203, 97, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "./IERC20.sol"; import "./Ownable.sol"; import "./SafeMath.sol"; import "./Address.sol"; interface ISwapAndLiquify{ function inSwapAndLiquify() external returns(bool); function swapAndLiquify(uint256 tokenAmount) external; } contract ALDN is IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; mapping(address => bool) private _isExcludedFromMaxTxAmount; address[] private _excluded; uint256 private constant MAX = type(uint256).max; uint256 private _tTotal = 1000000000 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "MagicLamp Governance Token"; string private _symbol = "ALDN"; uint8 private _decimals = 9; // fee factors uint256 public taxFee = 5; uint256 private _previousTaxFee; uint256 public liquidityFee = 5; uint256 private _previousLiquidityFee; bool public swapAndLiquifyEnabled = true; uint256 public maxTxAmount = 5000000 * 10**6 * 10**9; uint256 private _numTokensSellToAddToLiquidity = 500000 * 10**6 * 10**9; ISwapAndLiquify public swapAndLiquify; // @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); // @notice 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)"); // @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; // @notice A record of each accounts delegate mapping (address => address) public delegates; // @notice A checkpoint for marking number of votes from a given block struct VotesCheckpoint { uint32 fromBlock; uint96 tOwned; uint256 rOwned; } // @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => VotesCheckpoint)) public votesCheckpoints; // @notice The number of votes checkpoints for each account mapping (address => uint32) public numVotesCheckpoints; // @notice A checkpoint for marking rate from a given block struct RateCheckpoint { uint32 fromBlock; uint256 rate; } // @notice A record of rates, by index mapping (uint32 => RateCheckpoint) public rateCheckpoints; // @notice The number of rate checkpoints uint32 public numRateCheckpoints; // @notice An event thats emitted when swap and liquidify address is changed event SwapAndLiquifyAddressChanged(address priviousAddress, address newAddress); // @notice An event thats emitted when swap and liquidify enable is changed event SwapAndLiquifyEnabledChanged(bool enabled); // @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); // @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousROwned, uint previousTOwned, uint newROwned, uint newTOwned); // @notice An event thats emitted when reflection rate changes event RateChanged(uint previousRate, uint newRate); constructor() { _rOwned[_msgSender()] = _rTotal; // excludes _isExcludedFromFee[owner()] = true; _isExcludedFromMaxTxAmount[owner()] = true; _isExcluded[address(this)] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromMaxTxAmount[address(this)] = true; _isExcluded[0x000000000000000000000000000000000000dEaD] = true; emit Transfer(address(0), owner(), _tTotal); } 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 _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); uint256 spenderAllowance = _allowances[sender][_msgSender()]; if (sender != _msgSender() && spenderAllowance != type(uint256).max) { _approve(sender, _msgSender(), spenderAllowance.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 isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function _getOwns(address account) private view returns (uint256, uint256) { uint256 rOwned = _isExcluded[account] ? 0 : _rOwned[account]; uint256 tOwned = _isExcluded[account] ? _tOwned[account] : 0; return (rOwned, tOwned); } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "ALDN::deliver: excluded addresses cannot call this function"); (uint256 oldROwned, uint256 oldTOwned) = _getOwns(sender); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); (uint256 newROwned, uint256 newTOwned) = _getOwns(sender); _moveDelegates(delegates[sender], delegates[sender], oldROwned, oldTOwned, newROwned, newTOwned); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "ALDN::reflectionFromToken: amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function _tokenFromReflection(uint256 rAmount, uint256 rate) private pure returns (uint256) { return rAmount.div(rate); } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require(rAmount <= _rTotal, "ALDN::tokenFromReflection: amount must be less than total reflections"); return _tokenFromReflection(rAmount, _getCurrentRate()); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "ALDN::excludeFromReward: account is already excluded"); (uint256 oldROwned, uint256 oldTOwned) = _getOwns(account); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); (uint256 newROwned, uint256 newTOwned) = _getOwns(account); _moveDelegates(delegates[account], delegates[account], oldROwned, oldTOwned, newROwned, newTOwned); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], "ALDN::includeInReward: account is already included"); (uint256 oldROwned, uint256 oldTOwned) = _getOwns(account); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } (uint256 newROwned, uint256 newTOwned) = _getOwns(account); _moveDelegates(delegates[account], delegates[account], oldROwned, oldTOwned, newROwned, newTOwned); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function excludeFromMaxTxAmount(address account) public onlyOwner { _isExcludedFromMaxTxAmount[account] = true; } function includeInMaxTxAmount(address account) public onlyOwner { _isExcludedFromMaxTxAmount[account] = false; } function setTaxFeePercent(uint256 newFee) external onlyOwner { taxFee = newFee; } function setLiquidityFeePercent(uint256 newFee) external onlyOwner { liquidityFee = newFee; } function setMaxTxPercent(uint256 newPercent) external onlyOwner { maxTxAmount = _tTotal.mul(newPercent).div(10**2); } function setSwapAndLiquifyAddress(address newAddress) public onlyOwner { address priviousAddress = address(swapAndLiquify); require(priviousAddress != newAddress, "ALDN::setSwapAndLiquifyAddress: same address"); _approve(address(this), address(newAddress), type(uint256).max); swapAndLiquify = ISwapAndLiquify(newAddress); emit SwapAndLiquifyAddressChanged(priviousAddress, newAddress); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledChanged(_enabled); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getCurrentRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } /** * @notice Gets the current rate * @return The current rate */ function _getCurrentRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } /** * @notice Gets the rate at a block number * @param blockNumber The block number to get the rate at * @return The rate at the given block */ function _getPriorRate(uint blockNumber) private view returns (uint256) { if (numRateCheckpoints == 0) { return 0; } // First check most recent balance if (rateCheckpoints[numRateCheckpoints - 1].fromBlock <= blockNumber) { return rateCheckpoints[numRateCheckpoints - 1].rate; } // Next check implicit zero balance if (rateCheckpoints[0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = numRateCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow RateCheckpoint memory rcp = rateCheckpoints[center]; if (rcp.fromBlock == blockNumber) { return rcp.rate; } else if (rcp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return rateCheckpoints[lower].rate; } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getCurrentRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(liquidityFee).div(10**2); } function removeAllFee() private { if (taxFee == 0 && liquidityFee == 0) return; _previousTaxFee = taxFee; _previousLiquidityFee = liquidityFee; taxFee = 0; liquidityFee = 0; } function restoreAllFee() private { taxFee = _previousTaxFee; liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function isExcludedFromMaxTxAmount(address account) public view returns (bool) { return _isExcludedFromMaxTxAmount[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ALDN::_approve: approve from the zero address"); require(spender != address(0), "ALDN::_approve: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ALDN::_transfer: transfer from the zero address"); require(to != address(0), "ALDN::_transfer: transfer to the zero address"); require(amount > 0, "ALDN::_transfer: amount must be greater than zero"); require(_isExcludedFromMaxTxAmount[from] || _isExcludedFromMaxTxAmount[to] || amount <= maxTxAmount, "ALDN::_transfer: transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= maxTxAmount) { contractTokenBalance = maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numTokensSellToAddToLiquidity; if (overMinTokenBalance && from != owner() && from != address(swapAndLiquify) && !swapAndLiquify.inSwapAndLiquify() && swapAndLiquifyEnabled) { contractTokenBalance = _numTokensSellToAddToLiquidity; // add liquidity swapAndLiquify.swapAndLiquify(contractTokenBalance); } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from, to, amount, takeFee); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if (sender == recipient) { emit Transfer(sender, recipient, amount); return; } (uint256 oldSenderROwned, uint256 oldSenderTOwned) = _getOwns(sender); (uint256 oldRecipientROwned, uint256 oldRecipientTOwned) = _getOwns(recipient); { if (!takeFee) { removeAllFee(); } bool isExcludedSender = _isExcluded[sender]; bool isExcludedRecipient = _isExcluded[recipient]; if (isExcludedSender && !isExcludedRecipient) { _transferFromExcluded(sender, recipient, amount); } else if (!isExcludedSender && isExcludedRecipient) { _transferToExcluded(sender, recipient, amount); } else if (!isExcludedSender && !isExcludedRecipient) { _transferStandard(sender, recipient, amount); } else if (isExcludedSender && isExcludedRecipient) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) { restoreAllFee(); } } (uint256 newSenderROwned, uint256 newSenderTOwned) = _getOwns(sender); (uint256 newRecipientROwned, uint256 newRecipientTOwned) = _getOwns(recipient); _moveDelegates(delegates[sender], delegates[recipient], oldSenderROwned.sub(newSenderROwned), oldSenderTOwned.sub(newSenderTOwned), newRecipientROwned.sub(oldRecipientROwned), newRecipientTOwned.sub(oldRecipientTOwned)); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function burn(uint256 burnQuantity) external override pure returns (bool) { burnQuantity; return false; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(_msgSender(), delegatee); } /** * @notice 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), "ALDN::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "ALDN::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "ALDN::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the votes balance of `checkpoint` with `rate` * @param rOwned The reflection value to get votes balance * @param tOwned The balance value to get votes balance * @param rate The rate to get votes balance * @return The number of votes with params */ function _getVotes(uint256 rOwned, uint256 tOwned, uint256 rate) private pure returns (uint96) { uint256 votes = 0; votes = votes.add(_tokenFromReflection(rOwned, rate)); votes = votes.add(tOwned); return uint96(votes); } /** * @notice Gets the votes balance of `checkpoint` with `rate` * @param checkpoint The checkpoint to get votes balance * @param rate The rate to get votes balance * @return The number of votes of `checkpoint` with `rate` */ function _getVotes(VotesCheckpoint memory checkpoint, uint256 rate) private pure returns (uint96) { return _getVotes(checkpoint.rOwned, checkpoint.tOwned, rate); } /** * @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 (uint96) { uint32 nCheckpoints = numVotesCheckpoints[account]; return nCheckpoints > 0 ? _getVotes(votesCheckpoints[account][nCheckpoints - 1], _getCurrentRate()) : 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 (uint96) { require(blockNumber < block.number, "ALDN::getPriorVotes: not yet determined"); uint32 nCheckpoints = numVotesCheckpoints[account]; if (nCheckpoints == 0) { return 0; } uint256 rate = _getPriorRate(blockNumber); // First check most recent balance if (votesCheckpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return _getVotes(votesCheckpoints[account][nCheckpoints - 1], rate); } // Next check implicit zero balance if (votesCheckpoints[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 if (votesCheckpoints[account][center].fromBlock == blockNumber) { return _getVotes(votesCheckpoints[account][center], rate); } else if (votesCheckpoints[account][center].fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return _getVotes(votesCheckpoints[account][lower], rate); } function _delegate(address delegator, address delegatee) private { address currentDelegate = delegates[delegator]; (uint256 delegatorROwned, uint256 delegatorTOwned) = _getOwns(delegator); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorROwned, delegatorTOwned, delegatorROwned, delegatorTOwned); } function _moveDelegates(address srcRep, address dstRep, uint256 subROwned, uint256 subTOwned, uint256 addROwned, uint256 addTOwned) private { if (srcRep != dstRep) { if (srcRep != address(0)) { uint32 srcRepNum = numVotesCheckpoints[srcRep]; uint256 srcRepOldR = srcRepNum > 0 ? votesCheckpoints[srcRep][srcRepNum - 1].rOwned : 0; uint256 srcRepOldT = srcRepNum > 0 ? votesCheckpoints[srcRep][srcRepNum - 1].tOwned : 0; uint256 srcRepNewR = srcRepOldR.sub(subROwned); uint256 srcRepNewT = srcRepOldT.sub(subTOwned); if (srcRepOldR != srcRepNewR || srcRepOldT != srcRepNewT) { _writeCheckpoint(srcRep, srcRepNum, srcRepOldR, srcRepOldT, srcRepNewR, srcRepNewT); } } if (dstRep != address(0)) { uint32 dstRepNum = numVotesCheckpoints[dstRep]; uint256 dstRepOldR = dstRepNum > 0 ? votesCheckpoints[dstRep][dstRepNum - 1].rOwned : 0; uint256 dstRepOldT = dstRepNum > 0 ? votesCheckpoints[dstRep][dstRepNum - 1].tOwned : 0; uint256 dstRepNewR = dstRepOldR.add(addROwned); uint256 dstRepNewT = dstRepOldT.add(addTOwned); if (dstRepOldR != dstRepNewR || dstRepOldT != dstRepNewT) { _writeCheckpoint(dstRep, dstRepNum, dstRepOldR, dstRepOldT, dstRepNewR, dstRepNewT); } } } else if (dstRep != address(0)) { uint32 dstRepNum = numVotesCheckpoints[dstRep]; uint256 dstRepOldR = dstRepNum > 0 ? votesCheckpoints[dstRep][dstRepNum - 1].rOwned : 0; uint256 dstRepOldT = dstRepNum > 0 ? votesCheckpoints[dstRep][dstRepNum - 1].tOwned : 0; uint256 dstRepNewR = dstRepOldR.add(addROwned).sub(subROwned); uint256 dstRepNewT = dstRepOldT.add(addTOwned).sub(subTOwned); if (dstRepOldR != dstRepNewR || dstRepOldT != dstRepNewT) { _writeCheckpoint(dstRep, dstRepNum, dstRepOldR, dstRepOldT, dstRepNewR, dstRepNewT); } } uint256 rate = _getCurrentRate(); uint256 rateOld = numRateCheckpoints > 0 ? rateCheckpoints[numRateCheckpoints - 1].rate : 0; if (rate != rateOld) { _writeRateCheckpoint(numRateCheckpoints, rateOld, rate); } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldROwned, uint256 oldTOwned, uint256 newROwned, uint256 newTOwned) private { uint32 blockNumber = safe32(block.number, "ALDN::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && votesCheckpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { votesCheckpoints[delegatee][nCheckpoints - 1].tOwned = uint96(newTOwned); votesCheckpoints[delegatee][nCheckpoints - 1].rOwned = newROwned; } else { votesCheckpoints[delegatee][nCheckpoints] = VotesCheckpoint(blockNumber, uint96(newTOwned), newROwned); numVotesCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldROwned, oldTOwned, newROwned, newTOwned); } function _writeRateCheckpoint(uint32 nCheckpoints, uint256 oldRate, uint256 newRate) private { uint32 blockNumber = safe32(block.number, "ALDN::_writeRateCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && rateCheckpoints[nCheckpoints - 1].fromBlock == blockNumber) { rateCheckpoints[nCheckpoints - 1].rate = newRate; } else { rateCheckpoints[nCheckpoints].fromBlock = blockNumber; rateCheckpoints[nCheckpoints].rate = newRate; numRateCheckpoints = nCheckpoints + 1; } emit RateChanged(oldRate, newRate); } function safe32(uint n, string memory errorMessage) private pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function _getChainId() private view returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // 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 custom add */ function burn(uint256 burnQuantity) 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 "./Context.sol"; // File: @openzeppelin/contracts/access/Ownable.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; address private _authorizedNewOwner; event OwnershipTransferAuthorization(address indexed authorizedAddress); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { 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 Returns the address of the current authorized new owner. */ function authorizedNewOwner() public view virtual returns (address) { return _authorizedNewOwner; } /** * @notice Authorizes the transfer of ownership from _owner to the provided address. * NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ). * This authorization may be removed by another call to this function authorizing * the null address. * * @param authorizedAddress The address authorized to become the new owner. */ function authorizeOwnershipTransfer(address authorizedAddress) external onlyOwner { _authorizedNewOwner = authorizedAddress; emit OwnershipTransferAuthorization(_authorizedNewOwner); } /** * @notice Transfers ownership of this contract to the _authorizedNewOwner. */ function assumeOwnership() external { require(_msgSender() == _authorizedNewOwner, "Ownable: only the authorized new owner can accept ownership"); emit OwnershipTransferred(_owner, _authorizedNewOwner); _owner = _authorizedNewOwner; _authorizedNewOwner = address(0); } /** * @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. * * @param confirmAddress The address wants to give up ownership. */ function renounceOwnership(address confirmAddress) public virtual onlyOwner { require(confirmAddress == _owner, "Ownable: confirm address is wrong"); emit OwnershipTransferred(_owner, address(0)); _authorizedNewOwner = address(0); _owner = address(0); } } // 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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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.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.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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
* @notice 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), "ALDN::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "ALDN::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "ALDN::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
1,414,416
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 24117, 815, 19588, 628, 1573, 8452, 358, 1375, 22216, 73, 68, 632, 891, 7152, 73, 1021, 1758, 358, 7152, 19588, 358, 632, 891, 7448, 1021, 6835, 919, 1931, 358, 845, 326, 3372, 632, 891, 10839, 1021, 813, 622, 1492, 358, 6930, 326, 3372, 632, 891, 331, 1021, 11044, 1160, 434, 326, 3372, 632, 891, 436, 670, 6186, 434, 326, 7773, 19748, 3372, 3082, 632, 891, 272, 670, 6186, 434, 326, 7773, 19748, 3372, 3082, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16, 2254, 10839, 16, 2254, 28, 331, 16, 1731, 1578, 436, 16, 1731, 1578, 272, 13, 1071, 288, 203, 3639, 1731, 1578, 2461, 6581, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 18192, 67, 2399, 15920, 16, 417, 24410, 581, 5034, 12, 3890, 24899, 529, 13, 3631, 389, 588, 3893, 548, 9334, 1758, 12, 2211, 3719, 1769, 203, 3639, 1731, 1578, 1958, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 1639, 19384, 2689, 67, 2399, 15920, 16, 7152, 73, 16, 7448, 16, 10839, 10019, 203, 3639, 1731, 1578, 5403, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 31458, 92, 3657, 64, 92, 1611, 3113, 2461, 6581, 16, 1958, 2310, 10019, 203, 3639, 1758, 1573, 8452, 273, 425, 1793, 3165, 12, 10171, 16, 331, 16, 436, 16, 272, 1769, 203, 3639, 2583, 12, 2977, 8452, 480, 1758, 12, 20, 3631, 315, 1013, 8609, 2866, 22216, 858, 8267, 30, 2057, 3372, 8863, 203, 3639, 2583, 12, 12824, 422, 1661, 764, 63, 2977, 8452, 3737, 15, 16, 315, 1013, 8609, 2866, 22216, 858, 8267, 30, 2057, 7448, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 1648, 10839, 16, 315, 1013, 8609, 2866, 22216, 858, 8267, 30, 3372, 7708, 8863, 203, 3639, 327, 389, 22216, 12, 2977, 8452, 16, 7152, 73, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xBcc008d20736433605c6b61f185d3B605440Eb5f/sources/pool.sol
settle preimum share
uint premiumShare;
5,123,035
[ 1, 4625, 348, 7953, 560, 30, 225, 444, 5929, 675, 2422, 7433, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 23020, 5077, 9535, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.8.4; library BytesUtils { /* * @dev Returns the keccak-256 hash of a byte range. * @param self The byte string to hash. * @param offset The position to start hashing at. * @param len The number of bytes to hash. * @return The hash of the byte range. */ function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) { require(offset + len <= self.length); assembly { ret := keccak256(add(add(self, 32), offset), len) } } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. * @param self The first bytes to compare. * @param other The second bytes to compare. * @return The result of the comparison. */ function compare(bytes memory self, bytes memory other) internal pure returns (int) { return compare(self, 0, self.length, other, 0, other.length); } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first bytes to compare. * @param offset The offset of self. * @param len The length of self. * @param other The second bytes to compare. * @param otheroffset The offset of the other string. * @param otherlen The length of the other string. * @return The result of the comparison. */ function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) { uint shortest = len; if (otherlen < len) shortest = otherlen; uint selfptr; uint otherptr; assembly { selfptr := add(self, add(offset, 32)) otherptr := add(other, add(otheroffset, 32)) } for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask; if (shortest > 32) { mask = type(uint256).max; } else { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } int diff = int(a & mask) - int(b & mask); if (diff != 0) return diff; } selfptr += 32; otherptr += 32; } return int(len) - int(otherlen); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @param len The number of bytes to compare * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) { return keccak(self, offset, len) == keccak(other, otherOffset, len); } /* * @dev Returns true if the two byte ranges are equal with offsets. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) { return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset); } /* * @dev Compares a range of 'self' to all of 'other' and returns True iff * they are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) { return self.length >= offset + other.length && equals(self, offset, other, 0, other.length); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, bytes memory other) internal pure returns(bool) { return self.length == other.length && equals(self, 0, other, 0, self.length); } /* * @dev Returns the 8-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 8 bits of the string, interpreted as an integer. */ function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) { return uint8(self[idx]); } /* * @dev Returns the 16-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 16 bits of the string, interpreted as an integer. */ function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) { require(idx + 2 <= self.length); assembly { ret := and(mload(add(add(self, 2), idx)), 0xFFFF) } } /* * @dev Returns the 32-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bits of the string, interpreted as an integer. */ function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) { require(idx + 4 <= self.length); assembly { ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) { require(idx + 32 <= self.length); assembly { ret := mload(add(add(self, 32), idx)) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) { require(idx + 20 <= self.length); assembly { ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000) } } /* * @dev Returns the n byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes. * @param len The number of bytes. * @return The specified 32 bytes of the string. */ function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) { require(len <= 32); require(idx + len <= self.length); assembly { let mask := not(sub(exp(256, sub(32, len)), 1)) ret := and(mload(add(add(self, 32), idx)), mask) } } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes unchecked { uint 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 Copies a substring into a new byte string. * @param self The byte string to copy from. * @param offset The offset to start copying at. * @param len The number of bytes to copy. */ function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) { require(offset + len <= self.length); bytes memory ret = new bytes(len); uint dest; uint src; assembly { dest := add(ret, 32) src := add(add(self, 32), offset) } memcpy(dest, src, len); return ret; } // Maps characters from 0x30 to 0x7A to their base32 values. // 0xFF represents invalid characters in that range. bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'; /** * @dev Decodes unpadded base32 data of up to one word in length. * @param self The data to decode. * @param off Offset into the string to start at. * @param len Number of characters to decode. * @return The decoded data, left aligned. */ function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) { require(len <= 52); uint ret = 0; uint8 decoded; for(uint i = 0; i < len; i++) { bytes1 char = self[off + i]; require(char >= 0x30 && char <= 0x7A); decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]); require(decoded <= 0x20); if(i == len - 1) { break; } ret = (ret << 5) | decoded; } uint bitlen = len * 5; if(len % 8 == 0) { // Multiple of 8 characters, no padding ret = (ret << 5) | decoded; } else if(len % 8 == 2) { // Two extra characters - 1 byte ret = (ret << 3) | (decoded >> 2); bitlen -= 2; } else if(len % 8 == 4) { // Four extra characters - 2 bytes ret = (ret << 1) | (decoded >> 4); bitlen -= 4; } else if(len % 8 == 5) { // Five extra characters - 3 bytes ret = (ret << 4) | (decoded >> 1); bitlen -= 1; } else if(len % 8 == 7) { // Seven extra characters - 4 bytes ret = (ret << 2) | (decoded >> 3); bitlen -= 3; } else { revert(); } return bytes32(ret << (256 - bitlen)); } } pragma solidity ^0.8.4; /** * @dev An interface for contracts implementing a DNSSEC (signing) algorithm. */ interface Algorithm { /** * @dev Verifies a signature. * @param key The public key to verify with. * @param data The signed data to verify. * @param signature The signature to verify. * @return True iff the signature is valid. */ function verify(bytes calldata key, bytes calldata data, bytes calldata signature) external virtual view returns (bool); } pragma solidity ^0.8.4; /** * @title EllipticCurve * * @author Tilman Drerup; * * @notice Implements elliptic curve math; Parametrized for SECP256R1. * * Includes components of code by Andreas Olofsson, Alexander Vlasov * (https://github.com/BANKEX/CurveArithmetics), and Avi Asayag * (https://github.com/orbs-network/elliptic-curve-solidity) * * Source: https://github.com/tdrerup/elliptic-curve-solidity * * @dev NOTE: To disambiguate public keys when verifying signatures, activate * condition 'rs[1] > lowSmax' in validateSignature(). */ contract EllipticCurve { // Set parameters for curve. uint constant a = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC; uint constant b = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B; uint constant gx = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296; uint constant gy = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5; uint constant p = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF; uint constant n = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551; uint constant lowSmax = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0; /** * @dev Inverse of u in the field of modulo m. */ function inverseMod(uint u, uint m) internal pure returns (uint) { unchecked { if (u == 0 || u == m || m == 0) return 0; if (u > m) u = u % m; int t1; int t2 = 1; uint r1 = m; uint r2 = u; uint q; while (r2 != 0) { q = r1 / r2; (t1, t2, r1, r2) = (t2, t1 - int(q) * t2, r2, r1 - q * r2); } if (t1 < 0) return (m - uint(-t1)); return uint(t1); } } /** * @dev Transform affine coordinates into projective coordinates. */ function toProjectivePoint(uint x0, uint y0) internal pure returns (uint[3] memory P) { P[2] = addmod(0, 1, p); P[0] = mulmod(x0, P[2], p); P[1] = mulmod(y0, P[2], p); } /** * @dev Add two points in affine coordinates and return projective point. */ function addAndReturnProjectivePoint(uint x1, uint y1, uint x2, uint y2) internal pure returns (uint[3] memory P) { uint x; uint y; (x, y) = add(x1, y1, x2, y2); P = toProjectivePoint(x, y); } /** * @dev Transform from projective to affine coordinates. */ function toAffinePoint(uint x0, uint y0, uint z0) internal pure returns (uint x1, uint y1) { uint z0Inv; z0Inv = inverseMod(z0, p); x1 = mulmod(x0, z0Inv, p); y1 = mulmod(y0, z0Inv, p); } /** * @dev Return the zero curve in projective coordinates. */ function zeroProj() internal pure returns (uint x, uint y, uint z) { return (0, 1, 0); } /** * @dev Return the zero curve in affine coordinates. */ function zeroAffine() internal pure returns (uint x, uint y) { return (0, 0); } /** * @dev Check if the curve is the zero curve. */ function isZeroCurve(uint x0, uint y0) internal pure returns (bool isZero) { if(x0 == 0 && y0 == 0) { return true; } return false; } /** * @dev Check if a point in affine coordinates is on the curve. */ function isOnCurve(uint x, uint y) internal pure returns (bool) { if (0 == x || x == p || 0 == y || y == p) { return false; } uint LHS = mulmod(y, y, p); // y^2 uint RHS = mulmod(mulmod(x, x, p), x, p); // x^3 if (a != 0) { RHS = addmod(RHS, mulmod(x, a, p), p); // x^3 + a*x } if (b != 0) { RHS = addmod(RHS, b, p); // x^3 + a*x + b } return LHS == RHS; } /** * @dev Double an elliptic curve point in projective coordinates. See * https://www.nayuki.io/page/elliptic-curve-point-addition-in-projective-coordinates */ function twiceProj(uint x0, uint y0, uint z0) internal pure returns (uint x1, uint y1, uint z1) { uint t; uint u; uint v; uint w; if(isZeroCurve(x0, y0)) { return zeroProj(); } u = mulmod(y0, z0, p); u = mulmod(u, 2, p); v = mulmod(u, x0, p); v = mulmod(v, y0, p); v = mulmod(v, 2, p); x0 = mulmod(x0, x0, p); t = mulmod(x0, 3, p); z0 = mulmod(z0, z0, p); z0 = mulmod(z0, a, p); t = addmod(t, z0, p); w = mulmod(t, t, p); x0 = mulmod(2, v, p); w = addmod(w, p-x0, p); x0 = addmod(v, p-w, p); x0 = mulmod(t, x0, p); y0 = mulmod(y0, u, p); y0 = mulmod(y0, y0, p); y0 = mulmod(2, y0, p); y1 = addmod(x0, p-y0, p); x1 = mulmod(u, w, p); z1 = mulmod(u, u, p); z1 = mulmod(z1, u, p); } /** * @dev Add two elliptic curve points in projective coordinates. See * https://www.nayuki.io/page/elliptic-curve-point-addition-in-projective-coordinates */ function addProj(uint x0, uint y0, uint z0, uint x1, uint y1, uint z1) internal pure returns (uint x2, uint y2, uint z2) { uint t0; uint t1; uint u0; uint u1; if (isZeroCurve(x0, y0)) { return (x1, y1, z1); } else if (isZeroCurve(x1, y1)) { return (x0, y0, z0); } t0 = mulmod(y0, z1, p); t1 = mulmod(y1, z0, p); u0 = mulmod(x0, z1, p); u1 = mulmod(x1, z0, p); if (u0 == u1) { if (t0 == t1) { return twiceProj(x0, y0, z0); } else { return zeroProj(); } } (x2, y2, z2) = addProj2(mulmod(z0, z1, p), u0, u1, t1, t0); } /** * @dev Helper function that splits addProj to avoid too many local variables. */ function addProj2(uint v, uint u0, uint u1, uint t1, uint t0) private pure returns (uint x2, uint y2, uint z2) { uint u; uint u2; uint u3; uint w; uint t; t = addmod(t0, p-t1, p); u = addmod(u0, p-u1, p); u2 = mulmod(u, u, p); w = mulmod(t, t, p); w = mulmod(w, v, p); u1 = addmod(u1, u0, p); u1 = mulmod(u1, u2, p); w = addmod(w, p-u1, p); x2 = mulmod(u, w, p); u3 = mulmod(u2, u, p); u0 = mulmod(u0, u2, p); u0 = addmod(u0, p-w, p); t = mulmod(t, u0, p); t0 = mulmod(t0, u3, p); y2 = addmod(t, p-t0, p); z2 = mulmod(u3, v, p); } /** * @dev Add two elliptic curve points in affine coordinates. */ function add(uint x0, uint y0, uint x1, uint y1) internal pure returns (uint, uint) { uint z0; (x0, y0, z0) = addProj(x0, y0, 1, x1, y1, 1); return toAffinePoint(x0, y0, z0); } /** * @dev Double an elliptic curve point in affine coordinates. */ function twice(uint x0, uint y0) internal pure returns (uint, uint) { uint z0; (x0, y0, z0) = twiceProj(x0, y0, 1); return toAffinePoint(x0, y0, z0); } /** * @dev Multiply an elliptic curve point by a 2 power base (i.e., (2^exp)*P)). */ function multiplyPowerBase2(uint x0, uint y0, uint exp) internal pure returns (uint, uint) { uint base2X = x0; uint base2Y = y0; uint base2Z = 1; for(uint i = 0; i < exp; i++) { (base2X, base2Y, base2Z) = twiceProj(base2X, base2Y, base2Z); } return toAffinePoint(base2X, base2Y, base2Z); } /** * @dev Multiply an elliptic curve point by a scalar. */ function multiplyScalar(uint x0, uint y0, uint scalar) internal pure returns (uint x1, uint y1) { if(scalar == 0) { return zeroAffine(); } else if (scalar == 1) { return (x0, y0); } else if (scalar == 2) { return twice(x0, y0); } uint base2X = x0; uint base2Y = y0; uint base2Z = 1; uint z1 = 1; x1 = x0; y1 = y0; if(scalar%2 == 0) { x1 = y1 = 0; } scalar = scalar >> 1; while(scalar > 0) { (base2X, base2Y, base2Z) = twiceProj(base2X, base2Y, base2Z); if(scalar%2 == 1) { (x1, y1, z1) = addProj(base2X, base2Y, base2Z, x1, y1, z1); } scalar = scalar >> 1; } return toAffinePoint(x1, y1, z1); } /** * @dev Multiply the curve's generator point by a scalar. */ function multipleGeneratorByScalar(uint scalar) internal pure returns (uint, uint) { return multiplyScalar(gx, gy, scalar); } /** * @dev Validate combination of message, signature, and public key. */ function validateSignature(bytes32 message, uint[2] memory rs, uint[2] memory Q) internal pure returns (bool) { // To disambiguate between public key solutions, include comment below. if(rs[0] == 0 || rs[0] >= n || rs[1] == 0) {// || rs[1] > lowSmax) return false; } if (!isOnCurve(Q[0], Q[1])) { return false; } uint x1; uint x2; uint y1; uint y2; uint sInv = inverseMod(rs[1], n); (x1, y1) = multiplyScalar(gx, gy, mulmod(uint(message), sInv, n)); (x2, y2) = multiplyScalar(Q[0], Q[1], mulmod(rs[0], sInv, n)); uint[3] memory P = addAndReturnProjectivePoint(x1, y1, x2, y2); if (P[2] == 0) { return false; } uint Px = inverseMod(P[2], p); Px = mulmod(P[0], mulmod(Px, Px, p), p); return Px % n == rs[0]; } } pragma solidity ^0.8.4; import "./Algorithm.sol"; import "./EllipticCurve.sol"; import "../BytesUtils.sol"; contract P256SHA256Algorithm is Algorithm, EllipticCurve { using BytesUtils for *; /** * @dev Verifies a signature. * @param key The public key to verify with. * @param data The signed data to verify. * @param signature The signature to verify. * @return True iff the signature is valid. */ function verify(bytes calldata key, bytes calldata data, bytes calldata signature) external override view returns (bool) { return validateSignature(sha256(data), parseSignature(signature), parseKey(key)); } function parseSignature(bytes memory data) internal pure returns (uint256[2] memory) { require(data.length == 64, "Invalid p256 signature length"); return [uint256(data.readBytes32(0)), uint256(data.readBytes32(32))]; } function parseKey(bytes memory data) internal pure returns (uint256[2] memory) { require(data.length == 68, "Invalid p256 key length"); return [uint256(data.readBytes32(4)), uint256(data.readBytes32(36))]; } }
* @dev Check if a point in affine coordinates is on the curve./
function isOnCurve(uint x, uint y) internal pure returns (bool) { if (0 == x || x == p || 0 == y || y == p) { return false; } if (a != 0) { } if (b != 0) { } return LHS == RHS; }
10,120,968
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 2073, 309, 279, 1634, 316, 28381, 5513, 353, 603, 326, 8882, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 28181, 9423, 12, 11890, 619, 16, 2254, 677, 13, 2713, 16618, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 309, 261, 20, 422, 619, 747, 619, 422, 293, 747, 374, 422, 677, 747, 677, 422, 293, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 203, 3639, 309, 261, 69, 480, 374, 13, 288, 203, 3639, 289, 203, 3639, 309, 261, 70, 480, 374, 13, 288, 203, 3639, 289, 203, 203, 3639, 327, 511, 13173, 422, 534, 13173, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xE32A88aAc056507F2E40a261ACd99742c377B6b3/sources/contracts/PriceDiscovery.sol
@notice Planned initial total supply of the sYSL token.
uint public initialTotalSupply;
12,470,905
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 3008, 10041, 2172, 2078, 14467, 434, 326, 272, 61, 4559, 1147, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2172, 5269, 3088, 1283, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xcC128DE52b8E4068Ba176B6391B38682C6180707/sources/browser/sovi/PioneerOreFlattened.sol
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 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); token.mint(devaddr, tokenReward.div(10)); token.mint(address(this), tokenReward); pool.accTokenPerShare = pool.accTokenPerShare.add(tokenReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
4,878,526
[ 1, 4625, 348, 7953, 560, 30, 225, 2315, 19890, 3152, 434, 326, 864, 2845, 358, 506, 731, 17, 869, 17, 712, 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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 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 9953, 3088, 1283, 422, 374, 13, 288, 203, 5411, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 3639, 2254, 5034, 1147, 17631, 1060, 273, 15027, 18, 16411, 12, 266, 2913, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 3639, 1147, 18, 81, 474, 12, 5206, 4793, 16, 1147, 17631, 1060, 18, 2892, 12, 2163, 10019, 203, 3639, 1147, 18, 81, 474, 12, 2867, 12, 2211, 3631, 1147, 17631, 1060, 1769, 203, 3639, 2845, 18, 8981, 1345, 2173, 9535, 273, 2845, 18, 8981, 1345, 2173, 9535, 18, 1289, 12, 2316, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 10019, 203, 3639, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* @AUTHOR - Raj Jha & Harish Jaggi */ pragma solidity ^0.5.1; // !!!!!! No exception handling has done here. It is just for demonstration purpose. //Insurer company contract that calculate premium amount based on age,time_period,alcohol state and smoke state. contract InsurerCompany { //this method has defined payable only because we can show how we can pass gas while calling it. function insuranceAmountCalculator(int age,bool is_smoke, bool is_consume_alcohol,int time_period) external payable returns (int insurance_amount) { int variable_amount = 0; if(is_consume_alcohol){ variable_amount = variable_amount + 100; } if(is_smoke){ variable_amount = variable_amount + 100; } return ((variable_amount + (age + 50)) - time_period); //randon logic to calculate insurance amount based on age,time_period,alcohol state and smoke state. } } //contract for insurance agent. Insurance agent saving client user info and calculate insurance premium using Insurer company contract. contract InsuranceAgent { InsurerCompany ic; constructor(address _ic) public { ic = InsurerCompany(_ic); //assuming we know address of InsurerCompany contract. Initialize third party contract in constructor. } //define mapping to store key-value pairs. mapping(string => userRecord) userRecordMapping; //organize user records using struct struct userRecord { string unique_identification; string name; int age; bool is_smoke; bool is_consume_alcohol; int time_period; } //Save user record. Test data to test on Remix - ("U123",20,"Jon",true,true,10) function saveUserDetails(string memory unique_identification, int age, string memory name, bool is_smoke, bool is_consume_alcohol, int time_period) public payable { userRecordMapping[unique_identification] = userRecord(unique_identification, name, age, is_smoke, is_consume_alcohol, time_period); } //fetch insurance premium information using third party contract. Test data to test on Remix - ("U123") function getInsurancePremium(string memory unique_identification) public payable returns (int){ /* value(msg.value) - send gas in wei unit to destination contract i.e InsurerCompany. gas(1000) - Set gas limit modifier. */ return ic.insuranceAmountCalculator.value(msg.value).gas(1000)(userRecordMapping[unique_identification].age, userRecordMapping[unique_identification].is_smoke, userRecordMapping[unique_identification].is_consume_alcohol, userRecordMapping[unique_identification].time_period); } }
define mapping to store key-value pairs.
mapping(string => userRecord) userRecordMapping;
12,864,960
[ 1, 4625, 348, 7953, 560, 30, 4426, 2874, 358, 1707, 498, 17, 1132, 5574, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-31 */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; contract GemLike { function allowance(address, address) public returns (uint); function approve(address, uint) public; function transfer(address, uint) public returns (bool); function transferFrom(address, address, uint) public returns (bool); } contract ValueLike { function peek() public returns (uint, bool); } contract SaiTubLike { function skr() public view returns (GemLike); function gem() public view returns (GemLike); function gov() public view returns (GemLike); function sai() public view returns (GemLike); function pep() public view returns (ValueLike); function vox() public view returns (VoxLike); function bid(uint) public view returns (uint); function ink(bytes32) public view returns (uint); function tag() public view returns (uint); function tab(bytes32) public returns (uint); function rap(bytes32) public returns (uint); function draw(bytes32, uint) public; function shut(bytes32) public; function exit(uint) public; function give(bytes32, address) public; } contract VoxLike { function par() public returns (uint); } contract JoinLike { function ilk() public returns (bytes32); function gem() public returns (GemLike); function dai() public returns (GemLike); function join(address, uint) public; function exit(address, uint) public; } contract VatLike { function ilks(bytes32) public view returns (uint, uint, uint, uint, uint); function hope(address) public; function frob(bytes32, address, address, address, int, int) public; } contract ManagerLike { function vat() public view returns (address); function urns(uint) public view returns (address); function open(bytes32, address) public returns (uint); function frob(uint, int, int) public; function give(uint, address) public; function move(uint, address, uint) public; } contract OtcLike { function getPayAmount(address, address, uint) public view returns (uint); function buyAllAmount(address, uint, address, uint) public; } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } /** * @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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. 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; } /** * @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]; } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ contract ICErc20 { address public underlying; function mint(uint256 mintAmount) external returns (uint); function redeemUnderlying(uint256 redeemAmount) external returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getCash() external view returns (uint); function supplyRatePerBlock() external view returns (uint); } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { require(_upperBound > 0, "UniformRand/min-bound"); uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* internal */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack.length = 0; tree.nodes.length = 0; tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* internal Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) internal view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; if (tree.nodes.length == 0) { return 0; } else { return tree.nodes[0]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } /** * @author Brendan Asselstine * @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances. * * Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw. * When a new draw is opened, the previous opened draw is committed. * * The committed balance for an address is the total of their balances for committed Draws. * An address's open balance is their balance in the open Draw. */ library DrawManager { using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; using SafeMath for uint256; /** * The ID to use for the selection tree. */ bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws"; uint8 public constant MAX_BRANCHES_PER_NODE = 10; /** * Stores information for all draws. */ struct State { /** * Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index. * There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS. */ SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees; /** * Stores the consolidated draw index that an address deposited to. */ mapping(address => uint256) consolidatedDrawIndices; /** * Stores the last Draw index that an address deposited to. */ mapping(address => uint256) latestDrawIndices; /** * Stores a mapping of Draw index => Draw total */ mapping(uint256 => uint256) __deprecated__drawTotals; /** * The current open Draw index */ uint256 openDrawIndex; /** * The total of committed balances */ uint256 __deprecated__committedSupply; } /** * @notice Opens the next Draw and commits the previous open Draw (if any). * @param self The drawState this library is attached to * @return The index of the new open Draw */ function openNextDraw(State storage self) public returns (uint256) { if (self.openDrawIndex == 0) { // If there is no previous draw, we must initialize self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_BRANCHES_PER_NODE); } else { // else add current draw to sortition sum trees bytes32 drawId = bytes32(self.openDrawIndex); uint256 drawTotal = openSupply(self); self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId); } // now create a new draw uint256 drawIndex = self.openDrawIndex.add(1); self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_BRANCHES_PER_NODE); self.openDrawIndex = drawIndex; return drawIndex; } /** * @notice Deposits the given amount into the current open draw by the given user. * @param self The DrawManager state * @param _addr The address to deposit for * @param _amount The amount to deposit */ function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openDrawIndex = self.openDrawIndex; // update the current draw uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId); currentAmount = currentAmount.add(_amount); drawSet(self, openDrawIndex, currentAmount, _addr); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; // if this is the user's first draw, set it if (consolidatedDrawIndex == 0) { self.consolidatedDrawIndices[_addr] = openDrawIndex; // otherwise, if the consolidated draw is not this draw } else if (consolidatedDrawIndex != openDrawIndex) { // if a second draw does not exist if (latestDrawIndex == 0) { // set the second draw to the current draw self.latestDrawIndices[_addr] = openDrawIndex; // otherwise if a second draw exists but is not the current one } else if (latestDrawIndex != openDrawIndex) { // merge it into the first draw, and update the second draw index to this one uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); uint256 latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId); drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(latestAmount), _addr); drawSet(self, latestDrawIndex, 0, _addr); self.latestDrawIndices[_addr] = openDrawIndex; } } } /** * @notice Deposits into a user's committed balance, thereby bypassing the open draw. * @param self The DrawManager state * @param _addr The address of the user for whom to deposit * @param _amount The amount to deposit */ function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; // if they have a committed balance if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(_amount), _addr); } else { // they must not have any committed balance self.latestDrawIndices[_addr] = consolidatedDrawIndex; self.consolidatedDrawIndices[_addr] = self.openDrawIndex.sub(1); drawSet(self, self.consolidatedDrawIndices[_addr], _amount, _addr); } } /** * @notice Withdraws a user's committed and open draws. * @param self The DrawManager state * @param _addr The address whose balance to withdraw */ function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) { uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; if (consolidatedDrawIndex != 0) { drawSet(self, consolidatedDrawIndex, 0, _addr); delete self.consolidatedDrawIndices[_addr]; } if (latestDrawIndex != 0) { drawSet(self, latestDrawIndex, 0, _addr); delete self.latestDrawIndices[_addr]; } } /** * @notice Withdraw's from a user's open balance * @param self The DrawManager state * @param _addr The user to withdrawn from * @param _amount The amount to withdraw */ function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId); require(_amount <= openTotal, "DrawMan/exceeds-open"); uint256 remaining = openTotal.sub(_amount); drawSet(self, self.openDrawIndex, remaining, _addr); } /** * @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available. * @param self The DrawManager state * @param _addr The user to withdraw from * @param _amount The amount to withdraw. */ function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; uint256 consolidatedAmount = 0; uint256 latestAmount = 0; uint256 total = 0; if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) { latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId); total = total.add(latestAmount); } if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); total = total.add(consolidatedAmount); } // If the total is greater than zero, then consolidated *must* have the committed balance // However, if the total is zero then the consolidated balance may be the open balance if (total == 0) { return; } require(_amount <= total, "Pool/exceed"); uint256 remaining = total.sub(_amount); // if there was a second amount that needs to be updated if (remaining > consolidatedAmount) { uint256 secondRemaining = remaining.sub(consolidatedAmount); drawSet(self, latestDrawIndex, secondRemaining, _addr); } else if (latestAmount > 0) { // else delete the second amount if it exists delete self.latestDrawIndices[_addr]; drawSet(self, latestDrawIndex, 0, _addr); } // if the consolidated amount needs to be destroyed if (remaining == 0) { delete self.consolidatedDrawIndices[_addr]; drawSet(self, consolidatedDrawIndex, 0, _addr); } else if (remaining < consolidatedAmount) { drawSet(self, consolidatedDrawIndex, remaining, _addr); } } /** * @notice Returns the total balance for an address, including committed balances and the open balance. */ function balanceOf(State storage drawState, address _addr) public view returns (uint256) { return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr)); } /** * @notice Returns the total committed balance for an address. * @param self The DrawManager state * @param _addr The address whose committed balance should be returned * @return The total committed balance */ function committedBalanceOf(State storage self, address _addr) public view returns (uint256) { uint256 balance = 0; uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { balance = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), bytes32(uint256(_addr))); } if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), bytes32(uint256(_addr)))); } return balance; } /** * @notice Returns the open balance for an address * @param self The DrawManager state * @param _addr The address whose open balance should be returned * @return The open balance */ function openBalanceOf(State storage self, address _addr) public view returns (uint256) { if (self.openDrawIndex == 0) { return 0; } else { return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr))); } } /** * @notice Returns the open Draw balance for the DrawManager * @param self The DrawManager state * @return The open draw total balance */ function openSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(bytes32(self.openDrawIndex)); } /** * @notice Returns the committed balance for the DrawManager * @param self The DrawManager state * @return The total committed balance */ function committedSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(TREE_OF_DRAWS); } /** * @notice Updates the Draw balance for an address. * @param self The DrawManager state * @param _drawIndex The Draw index * @param _amount The new balance * @param _addr The address whose balance should be updated */ function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal { bytes32 drawId = bytes32(_drawIndex); bytes32 userId = bytes32(uint256(_addr)); uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId); if (oldAmount != _amount) { // If the amount has changed // Update the Draw's balance for that address self.sortitionSumTrees.set(drawId, _amount, userId); // if the draw is committed if (_drawIndex != self.openDrawIndex) { // Get the new draw total uint256 newDrawTotal = self.sortitionSumTrees.total(drawId); // update the draw in the committed tree self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId); } } } /** * @notice Selects an address by indexing into the committed tokens using the passed token. * If there is no committed supply, the zero address is returned. * @param self The DrawManager state * @param _token The token index to select * @return The selected address */ function draw(State storage self, uint256 _token) public view returns (address) { // If there is no one to select, just return the zero address if (committedSupply(self) == 0) { return address(0); } require(_token < committedSupply(self), "Pool/ineligible"); bytes32 drawIndex = self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token); uint256 drawSupply = self.sortitionSumTrees.total(drawIndex); uint256 drawToken = _token % drawSupply; return address(uint256(self.sortitionSumTrees.draw(drawIndex, drawToken))); } /** * @notice Selects an address using the entropy as an index into the committed tokens * The entropy is passed into the UniformRandomNumber library to remove modulo bias. * @param self The DrawManager state * @param _entropy The random entropy to use * @return The selected address */ function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) { uint256 bound = committedSupply(self); address selected; if (bound == 0) { selected = address(0); } else { selected = draw(self, UniformRandomNumber.uniform(uint256(_entropy), bound)); } return selected; } modifier requireOpenDraw(State storage self) { require(self.openDrawIndex > 0, "Pool/no-open"); _; } modifier requireCommittedDraw(State storage self) { require(self.openDrawIndex > 1, "Pool/no-commit"); _; } modifier onlyNonZero(address _addr) { require(_addr != address(0), "Pool/not-zero"); _; } } /** * @title FixidityLib * @author Gadi Guy, Alberto Cuesta Canada * @notice This library provides fixed point arithmetic with protection against * overflow. * All operations are done with int256 and the operands must have been created * with any of the newFrom* functions, which shift the comma digits() to the * right and check for limits. * When using this library be sure of using maxNewFixed() as the upper limit for * creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and * maxFixedAdd() if you want to be certain that those operations don't * overflow. */ library FixidityLib { /** * @notice Number of positions that the comma is shifted to the right. */ function digits() public pure returns(uint8) { return 24; } /** * @notice This is 1 in the fixed point units used in this library. * @dev Test fixed1() equals 10^digits() * Hardcoded to 24 digits. */ function fixed1() public pure returns(int256) { return 1000000000000000000000000; } /** * @notice The amount of decimals lost on each multiplication operand. * @dev Test mulPrecision() equals sqrt(fixed1) * Hardcoded to 24 digits. */ function mulPrecision() public pure returns(int256) { return 1000000000000; } /** * @notice Maximum value that can be represented in an int256 * @dev Test maxInt256() equals 2^255 -1 */ function maxInt256() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282019728792003956564819967; } /** * @notice Minimum value that can be represented in an int256 * @dev Test minInt256 equals (2^255) * (-1) */ function minInt256() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282019728792003956564819968; } /** * @notice Maximum value that can be converted to fixed point. Optimize for * @dev deployment. * Test maxNewFixed() equals maxInt256() / fixed1() * Hardcoded to 24 digits. */ function maxNewFixed() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Minimum value that can be converted to fixed point. Optimize for * deployment. * @dev Test minNewFixed() equals -(maxInt256()) / fixed1() * Hardcoded to 24 digits. */ function minNewFixed() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as an addition operator. * @dev Test maxFixedAdd() equals maxInt256()-1 / 2 * Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd() * Test add(maxFixedAdd()+1,maxFixedAdd()) throws * Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd() * Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws */ function maxFixedAdd() public pure returns(int256) { return 28948022309329048855892746252171976963317496166410141009864396001978282409983; } /** * @notice Maximum negative value that can be safely in a subtraction. * @dev Test maxFixedSub() equals minInt256() / 2 */ function maxFixedSub() public pure returns(int256) { return -28948022309329048855892746252171976963317496166410141009864396001978282409984; } /** * @notice Maximum value that can be safely used as a multiplication operator. * @dev Calculated as sqrt(maxInt256()*fixed1()). * Be careful with your sqrt() implementation. I couldn't find a calculator * that would give the exact square root of maxInt256*fixed1 so this number * is below the real number by no more than 3*10**28. It is safe to use as * a limit for your multiplications, although powers of two of numbers over * this value might still work. * Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul() * Test multiply(maxFixedMul(),maxFixedMul()+1) throws * Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul() * Test multiply(-maxFixedMul(),maxFixedMul()+1) throws * Hardcoded to 24 digits. */ function maxFixedMul() public pure returns(int256) { return 240615969168004498257251713877715648331380787511296; } /** * @notice Maximum value that can be safely used as a dividend. * @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256(). * Test maxFixedDiv() equals maxInt256()/fixed1() * Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws * Hardcoded to 24 digits. */ function maxFixedDiv() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as a divisor. * @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2) * Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1() * Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws * Hardcoded to 24 digits. */ function maxFixedDivisor() public pure returns(int256) { return 1000000000000000000000000000000000000000000000000; } /** * @notice Converts an int256 to fixed point units, equivalent to multiplying * by 10^digits(). * @dev Test newFixed(0) returns 0 * Test newFixed(1) returns fixed1() * Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1() * Test newFixed(maxNewFixed()+1) fails */ function newFixed(int256 x) public pure returns (int256) { require(x <= maxNewFixed()); require(x >= minNewFixed()); return x * fixed1(); } /** * @notice Converts an int256 in the fixed point representation of this * library to a non decimal. All decimal digits will be truncated. */ function fromFixed(int256 x) public pure returns (int256) { return x / fixed1(); } /** * @notice Converts an int256 which is already in some fixed point * representation to a different fixed precision representation. * Both the origin and destination precisions must be 38 or less digits. * Origin values with a precision higher than the destination precision * will be truncated accordingly. * @dev * Test convertFixed(1,0,0) returns 1; * Test convertFixed(1,1,1) returns 1; * Test convertFixed(1,1,0) returns 0; * Test convertFixed(1,0,1) returns 10; * Test convertFixed(10,1,0) returns 1; * Test convertFixed(10,0,1) returns 100; * Test convertFixed(100,1,0) returns 10; * Test convertFixed(100,0,1) returns 1000; * Test convertFixed(1000,2,0) returns 10; * Test convertFixed(1000,0,2) returns 100000; * Test convertFixed(1000,2,1) returns 100; * Test convertFixed(1000,1,2) returns 10000; * Test convertFixed(maxInt256,1,0) returns maxInt256/10; * Test convertFixed(maxInt256,0,1) throws * Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38); * Test convertFixed(1,0,38) returns 10**38; * Test convertFixed(maxInt256,39,0) throws * Test convertFixed(1,0,39) throws */ function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits) public pure returns (int256) { require(_originDigits <= 38 && _destinationDigits <= 38); uint8 decimalDifference; if ( _originDigits > _destinationDigits ){ decimalDifference = _originDigits - _destinationDigits; return x/(uint128(10)**uint128(decimalDifference)); } else if ( _originDigits < _destinationDigits ){ decimalDifference = _destinationDigits - _originDigits; // Cast uint8 -> uint128 is safe // Exponentiation is safe: // _originDigits and _destinationDigits limited to 38 or less // decimalDifference = abs(_destinationDigits - _originDigits) // decimalDifference < 38 // 10**38 < 2**128-1 require(x <= maxInt256()/uint128(10)**uint128(decimalDifference)); require(x >= minInt256()/uint128(10)**uint128(decimalDifference)); return x*(uint128(10)**uint128(decimalDifference)); } // _originDigits == digits()) return x; } /** * @notice Converts an int256 which is already in some fixed point * representation to that of this library. The _originDigits parameter is the * precision of x. Values with a precision higher than FixidityLib.digits() * will be truncated accordingly. */ function newFixed(int256 x, uint8 _originDigits) public pure returns (int256) { return convertFixed(x, _originDigits, digits()); } /** * @notice Converts an int256 in the fixed point representation of this * library to a different representation. The _destinationDigits parameter is the * precision of the output x. Values with a precision below than * FixidityLib.digits() will be truncated accordingly. */ function fromFixed(int256 x, uint8 _destinationDigits) public pure returns (int256) { return convertFixed(x, digits(), _destinationDigits); } /** * @notice Converts two int256 representing a fraction to fixed point units, * equivalent to multiplying dividend and divisor by 10^digits(). * @dev * Test newFixedFraction(maxFixedDiv()+1,1) fails * Test newFixedFraction(1,maxFixedDiv()+1) fails * Test newFixedFraction(1,0) fails * Test newFixedFraction(0,1) returns 0 * Test newFixedFraction(1,1) returns fixed1() * Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1() * Test newFixedFraction(1,fixed1()) returns 1 * Test newFixedFraction(1,fixed1()-1) returns 0 */ function newFixedFraction( int256 numerator, int256 denominator ) public pure returns (int256) { require(numerator <= maxNewFixed()); require(denominator <= maxNewFixed()); require(denominator != 0); int256 convertedNumerator = newFixed(numerator); int256 convertedDenominator = newFixed(denominator); return divide(convertedNumerator, convertedDenominator); } /** * @notice Returns the integer part of a fixed point number. * @dev * Test integer(0) returns 0 * Test integer(fixed1()) returns fixed1() * Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test integer(-fixed1()) returns -fixed1() * Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1() */ function integer(int256 x) public pure returns (int256) { return (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Returns the fractional part of a fixed point number. * In the case of a negative number the fractional is also negative. * @dev * Test fractional(0) returns 0 * Test fractional(fixed1()) returns 0 * Test fractional(fixed1()-1) returns 10^24-1 * Test fractional(-fixed1()) returns 0 * Test fractional(-fixed1()+1) returns -10^24-1 */ function fractional(int256 x) public pure returns (int256) { return x - (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Converts to positive if negative. * Due to int256 having one more negative number than positive numbers * abs(minInt256) reverts. * @dev * Test abs(0) returns 0 * Test abs(fixed1()) returns -fixed1() * Test abs(-fixed1()) returns fixed1() * Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1() */ function abs(int256 x) public pure returns (int256) { if (x >= 0) { return x; } else { int256 result = -x; assert (result > 0); return result; } } /** * @notice x+y. If any operator is higher than maxFixedAdd() it * might overflow. * In solidity maxInt256 + 1 = minInt256 and viceversa. * @dev * Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1 * Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails * Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256() * Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails * Test add(maxInt256(),maxInt256()) fails * Test add(minInt256(),minInt256()) fails */ function add(int256 x, int256 y) public pure returns (int256) { int256 z = x + y; if (x > 0 && y > 0) assert(z > x && z > y); if (x < 0 && y < 0) assert(z < x && z < y); return z; } /** * @notice x-y. You can use add(x,-y) instead. * @dev Tests covered by add(x,y) */ function subtract(int256 x, int256 y) public pure returns (int256) { return add(x,-y); } /** * @notice x*y. If any of the operators is higher than maxFixedMul() it * might overflow. * @dev * Test multiply(0,0) returns 0 * Test multiply(maxFixedMul(),0) returns 0 * Test multiply(0,maxFixedMul()) returns 0 * Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul() * Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul() * Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5) * Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision()) * Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1) * Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits * Test multiply(maxFixedMul()+1,maxFixedMul()) fails * Test multiply(maxFixedMul(),maxFixedMul()+1) fails */ function multiply(int256 x, int256 y) public pure returns (int256) { if (x == 0 || y == 0) return 0; if (y == fixed1()) return x; if (x == fixed1()) return y; // Separate into integer and fractional parts // x = x1 + x2, y = y1 + y2 int256 x1 = integer(x) / fixed1(); int256 x2 = fractional(x); int256 y1 = integer(y) / fixed1(); int256 y2 = fractional(y); // (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2) int256 x1y1 = x1 * y1; if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1 // x1y1 needs to be multiplied back by fixed1 // solium-disable-next-line mixedcase int256 fixed_x1y1 = x1y1 * fixed1(); if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1 x1y1 = fixed_x1y1; int256 x2y1 = x2 * y1; if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1 int256 x1y2 = x1 * y2; if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2 x2 = x2 / mulPrecision(); y2 = y2 / mulPrecision(); int256 x2y2 = x2 * y2; if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2 // result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1(); int256 result = x1y1; result = add(result, x2y1); // Add checks for overflow result = add(result, x1y2); // Add checks for overflow result = add(result, x2y2); // Add checks for overflow return result; } /** * @notice 1/x * @dev * Test reciprocal(0) fails * Test reciprocal(fixed1()) returns fixed1() * Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated * Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated */ function reciprocal(int256 x) public pure returns (int256) { require(x != 0); return (fixed1()*fixed1()) / x; // Can't overflow } /** * @notice x/y. If the dividend is higher than maxFixedDiv() it * might overflow. You can use multiply(x,reciprocal(y)) instead. * There is a loss of precision on division for the lower mulPrecision() decimals. * @dev * Test divide(fixed1(),0) fails * Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,1) throws * Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1() */ function divide(int256 x, int256 y) public pure returns (int256) { if (y == fixed1()) return x; require(y != 0); require(y <= maxFixedDivisor()); return multiply(x, reciprocal(y)); } } /** * @title Blocklock * @author Brendan Asselstine * @notice A time lock with a cooldown period. When locked, the contract will remain locked until it is unlocked manually * or the lock duration expires. After the contract is unlocked, it cannot be locked until the cooldown duration expires. */ library Blocklock { using SafeMath for uint256; struct State { uint256 lockedAt; uint256 unlockedAt; uint256 lockDuration; uint256 cooldownDuration; } /** * @notice Sets the duration of the lock. This how long the lock lasts before it expires and automatically unlocks. * @param self The Blocklock state * @param lockDuration The duration, in blocks, that the lock should last. */ function setLockDuration(State storage self, uint256 lockDuration) public { require(lockDuration > 0, "Blocklock/lock-min"); self.lockDuration = lockDuration; } /** * @notice Sets the cooldown duration in blocks. This is the number of blocks that must pass before being able to * lock again. The cooldown duration begins when the lock duration expires, or when it is unlocked manually. * @param self The Blocklock state * @param cooldownDuration The duration of the cooldown, in blocks. */ function setCooldownDuration(State storage self, uint256 cooldownDuration) public { require(cooldownDuration > 0, "Blocklock/cool-min"); self.cooldownDuration = cooldownDuration; } /** * @notice Returns whether the state is locked at the given block number. * @param self The Blocklock state * @param blockNumber The current block number. */ function isLocked(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt != 0 && blockNumber >= self.lockedAt && blockNumber < endAt ); } /** * @notice Locks the state at the given block number. * @param self The Blocklock state * @param blockNumber The block number to use as the lock start time */ function lock(State storage self, uint256 blockNumber) public { require(canLock(self, blockNumber), "Blocklock/no-lock"); self.lockedAt = blockNumber; } /** * @notice Manually unlocks the lock. * @param self The Blocklock state * @param blockNumber The block number at which the lock is being unlocked. */ function unlock(State storage self, uint256 blockNumber) public { self.unlockedAt = blockNumber; } /** * @notice Returns whether the Blocklock can be locked at the given block number * @param self The Blocklock state * @param blockNumber The block number to check against * @return True if we can lock at the given block number, false otherwise. */ function canLock(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt == 0 || blockNumber >= endAt.add(self.cooldownDuration) ); } function cooldownEndAt(State storage self) internal view returns (uint256) { return lockEndAt(self).add(self.cooldownDuration); } function lockEndAt(State storage self) internal view returns (uint256) { uint256 endAt = self.lockedAt.add(self.lockDuration); // if we unlocked early if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) { endAt = self.unlockedAt; } return endAt; } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Implementation of the {IERC777} interface. * * Largely taken from the OpenZeppelin ERC777 contract. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. * * It is important to note that no Mint events are emitted. Tokens are minted in batches * by a state change in a tree data structure, so emitting a Mint event for each user * is not possible. * */ contract PoolToken is Initializable, IERC20, IERC777 { using SafeMath for uint256; using Address for address; /** * Event emitted when a user or operator redeems tokens */ event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256("ERC777Token") bytes32 constant internal TOKENS_INTERFACE_HASH = 0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054; // keccak256("ERC20Token") bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH = 0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a; string internal _name; string internal _symbol; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] internal _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) internal _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) internal _operators; mapping(address => mapping(address => bool)) internal _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) internal _allowances; // The Pool that is bound to this token BasePool internal _pool; /** * @notice Initializes the PoolToken. * @param name The name of the token * @param symbol The token symbol * @param defaultOperators The default operators who are allowed to move tokens */ function init ( string memory name, string memory symbol, address[] memory defaultOperators, BasePool pool ) public initializer { require(bytes(name).length != 0, "PoolToken/name"); require(bytes(symbol).length != 0, "PoolToken/symbol"); require(address(pool) != address(0), "PoolToken/pool-zero"); _name = name; _symbol = symbol; _pool = pool; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this)); } /** * @notice Returns the address of the Pool contract * @return The address of the pool contract */ function pool() public view returns (BasePool) { return _pool; } /** * @notice Calls the ERC777 transfer hook, and emits Redeemed and Transfer. Can only be called by the Pool contract. * @param from The address from which to redeem tokens * @param amount The amount of tokens to redeem */ function poolRedeem(address from, uint256 amount) external onlyPool { _callTokensToSend(from, from, address(0), amount, '', ''); emit Redeemed(from, from, amount, '', ''); emit Transfer(from, address(0), amount); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public view returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _pool.committedSupply(); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address _addr) external view returns (uint256) { return _pool.committedBalanceOf(_addr); } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(msg.sender, msg.sender, recipient, amount, data, ""); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/transfer-zero"); address from = msg.sender; _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev Allows a user to withdraw their tokens as the underlying asset. * * Also emits a {Transfer} event for ERC20 compatibility. */ function redeem(uint256 amount, bytes calldata data) external { _redeem(msg.sender, msg.sender, amount, data, ""); } /** * @dev See {IERC777-burn}. Not currently implemented. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(msg.sender != operator, "PoolToken/auth-self"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[msg.sender][operator]; } else { _operators[msg.sender][operator] = true; } emit AuthorizedOperator(operator, msg.sender); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != msg.sender, "PoolToken/revoke-self"); if (_defaultOperators[operator]) { _revokedDefaultOperators[msg.sender][operator] = true; } else { delete _operators[msg.sender][operator]; } emit RevokedOperator(operator, msg.sender); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external { require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator"); _send(msg.sender, sender, recipient, amount, data, operatorData); } /** * @dev See {IERC777-operatorBurn}. * * Currently not supported */ function operatorBurn(address, uint256, bytes calldata, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user. * * Emits {Redeemed} and {Transfer} events. */ function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(msg.sender, account), "PoolToken/not-operator"); _redeem(msg.sender, account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = msg.sender; _approve(holder, spender, value); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "PoolToken/negative")); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/to-zero"); require(holder != address(0), "PoolToken/from-zero"); address spender = msg.sender; _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * Called by the associated Pool to emit `Mint` events. * @param amount The amount that was minted */ function poolMint(uint256 amount) external onlyPool { _mintEvents(address(_pool), address(_pool), amount, '', ''); } /** * Emits {Minted} and {IERC20-Transfer} events. */ function _mintEvents( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); require(to != address(0), "PoolToken/to-zero"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, false); } /** * @dev Redeems tokens for the underlying asset. * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to redeem * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _redeem( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _pool.withdrawCommittedDepositFrom(from, amount); emit Redeemed(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } /** * @notice Moves tokens from one user to another. Emits Sent and Transfer events. */ function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _pool.moveCommitted(from, to, amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * Approves of a token spend by a spender for a holder. * @param holder The address from which the tokens are spent * @param spender The address that is spending the tokens * @param value The amount of tokens to spend */ function _approve(address holder, address spender, uint256 value) private { require(spender != address(0), "PoolToken/from-zero"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal notLocked { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck whether to require that, if the recipient is a contract, it has registered a IERC777Recipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "PoolToken/no-recip-inter"); } } /** * @notice Requires the sender to be the pool contract */ modifier onlyPool() { require(msg.sender == address(_pool), "PoolToken/only-pool"); _; } /** * @notice Requires the contract to be unlocked */ modifier notLocked() { require(!_pool.isLocked(), "PoolToken/is-locked"); _; } } /** * @title The Pool contract * @author Brendan Asselstine * @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws. * Funds are immediately deposited and withdrawn from the Compound cToken contract. * Draws go through three stages: open, committed and rewarded in that order. * Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance. * When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated. * When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being * proportional to their committed balance vs the total committed balance of all users. * * * With the above in mind, there is always an open draw and possibly a committed draw. The progression is: * * Step 1: Draw 1 Open * Step 2: Draw 2 Open | Draw 1 Committed * Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded * Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded * Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded * Step X: ... */ contract BasePool is Initializable, ReentrancyGuard { using DrawManager for DrawManager.State; using SafeMath for uint256; using Roles for Roles.Role; using Blocklock for Blocklock.State; bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1)); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("PoolTogetherRewardListener") bytes32 constant internal REWARD_LISTENER_INTERFACE_HASH = 0x68f03b0b1a978ee238a70b362091d993343460bc1a2830ab3f708936d9f564a4; /** * Emitted when a user deposits into the Pool. * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event Deposited(address indexed sender, uint256 amount); /** * Emitted when a user deposits into the Pool and the deposit is immediately committed * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event DepositedAndCommitted(address indexed sender, uint256 amount); /** * Emitted when Sponsors have deposited into the Pool * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event SponsorshipDeposited(address indexed sender, uint256 amount); /** * Emitted when an admin has been added to the Pool. * @param admin The admin that was added */ event AdminAdded(address indexed admin); /** * Emitted when an admin has been removed from the Pool. * @param admin The admin that was removed */ event AdminRemoved(address indexed admin); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws their sponsorship and fees from the pool. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their open deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event OpenDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their committed deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event CommittedDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when an address collects a fee * @param sender The address collecting the fee * @param amount The fee amount * @param drawId The draw from which the fee was awarded */ event FeeCollected(address indexed sender, uint256 amount, uint256 drawId); /** * Emitted when a new draw is opened for deposit. * @param drawId The draw id * @param feeBeneficiary The fee beneficiary for this draw * @param secretHash The committed secret hash * @param feeFraction The fee fraction of the winnings to be given to the beneficiary */ event Opened( uint256 indexed drawId, address indexed feeBeneficiary, bytes32 secretHash, uint256 feeFraction ); /** * Emitted when a draw is committed. * @param drawId The draw id */ event Committed( uint256 indexed drawId ); /** * Emitted when a draw is rewarded. * @param drawId The draw id * @param winner The address of the winner * @param entropy The entropy used to select the winner * @param winnings The net winnings given to the winner * @param fee The fee being given to the draw beneficiary */ event Rewarded( uint256 indexed drawId, address indexed winner, bytes32 entropy, uint256 winnings, uint256 fee ); /** * Emitted when a RewardListener call fails * @param drawId The draw id * @param winner The address that one the draw * @param impl The implementation address of the RewardListener */ event RewardListenerFailed( uint256 indexed drawId, address indexed winner, address indexed impl ); /** * Emitted when the fee fraction is changed. Takes effect on the next draw. * @param feeFraction The next fee fraction encoded as a fixed point 18 decimal */ event NextFeeFractionChanged(uint256 feeFraction); /** * Emitted when the next fee beneficiary changes. Takes effect on the next draw. * @param feeBeneficiary The next fee beneficiary */ event NextFeeBeneficiaryChanged(address indexed feeBeneficiary); /** * Emitted when an admin pauses the contract */ event DepositsPaused(address indexed sender); /** * Emitted when an admin unpauses the contract */ event DepositsUnpaused(address indexed sender); /** * Emitted when the draw is rolled over in the event that the secret is forgotten. */ event RolledOver(uint256 indexed drawId); struct Draw { uint256 feeFraction; //fixed point 18 address feeBeneficiary; uint256 openedBlock; bytes32 secretHash; bytes32 entropy; address winner; uint256 netWinnings; uint256 fee; } /** * The Compound cToken that this Pool is bound to. */ ICErc20 public cToken; /** * The fee beneficiary to use for subsequent Draws. */ address public nextFeeBeneficiary; /** * The fee fraction to use for subsequent Draws. */ uint256 public nextFeeFraction; /** * The total of all balances */ uint256 public accountedBalance; /** * The total deposits and winnings for each user. */ mapping (address => uint256) internal balances; /** * A mapping of draw ids to Draw structures */ mapping(uint256 => Draw) internal draws; /** * A structure that is used to manage the user's odds of winning. */ DrawManager.State internal drawState; /** * A structure containing the administrators */ Roles.Role internal admins; /** * Whether the contract is paused */ bool public paused; Blocklock.State internal blocklock; PoolToken public poolToken; /** * @notice Initializes a new Pool contract. * @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries. * @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _feeBeneficiary The address that will receive the fee fraction */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 _lockDuration, uint256 _cooldownDuration ) public initializer { require(_owner != address(0), "Pool/owner-zero"); require(_cToken != address(0), "Pool/ctoken-zero"); cToken = ICErc20(_cToken); _addAdmin(_owner); _setNextFeeFraction(_feeFraction); _setNextFeeBeneficiary(_feeBeneficiary); initBlocklock(_lockDuration, _cooldownDuration); } function setPoolToken(PoolToken _poolToken) external onlyAdmin { require(address(poolToken) == address(0), "Pool/token-was-set"); require(address(_poolToken.pool()) == address(this), "Pool/token-mismatch"); poolToken = _poolToken; } function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal { blocklock.setLockDuration(_lockDuration); blocklock.setCooldownDuration(_cooldownDuration); } /** * @notice Opens a new Draw. * @param _secretHash The secret hash to commit to the Draw. */ function open(bytes32 _secretHash) internal { drawState.openNextDraw(); draws[drawState.openDrawIndex] = Draw( nextFeeFraction, nextFeeBeneficiary, block.number, _secretHash, bytes32(0), address(0), uint256(0), uint256(0) ); emit Opened( drawState.openDrawIndex, nextFeeBeneficiary, _secretHash, nextFeeFraction ); } /** * @notice Emits the Committed event for the current open draw. */ function emitCommitted() internal { uint256 drawId = currentOpenDrawId(); emit Committed(drawId); if (address(poolToken) != address(0)) { poolToken.poolMint(openSupply()); } } /** * @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice: * the first after Pool contract creation and the second immediately after. * Can only be called by an admin. * May fire the Committed event, and always fires the Open event. * @param nextSecretHash The secret hash to use to open a new Draw */ function openNextDraw(bytes32 nextSecretHash) public onlyAdmin { if (currentCommittedDrawId() > 0) { require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward"); } if (currentOpenDrawId() != 0) { emitCommitted(); } open(nextSecretHash); } /** * @notice Ignores the current draw, and opens the next draw. * @dev This function will be removed once the winner selection has been decentralized. * @param nextSecretHash The hash to commit for the next draw */ function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin { rollover(); openNextDraw(nextSecretHash); } /** * @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash. * Can only be called by an admin. * Fires the Rewarded event, the Committed event, and the Open event. * @param nextSecretHash The secret hash to use to open a new Draw * @param lastSecret The secret to reveal to reward the current committed Draw. * @param _salt The salt that was used to conceal the secret */ function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin { reward(lastSecret, _salt); openNextDraw(nextSecretHash); } /** * @notice Rewards the winner for the current committed Draw using the passed secret. * The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. * A winner is calculated using the revealed secret. * If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. * The draw beneficiary's balance is updated with the fee. * The accounted balance is updated to include the fee and, if there was a winner, the net winnings. * Fires the Rewarded event. * @param _secret The secret to reveal for the current committed Draw * @param _salt The salt that was used to conceal the secret */ function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant { // require that there is a committed draw // require that the committed draw has not been rewarded uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret"); // derive entropy from the revealed secret bytes32 entropy = keccak256(abi.encodePacked(_secret)); _reward(drawId, draw, entropy); } function _reward(uint256 drawId, Draw storage draw, bytes32 entropy) internal { blocklock.unlock(block.number); // Select the winner using the hash as entropy address winningAddress = calculateWinner(entropy); // Calculate the gross winnings uint256 underlyingBalance = balance(); uint256 grossWinnings; // It's possible when the APR is zero that the underlying balance will be slightly lower than the accountedBalance // due to rounding errors in the Compound contract. if (underlyingBalance > accountedBalance) { grossWinnings = capWinnings(underlyingBalance.sub(accountedBalance)); } // Calculate the beneficiary fee uint256 fee = calculateFee(draw.feeFraction, grossWinnings); // Update balance of the beneficiary balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee); // Calculate the net winnings uint256 netWinnings = grossWinnings.sub(fee); draw.winner = winningAddress; draw.netWinnings = netWinnings; draw.fee = fee; draw.entropy = entropy; // If there is a winner who is to receive non-zero winnings if (winningAddress != address(0) && netWinnings != 0) { // Updated the accounted total accountedBalance = underlyingBalance; // Update balance of the winner balances[winningAddress] = balances[winningAddress].add(netWinnings); // Enter their winnings into the open draw drawState.deposit(winningAddress, netWinnings); callRewarded(winningAddress, netWinnings, drawId); } else { // Only account for the fee accountedBalance = accountedBalance.add(fee); } emit Rewarded( drawId, winningAddress, entropy, netWinnings, fee ); emit FeeCollected(draw.feeBeneficiary, fee, drawId); } /** * @notice Calls the reward listener for the winner, if a listener exists. * @dev Checks for a listener using the ERC1820 registry. The listener is given a gas stipend of 200,000 to run the function. * The number 200,000 was selected because it's safely above the gas requirements for PoolTogether [Pod](https://github.com/pooltogether/pods) contract. * * @param winner The winner. If they have a listener registered in the ERC1820 registry it will be called. * @param netWinnings The amount that was won. * @param drawId The draw id that was won. */ function callRewarded(address winner, uint256 netWinnings, uint256 drawId) internal { address impl = ERC1820_REGISTRY.getInterfaceImplementer(winner, REWARD_LISTENER_INTERFACE_HASH); if (impl != address(0)) { (bool success,) = impl.call.gas(200000)(abi.encodeWithSignature("rewarded(address,uint256,uint256)", winner, netWinnings, drawId)); if (!success) { emit RewardListenerFailed(drawId, winner, impl); } } } /** * @notice A function that skips the reward for the committed draw id. * @dev This function will be removed once the entropy is decentralized. */ function rollover() public onlyAdmin requireCommittedNoReward { uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER; emit RolledOver( drawId ); emit Rewarded( drawId, address(0), ROLLED_OVER_ENTROPY_MAGIC_NUMBER, 0, 0 ); } /** * @notice Ensures that the winnings don't overflow. Note that we can make this integer max, because the fee * is always less than zero (meaning the FixidityLib.multiply will always make the number smaller) */ function capWinnings(uint256 _grossWinnings) internal pure returns (uint256) { uint256 max = uint256(FixidityLib.maxNewFixed()); if (_grossWinnings > max) { return max; } return _grossWinnings; } /** * @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings. * @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number. * @param _grossWinnings The gross winnings to take a fraction of. */ function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) { int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings)); // _feeFraction *must* be less than 1 ether, so it will never overflow int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18))); return uint256(FixidityLib.fromFixed(feeFixed)); } /** * @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken. * Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time. * The deposit will immediately be added to Compound and the interest will contribute to the next draw. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositSponsorship(uint256 _amount) public unlessDepositsPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the sponsorship amount _depositSponsorshipFrom(msg.sender, _amount); } /** * @notice Deposits the token balance for this contract as a sponsorship. * If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship. */ function transferBalanceToSponsorship() public unlessDepositsPaused { // Deposit the sponsorship amount _depositSponsorshipFrom(address(this), token().balanceOf(address(this))); } /** * @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken. * Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning * proportional to the total committed balance of all users. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositPool(uint256 _amount) public requireOpenDraw unlessDepositsPaused nonReentrant notLocked { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the funds _depositPoolFrom(msg.sender, _amount); } /** * @notice Deposits sponsorship for a user * @param _spender The user who is sponsoring * @param _amount The amount they are sponsoring */ function _depositSponsorshipFrom(address _spender, uint256 _amount) internal { // Deposit the funds _depositFrom(_spender, _amount); emit SponsorshipDeposited(_spender, _amount); } /** * @notice Deposits into the pool for a user. The deposit will be open until the next draw is committed. * @param _spender The user who is depositing * @param _amount The amount the user is depositing */ function _depositPoolFrom(address _spender, uint256 _amount) internal { // Update the user's eligibility drawState.deposit(_spender, _amount); _depositFrom(_spender, _amount); emit Deposited(_spender, _amount); } /** * @notice Deposits into the pool for a user. The deposit is made part of the currently committed draw * @param _spender The user who is depositing * @param _amount The amount to deposit */ function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked { // Update the user's eligibility drawState.depositCommitted(_spender, _amount); _depositFrom(_spender, _amount); emit DepositedAndCommitted(_spender, _amount); } /** * @notice Deposits into the pool for a user. Updates their balance and transfers their tokens into this contract. * @param _spender The user who is depositing * @param _amount The amount they are depositing */ function _depositFrom(address _spender, uint256 _amount) internal { // Update the user's balance balances[_spender] = balances[_spender].add(_amount); // Update the total of this contract accountedBalance = accountedBalance.add(_amount); // Deposit into Compound require(token().approve(address(cToken), _amount), "Pool/approve"); require(cToken.mint(_amount) == 0, "Pool/supply"); } /** * Withdraws the given amount from the user's deposits. It first withdraws from their sponsorship, * then their open deposits, then their committed deposits. * * @param amount The amount to withdraw. */ function withdraw(uint256 amount) public nonReentrant notLocked { uint256 remainingAmount = amount; // first sponsorship uint256 sponsorshipAndFeesBalance = sponsorshipAndFeeBalanceOf(msg.sender); if (sponsorshipAndFeesBalance < remainingAmount) { withdrawSponsorshipAndFee(sponsorshipAndFeesBalance); remainingAmount = remainingAmount.sub(sponsorshipAndFeesBalance); } else { withdrawSponsorshipAndFee(remainingAmount); return; } // now pending uint256 pendingBalance = drawState.openBalanceOf(msg.sender); if (pendingBalance < remainingAmount) { _withdrawOpenDeposit(msg.sender, pendingBalance); remainingAmount = remainingAmount.sub(pendingBalance); } else { _withdrawOpenDeposit(msg.sender, remainingAmount); return; } // now committed. remainingAmount should not be greater than committed balance. _withdrawCommittedDeposit(msg.sender, remainingAmount); } /** * @notice Withdraw the sender's entire balance back to them. */ function withdraw() public nonReentrant notLocked { uint256 committedBalance = drawState.committedBalanceOf(msg.sender); uint256 balance = balances[msg.sender]; // Update their chances of winning drawState.withdraw(msg.sender); _withdraw(msg.sender, balance); if (address(poolToken) != address(0)) { poolToken.poolRedeem(msg.sender, committedBalance); } emit Withdrawn(msg.sender, balance); } /** * Withdraws only from the sender's sponsorship and fee balances * @param _amount The amount to withdraw */ function withdrawSponsorshipAndFee(uint256 _amount) public { uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender); require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee"); _withdraw(msg.sender, _amount); emit SponsorshipAndFeesWithdrawn(msg.sender, _amount); } /** * Returns the total balance of the user's sponsorship and fees * @param _sender The user whose balance should be returned */ function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) { return balances[_sender].sub(drawState.balanceOf(_sender)); } /** * Withdraws from the user's open deposits * @param _amount The amount to withdraw */ function withdrawOpenDeposit(uint256 _amount) public nonReentrant notLocked { _withdrawOpenDeposit(msg.sender, _amount); } function _withdrawOpenDeposit(address sender, uint256 _amount) internal { drawState.withdrawOpen(sender, _amount); _withdraw(sender, _amount); emit OpenDepositWithdrawn(sender, _amount); } /** * Withdraws from the user's committed deposits * @param _amount The amount to withdraw */ function withdrawCommittedDeposit(uint256 _amount) public nonReentrant notLocked returns (bool) { _withdrawCommittedDeposit(msg.sender, _amount); return true; } function _withdrawCommittedDeposit(address sender, uint256 _amount) internal { _withdrawCommittedDepositAndEmit(sender, _amount); if (address(poolToken) != address(0)) { poolToken.poolRedeem(sender, _amount); } } /** * Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token. * @param _from The user to withdraw from * @param _amount The amount to withdraw */ function withdrawCommittedDepositFrom( address _from, uint256 _amount ) external onlyToken notLocked returns (bool) { return _withdrawCommittedDepositAndEmit(_from, _amount); } /** * A function that withdraws committed deposits for a user and emits the corresponding events. * @param _from User to withdraw for * @param _amount The amount to withdraw */ function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) { drawState.withdrawCommitted(_from, _amount); _withdraw(_from, _amount); emit CommittedDepositWithdrawn(_from, _amount); return true; } /** * @notice Allows the associated PoolToken to move committed tokens from one user to another. * @param _from The account to move tokens from * @param _to The account that is receiving the tokens * @param _amount The amount of tokens to transfer */ function moveCommitted( address _from, address _to, uint256 _amount ) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) { balances[_from] = balances[_from].sub(_amount, "move could not sub amount"); balances[_to] = balances[_to].add(_amount); drawState.withdrawCommitted(_from, _amount); drawState.depositCommitted(_to, _amount); return true; } /** * @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance. */ function _withdraw(address _sender, uint256 _amount) internal { uint256 balance = balances[_sender]; require(_amount <= balance, "Pool/no-funds"); // Update the user's balance balances[_sender] = balance.sub(_amount); // Update the total of this contract accountedBalance = accountedBalance.sub(_amount); // Withdraw from Compound and transfer require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem"); require(token().transfer(_sender, _amount), "Pool/transfer"); } /** * @notice Returns the id of the current open Draw. * @return The current open Draw id */ function currentOpenDrawId() public view returns (uint256) { return drawState.openDrawIndex; } /** * @notice Returns the id of the current committed Draw. * @return The current committed Draw id */ function currentCommittedDrawId() public view returns (uint256) { if (drawState.openDrawIndex > 1) { return drawState.openDrawIndex - 1; } else { return 0; } } /** * @notice Returns whether the current committed draw has been rewarded * @return True if the current committed draw has been rewarded, false otherwise */ function currentCommittedDrawHasBeenRewarded() internal view returns (bool) { Draw storage draw = draws[currentCommittedDrawId()]; return draw.entropy != bytes32(0); } /** * @notice Gets information for a given draw. * @param _drawId The id of the Draw to retrieve info for. * @return Fields including: * feeFraction: the fee fraction * feeBeneficiary: the beneficiary of the fee * openedBlock: The block at which the draw was opened * secretHash: The hash of the secret committed to this draw. * entropy: the entropy used to select the winner * winner: the address of the winner * netWinnings: the total winnings less the fee * fee: the fee taken by the beneficiary */ function getDraw(uint256 _drawId) public view returns ( uint256 feeFraction, address feeBeneficiary, uint256 openedBlock, bytes32 secretHash, bytes32 entropy, address winner, uint256 netWinnings, uint256 fee ) { Draw storage draw = draws[_drawId]; feeFraction = draw.feeFraction; feeBeneficiary = draw.feeBeneficiary; openedBlock = draw.openedBlock; secretHash = draw.secretHash; entropy = draw.entropy; winner = draw.winner; netWinnings = draw.netWinnings; fee = draw.fee; } /** * @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning. * @param _addr The address of the user * @return The total committed balance for the user */ function committedBalanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning. * @param _addr The address of the user * @return The total open balance for the user */ function openBalanceOf(address _addr) external view returns (uint256) { return drawState.openBalanceOf(_addr); } /** * @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits. * @param _addr The address of the user to check. * @return The user's current balance. */ function totalBalanceOf(address _addr) external view returns (uint256) { return balances[_addr]; } /** * @notice Returns a user's committed balance. This is the balance of their Pool tokens. * @param _addr The address of the user to check. * @return The user's current balance. */ function balanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Calculates a winner using the passed entropy for the current committed balances. * @param _entropy The entropy to use to select the winner * @return The winning address */ function calculateWinner(bytes32 _entropy) public view returns (address) { return drawState.drawWithEntropy(_entropy); } /** * @notice Returns the total committed balance. Used to compute an address's chances of winning. * @return The total committed balance. */ function committedSupply() public view returns (uint256) { return drawState.committedSupply(); } /** * @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw. * @return The total open balance */ function openSupply() public view returns (uint256) { return drawState.openSupply(); } /** * @notice Calculates the total estimated interest earned for the given number of blocks * @param _blocks The number of block that interest accrued for * @return The total estimated interest as a 18 point fixed decimal. */ function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); } /** * @notice Convenience function to return the supplyRatePerBlock value from the money market contract. * @return The cToken supply rate per block */ function supplyRatePerBlock() public view returns (uint256) { return cToken.supplyRatePerBlock(); } /** * @notice Sets the beneficiary fee fraction for subsequent Draws. * Fires the NextFeeFractionChanged event. * Can only be called by an admin. * @param _feeFraction The fee fraction to use. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin { _setNextFeeFraction(_feeFraction); } function _setNextFeeFraction(uint256 _feeFraction) internal { require(_feeFraction <= 1 ether, "Pool/less-1"); nextFeeFraction = _feeFraction; emit NextFeeFractionChanged(_feeFraction); } /** * @notice Sets the fee beneficiary for subsequent Draws. * Can only be called by admins. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); } /** * @notice Sets the fee beneficiary for subsequent Draws. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function _setNextFeeBeneficiary(address _feeBeneficiary) internal { require(_feeBeneficiary != address(0), "Pool/not-zero"); nextFeeBeneficiary = _feeBeneficiary; emit NextFeeBeneficiaryChanged(_feeBeneficiary); } /** * @notice Adds an administrator. * Can only be called by administrators. * Fires the AdminAdded event. * @param _admin The address of the admin to add */ function addAdmin(address _admin) public onlyAdmin { _addAdmin(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function isAdmin(address _admin) public view returns (bool) { return admins.has(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function _addAdmin(address _admin) internal { admins.add(_admin); emit AdminAdded(_admin); } /** * @notice Removes an administrator * Can only be called by an admin. * Admins cannot remove themselves. This ensures there is always one admin. * @param _admin The address of the admin to remove */ function removeAdmin(address _admin) public onlyAdmin { require(admins.has(_admin), "Pool/no-admin"); require(_admin != msg.sender, "Pool/remove-self"); admins.remove(_admin); emit AdminRemoved(_admin); } /** * Requires that there is a committed draw that has not been rewarded. */ modifier requireCommittedNoReward() { require(currentCommittedDrawId() > 0, "Pool/committed"); require(!currentCommittedDrawHasBeenRewarded(), "Pool/already"); _; } /** * @notice Returns the token underlying the cToken. * @return An ERC20 token address */ function token() public view returns (IERC20) { return IERC20(cToken.underlying()); } /** * @notice Returns the underlying balance of this contract in the cToken. * @return The cToken underlying balance for this contract. */ function balance() public returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } /** * @notice Locks the movement of tokens (essentially the committed deposits and winnings) * @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes. */ function lockTokens() public onlyAdmin { blocklock.lock(block.number); } /** * @notice Unlocks the movement of tokens (essentially the committed deposits) */ function unlockTokens() public onlyAdmin { blocklock.unlock(block.number); } /** * Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue * to collect rewards and withdraw, but eventually the Pool will grow smaller. * * emits DepositsPaused */ function pauseDeposits() public unlessDepositsPaused onlyAdmin { paused = true; emit DepositsPaused(msg.sender); } /** * @notice Unpauses all deposits into the contract * * emits DepositsUnpaused */ function unpauseDeposits() public whenDepositsPaused onlyAdmin { paused = false; emit DepositsUnpaused(msg.sender); } /** * @notice Check if the contract is locked. * @return True if the contract is locked, false otherwise */ function isLocked() public view returns (bool) { return blocklock.isLocked(block.number); } /** * @notice Returns the block number at which the lock expires * @return The block number at which the lock expires */ function lockEndAt() public view returns (uint256) { return blocklock.lockEndAt(); } /** * @notice Check cooldown end block * @return The block number at which the cooldown ends and the contract can be re-locked */ function cooldownEndAt() public view returns (uint256) { return blocklock.cooldownEndAt(); } /** * @notice Returns whether the contract can be locked * @return True if the contract can be locked, false otherwise */ function canLock() public view returns (bool) { return blocklock.canLock(block.number); } /** * @notice Duration of the lock * @return Returns the duration of the lock in blocks. */ function lockDuration() public view returns (uint256) { return blocklock.lockDuration; } /** * @notice Returns the cooldown duration. The cooldown period starts after the Pool has been unlocked. * The Pool cannot be locked during the cooldown period. * @return The cooldown duration in blocks */ function cooldownDuration() public view returns (uint256) { return blocklock.cooldownDuration; } /** * @notice requires the pool not to be locked */ modifier notLocked() { require(!blocklock.isLocked(block.number), "Pool/locked"); _; } /** * @notice requires the pool to be locked */ modifier onlyLocked() { require(blocklock.isLocked(block.number), "Pool/unlocked"); _; } /** * @notice requires the caller to be an admin */ modifier onlyAdmin() { require(admins.has(msg.sender), "Pool/admin"); _; } /** * @notice Requires an open draw to exist */ modifier requireOpenDraw() { require(currentOpenDrawId() != 0, "Pool/no-open"); _; } /** * @notice Requires deposits to be paused */ modifier whenDepositsPaused() { require(paused, "Pool/d-not-paused"); _; } /** * @notice Requires deposits not to be paused */ modifier unlessDepositsPaused() { require(!paused, "Pool/d-paused"); _; } /** * @notice Requires the caller to be the pool token */ modifier onlyToken() { require(msg.sender == address(poolToken), "Pool/only-token"); _; } /** * @notice requires the passed user's committed balance to be greater than or equal to the passed amount * @param _from The user whose committed balance should be checked * @param _amount The minimum amount they must have */ modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) { uint256 committedBalance = drawState.committedBalanceOf(_from); require(_amount <= committedBalance, "not enough funds"); _; } } contract ScdMcdMigration { SaiTubLike public tub; VatLike public vat; ManagerLike public cdpManager; JoinLike public saiJoin; JoinLike public wethJoin; JoinLike public daiJoin; constructor( address tub_, // SCD tub contract address address cdpManager_, // MCD manager contract address address saiJoin_, // MCD SAI collateral adapter contract address address wethJoin_, // MCD ETH collateral adapter contract address address daiJoin_ // MCD DAI adapter contract address ) public { tub = SaiTubLike(tub_); cdpManager = ManagerLike(cdpManager_); vat = VatLike(cdpManager.vat()); saiJoin = JoinLike(saiJoin_); wethJoin = JoinLike(wethJoin_); daiJoin = JoinLike(daiJoin_); require(wethJoin.gem() == tub.gem(), "non-matching-weth"); require(saiJoin.gem() == tub.sai(), "non-matching-sai"); tub.gov().approve(address(tub), uint(-1)); tub.skr().approve(address(tub), uint(-1)); tub.sai().approve(address(tub), uint(-1)); tub.sai().approve(address(saiJoin), uint(-1)); wethJoin.gem().approve(address(wethJoin), uint(-1)); daiJoin.dai().approve(address(daiJoin), uint(-1)); vat.hope(address(daiJoin)); } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } // Function to swap SAI to DAI // This function is to be used by users that want to get new DAI in exchange of old one (aka SAI) // wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one) function swapSaiToDai( uint wad ) external { // Get wad amount of SAI from user's wallet: saiJoin.gem().transferFrom(msg.sender, address(this), wad); // Join the SAI wad amount to the `vat`: saiJoin.join(address(this), wad); // Lock the SAI wad amount to the CDP and generate the same wad amount of DAI vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad)); // Send DAI wad amount as a ERC20 token to the user's wallet daiJoin.exit(msg.sender, wad); } // Function to swap DAI to SAI // This function is to be used by users that want to get SAI in exchange of DAI // wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP function swapDaiToSai( uint wad ) external { // Get wad amount of DAI from user's wallet: daiJoin.dai().transferFrom(msg.sender, address(this), wad); // Join the DAI wad amount to the vat: daiJoin.join(address(this), wad); // Payback the DAI wad amount and unlocks the same value of SAI collateral vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad)); // Send SAI wad amount as a ERC20 token to the user's wallet saiJoin.exit(msg.sender, wad); } // Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage. // In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio) function migrate( bytes32 cup ) external returns (uint cdp) { // Get values uint debtAmt = tub.tab(cup); // CDP SAI debt uint pethAmt = tub.ink(cup); // CDP locked collateral uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH // Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio // This is not actually a problem as this ilk will only be accessed by this migration contract, // which will make sure to have the amounts balanced out at the end of the execution. vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), -toInt(debtAmt), 0 ); saiJoin.exit(address(this), debtAmt); // SAI is exited as a token // Shut SAI CDP and gets WETH back tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call) tub.exit(pethAmt); // Converts PETH to WETH // Open future user's CDP in MCD cdp = cdpManager.open(wethJoin.ilk(), address(this)); // Join WETH to Adapter wethJoin.join(cdpManager.urns(cdp), ethAmt); // Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP (, uint rate,,,) = vat.ilks(wethJoin.ilk()); cdpManager.frob( cdp, toInt(ethAmt), toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt ); // Move DAI generated to migration contract (to recover the used funds) cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27)); // Re-balance MCD SAI migration contract's CDP vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), 0, -toInt(debtAmt) ); // Set ownership of CDP to the user cdpManager.give(cdp, msg.sender); } } /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @title MCDAwarePool * @author Brendan Asselstine [email protected] * @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to * detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai * and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for * users to encourage them to migrate to the MCD Pool. */ contract MCDAwarePool is BasePool, IERC777Recipient { IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; uint256 internal constant DEFAULT_LOCK_DURATION = 40; uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80; /** * @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts) */ ScdMcdMigration public scdMcdMigration; /** * @notice The address of the Sai Pool contract */ MCDAwarePool public saiPool; /** * @notice Initializes the contract. * @param _owner The initial administrator of the contract * @param _cToken The Compound cToken to bind this Pool to * @param _feeFraction The fraction of the winnings to give to the beneficiary * @param _feeBeneficiary The beneficiary who receives the fee */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 lockDuration, uint256 cooldownDuration ) public initializer { super.init( _owner, _cToken, _feeFraction, _feeBeneficiary, lockDuration, cooldownDuration ); initRegistry(); initBlocklock(lockDuration, cooldownDuration); } /** * @notice Used to initialize the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock. */ function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public { initRegistry(); if (blocklock.lockDuration == 0) { initBlocklock(lockDuration, cooldownDuration); } } function initRegistry() internal { ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin { _initMigration(_scdMcdMigration, _saiPool); } function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal { require(address(scdMcdMigration) == address(0), "Pool/init"); require(address(_scdMcdMigration) != address(0), "Pool/mig-def"); scdMcdMigration = _scdMcdMigration; saiPool = _saiPool; // may be null } /** * @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool * and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of * the sender. It will reject all other tokens. * * If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the * open prize. This is to encourage migration. * * @param from The sender * @param amount The amount they are transferring */ function tokensReceived( address, // operator address from, address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface uint256 amount, bytes calldata, bytes calldata ) external unlessDepositsPaused { require(msg.sender == address(saiPoolToken()), "Pool/sai-only"); require(address(token()) == address(daiToken()), "Pool/not-dai"); // cash out of the Pool. This call transfers sai to this contract saiPoolToken().redeem(amount, ''); // approve of the transfer to the migration contract saiToken().approve(address(scdMcdMigration), amount); // migrate the sai to dai. The contract now has dai scdMcdMigration.swapSaiToDai(amount); if (currentCommittedDrawId() > 0) { // now deposit the dai as tickets _depositPoolFromCommitted(from, amount); } else { _depositPoolFrom(from, amount); } } /** * @notice Returns the address of the PoolSai pool token contract * @return The address of the Sai PoolToken contract */ function saiPoolToken() internal view returns (PoolToken) { if (address(saiPool) != address(0)) { return saiPool.poolToken(); } else { return PoolToken(0); } } /** * @notice Returns the address of the Sai token * @return The address of the sai token */ function saiToken() public returns (GemLike) { return scdMcdMigration.saiJoin().gem(); } /** * @notice Returns the address of the Dai token * @return The address of the Dai token. */ function daiToken() public returns (GemLike) { return scdMcdMigration.daiJoin().dai(); } }
* Withdraws from the user's committed deposits @param _amount The amount to withdraw/
function withdrawCommittedDeposit(uint256 _amount) public nonReentrant notLocked returns (bool) { _withdrawCommittedDeposit(msg.sender, _amount); return true; }
8,015,419
[ 1, 4625, 348, 7953, 560, 30, 380, 3423, 9446, 87, 628, 326, 729, 1807, 16015, 443, 917, 1282, 632, 891, 389, 8949, 1021, 3844, 358, 598, 9446, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 9446, 27813, 758, 1724, 12, 11890, 5034, 389, 8949, 13, 1071, 1661, 426, 8230, 970, 486, 8966, 1135, 261, 6430, 13, 225, 288, 203, 565, 389, 1918, 9446, 27813, 758, 1724, 12, 3576, 18, 15330, 16, 389, 8949, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xDf0dbc66f85979a1d54671c4D9e439F306Be27EE/sources/_mean-finance/dca-v2-periphery/contracts/libraries/InputBuilding.sol
Load sorted into new array
_tokens = new address[](_uniqueTokens);
9,345,551
[ 1, 4625, 348, 7953, 560, 30, 225, 4444, 3115, 1368, 394, 526, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 7860, 273, 394, 1758, 8526, 24899, 6270, 5157, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 pragma solidity ^0.8.0; /** * Contract for administering the Airdrop of RIP. * 500,000 RIP will be made available via the Airdrop. */ contract Airdrop { // token addresses address public rip; address public owner; address public remainderDestination; // amount of RIP to transfer mapping (address => uint96) public withdrawAmount; uint public totalAllocated; bool public claimingAllowed; // Giving away 500,000 rip uint constant public TOTAL_AIRDROP_SUPPLY = 500_000e18; // Events event ClaimingAllowed(); event ClaimingOver(); event RipClaimed(address claimer, uint amount); /** * Initializes the contract. Sets token addresses, owner, and leftover token * destination. Claiming period is not enabled. * * @param rip_ the rip token contract address * @param owner_ the privileged contract owner * @param remainderDestination_ address to transfer remaining rip to when * claiming ends. Should be community treasury. */ constructor(address rip_, address owner_, address remainderDestination_) { rip = rip_; owner = owner_; remainderDestination = remainderDestination_; claimingAllowed = false; totalAllocated = 0; } /** * Changes the address that receives the remaining rip at the end of the * claiming period. Can only be set by the contract owner. * * @param remainderDestination_ address to transfer remaining rip to when * claiming ends. */ function setRemainderDestination(address remainderDestination_) external { require(msg.sender == owner, 'Airdrop::setRemainderDestination: unauthorized'); remainderDestination = remainderDestination_; } /** * Changes the contract owner. Can only be set by the contract owner. * * @param owner_ new contract owner address */ function setowner(address owner_) external { require(msg.sender == owner, 'Airdrop::setowner: unauthorized'); owner = owner_; } /** * Enable the claiming period and allow user to claim rip. Before activation, * this contract must have a rip balance equal to the total airdrop rip * supply of 500,000 RIP. All claimable RIP tokens must be whitelisted * before claiming is enabled. Only callable by the owner. */ function allowClaiming() external { require(IRIP(rip).balanceOf(address(this)) >= TOTAL_AIRDROP_SUPPLY, 'Airdrop::allowClaiming: incorrect rip supply'); require(msg.sender == owner, 'Airdrop::allowClaiming: unauthorized'); claimingAllowed = true; emit ClaimingAllowed(); } /** * End the claiming period. All unclaimed rip will be transferred to the address * specified by remainderDestination. Can only be called by the owner. */ function endClaiming() external { require(msg.sender == owner, 'Airdrop::endClaiming: unauthorized'); require(claimingAllowed, "Airdrop::endClaiming: Claiming not started"); claimingAllowed = false; emit ClaimingOver(); // Transfer remainder uint amount = IRIP(rip).balanceOf(address(this)); require(IRIP(rip).transfer(remainderDestination, amount), 'Airdrop::endClaiming: Transfer failed'); } /** * Withdraw your RIP. In order to qualify for a withdrawl, the caller's address * must be whitelisted. All RIP must be claimed at once. Only the full amount can be * claimed and only one claim is allowed per user. */ function claim() external { // tradeoff: if you only transfer one but you held both, you can't claim require(claimingAllowed, 'Airdrop::claim: Claiming is not allowed'); uint amountToClaim = withdrawAmount[msg.sender]; withdrawAmount[msg.sender] = 0; emit RipClaimed(msg.sender, amountToClaim); require(IRIP(rip).transfer(msg.sender, amountToClaim), 'Airdrop::claim: Transfer failed'); } /** * Whitelist an address to claim RIP. Specify the amount of RIP to be allocated. * That address will then be able to claim that amount of rip during the claiming * period. The transferrable amount of * rip must be nonzero. Total amount allocated must be less than or equal to the * total airdrop supply. Whitelisting must occur before the claiming period is * enabled. Addresses may only be added one time. Only called by the owner. * * @param addr address that may claim rip * @param ripOut the amount of rip that addr may withdraw */ function whitelistAddress(address addr, uint96 ripOut) public { require(msg.sender == owner, 'Airdrop::whitelistAddress: unauthorized'); require(!claimingAllowed, 'Airdrop::whitelistAddress: claiming in session'); require(ripOut > 0, 'Airdrop::whitelistAddress: No rip to allocated'); require(withdrawAmount[addr] == 0, 'Airdrop::whitelistAddress: address already added'); withdrawAmount[addr] = ripOut; totalAllocated = totalAllocated + ripOut; require(totalAllocated <= TOTAL_AIRDROP_SUPPLY, 'Airdrop::whitelistAddress: Exceeds rip allocation'); } /** * Whitelist multiple addresses in one call. Wrapper around whitelistAddress. * All parameters are arrays. Each array must be the same length. Each index * corresponds to one (address, rip) tuple. Only callable by the owner. */ function whitelistAddresses(address[] memory addrs, uint96 ripOut) external { require(msg.sender == owner, 'Airdrop::whitelistAddresses: unauthorized'); for (uint i = 0; i < addrs.length; i++) { whitelistAddress(addrs[i], ripOut); } } } interface IRIP { function balanceOf(address account) external view returns (uint); function transfer(address dst, uint rawAmount) external returns (bool); }
* Initializes the contract. Sets token addresses, owner, and leftover token destination. Claiming period is not enabled. @param rip_ the rip token contract address @param owner_ the privileged contract owner @param remainderDestination_ address to transfer remaining rip to when claiming ends. Should be community treasury./
address remainderDestination_) { rip = rip_; owner = owner_; remainderDestination = remainderDestination_; claimingAllowed = false; totalAllocated = 0; }
1,009,748
[ 1, 4625, 348, 7953, 560, 30, 380, 10188, 3128, 326, 6835, 18, 11511, 1147, 6138, 16, 3410, 16, 471, 29709, 1147, 2929, 18, 18381, 310, 3879, 353, 486, 3696, 18, 632, 891, 436, 625, 67, 326, 436, 625, 1147, 6835, 1758, 632, 891, 3410, 67, 326, 11334, 2423, 6835, 3410, 632, 891, 10022, 5683, 67, 1758, 358, 7412, 4463, 436, 625, 358, 1347, 377, 7516, 310, 3930, 18, 9363, 506, 19833, 9787, 345, 22498, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 1758, 10022, 5683, 67, 13, 288, 203, 3639, 436, 625, 273, 436, 625, 67, 31, 203, 3639, 3410, 273, 3410, 67, 31, 203, 3639, 10022, 5683, 273, 10022, 5683, 67, 31, 203, 3639, 7516, 310, 5042, 273, 629, 31, 203, 3639, 2078, 29392, 273, 374, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.13; import './MadMouseTroupe.sol'; import './MadMouseStaking.sol'; import './lib/Ownable.sol'; contract MadMouseTroupeMetadata is Ownable { using Strings for uint256; MadMouseTroupe public madmouseTroupe; MadMouseTroupeMetadata public metadataGenesis; string specialURI; string constant unrevealedURI = 'ipfs://QmW9NKUGYesTiYx5iSP1o82tn4Chq9i1yQV6DBnzznrHTH'; function setMadMouseAddress(MadMouseTroupe madmouseTroupe_, MadMouseTroupeMetadata metadataGenesis_) external onlyOwner { metadataGenesis = metadataGenesis_; madmouseTroupe = madmouseTroupe_; } function setSpecialURI(string calldata uri) external onlyOwner { specialURI = uri; } // will act as an ERC721 proxy function balanceOf(address user) external view returns (uint256) { return madmouseTroupe.numOwned(user); } // reuse metadata build from genesis collection function buildMouseMetadata(uint256 tokenId, uint256 level) external returns (string memory) { if (tokenId > 30) { (, bytes memory data) = address(metadataGenesis).delegatecall( abi.encodeWithSelector(this.buildMouseMetadata.selector, tokenId, level) ); return abi.decode(data, (string)); } return bytes(specialURI).length != 0 ? string.concat(specialURI, tokenId.toString()) : unrevealedURI; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.13; // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM`MMM NMM MMM MMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMhMMMMMMM MMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMM MM-MMMMM MMMM MMMM lMMMDMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMM jMMMMl MM MMM M MMM M MMMM MMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMM MMMMMMMMM , ` M Y MM MMM BMMMMMM MMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMM MMMMMMMMMMMM IM MM l MMM X MM. MMMMMMMMMM MMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.nlMMMMMMMMMMMMMMMMM]._ MMMMMMMMMMMMMMMNMMMMMMMMMMMMMM // MMMMMMMMMMMMMM TMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMM: rMMMMMMMMN MMMMMMMMMMMMMM // MMMMMMMMMMMM MMMMMMMMMMMMMMMM MMMMMM MMMMMMMM qMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMM^ MMMb .MMMMMMMMMMMMMMMMMMM // MMMMMMMMMM MMMMMMMMMMMMMMM MM MMMMMMM MMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMM M gMMMMMMMMMMMMMMMMM // MMMMMMMMu MMMMMMMMMMMMMMM MMMMMMM .MMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMM :MMMMMMMMMMMMMMMM // MMMMMMM^ MMMMMMMMMMMMMMMl MMMMMMMM MMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMM // MMMMMMM MMMMMMMMMMMMMMMM MMMMMMMM MMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMM // MMMMMMr MMMMMMMMMMMMMMMM MMMMMMMM .MMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMM // MMMMMMM MMMMMMMMMMMMMMMMM DMMMMMMMMMM MMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMM|`MMMMMMMMMMMMMMMM q MMMMMMMMMMMMMMMMMMM MMMMMMM // MMMMMMMMMTMMMMMMMMMMMMMMM qMMMMMMMMMMMMMMMMMMgMMMMMMMMM // MMMMMMMMq MMMMMMMMMMMMMMMh jMMMMMMMMMMMMMMMMMMM nMMMMMMMM // MMMMMMMMMM MMMMMMMMMMMMMMMQ nc -MMMMMn MMMMMMMMMMMMMMMMMMMM MMMMMMMMMM // MMMMMMMMMM.MMMMMMMMMMMMMMMMMMl M1 `MMMMMMMMMMMMMMMMMMMMMMrMMMMMMMMMM // MMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMM :MMMMMMMMMM MMMMMMMMMMMM qMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMX MMMMMMMMMMMMMMM uMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMM DMMMMMMMMM IMMMMMMMMMMMMMMMMMMMMMMM M Y MMMMMMMN MMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMM MMMMMM `` M MM MMM , MMMM Mv MMM MMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMM MMh Ml . M MMMM I MMMT M :M ,MMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMM MMMMMMMMt MM MMMMB m ]MMM MMMM MMMMMM MMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMM MMMMM MMM TM MM 9U .MM _MMMMM MMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMM YMMMMMMMn MMMM +MMMMMMM1`MMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.`MMM MMM MMMMM`.MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MM M M M M M______ ____ ___ __ __ ____ ___ M M M M M M MM // MM M M M M M| || \ / \ | | || \ / _] M M M M M M MM // MM M M M M M | || D ) || | || o ) [_ M M M M M M MM // MM M M M M M M|_| |_|| /| O || | || _/ _] M M M M M MMM // MM M M M M M M | | | \| || : || | | [_ M M M M M M MM // MMM M M M M M | | | . \ || || | | | M M M M M MMM // MM M M M M M |__| |__|\_|\___/ \__,_||__| |_____|M M M M M M MM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM author: phaze MMM import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; import './lib/Ownable.sol'; import {VRFBaseMainnet as VRFBase} from './lib/VRFBase.sol'; import './Gouda.sol'; import './MadMouseStaking.sol'; error PublicSaleNotActive(); error WhitelistNotActive(); error InvalidAmount(); error ExceedsLimit(); error SignatureExceedsLimit(); error IncorrectValue(); error InvalidSignature(); error ContractCallNotAllowed(); error InvalidString(); error MaxLevelReached(); error MaxNumberReached(); error MinHoldDurationRequired(); error IncorrectHash(); error CollectionAlreadyRevealed(); error CollectionNotRevealed(); error TokenDataAlreadySet(); error MintAndStakeMinHoldDurationNotReached(); interface IMadMouseMetadata { function buildMouseMetadata(uint256 tokenId, uint256 level) external view returns (string memory); } contract MadMouseTroupe is Ownable, MadMouseStaking, VRFBase { using ECDSA for bytes32; using UserDataOps for uint256; using TokenDataOps for uint256; using DNAOps for uint256; bool public publicSaleActive; uint256 constant MAX_SUPPLY = 5000; uint256 constant MAX_PER_WALLET = 50; uint256 constant PURCHASE_LIMIT = 3; uint256 constant whitelistPrice = 0.075 ether; address public metadata; address public multiSigTreasury = 0xFB79a928C5d6c5932Ba83Aa8C7145cBDCDb9fd2E; address signerAddress = 0x3ADE0c5e35cbF136245F4e4bBf4563BD151d39D1; uint256 public totalLevel2Reached; uint256 public totalLevel3Reached; uint256 constant LEVEL_2_COST = 120 * 1e18; uint256 constant LEVEL_3_COST = 350 * 1e18; uint256 constant MAX_NUM_LEVEL_2 = 3300; uint256 constant MAX_NUM_LEVEL_3 = 1200; uint256 constant NAME_CHANGE_COST = 25 * 1e18; uint256 constant BIO_CHANGE_COST = 15 * 1e18; uint256 constant MAX_LEN_NAME = 20; uint256 constant MAX_LEN_BIO = 35; uint256 constant MINT_AND_STAKE_MIN_HOLD_DURATION = 3 days; uint256 profileUpdateMinHoldDuration = 30 days; mapping(uint256 => string) public mouseName; mapping(uint256 => string) public mouseBio; string public description; string public imagesBaseURI; string constant unrevealedURI = 'ipfs://QmW9NKUGYesTiYx5iSP1o82tn4Chq9i1yQV6DBnzznrHTH'; bool private revealed; bytes32 immutable secretHash; constructor(bytes32 secretHash_) MadMouseStaking(MAX_SUPPLY, MAX_PER_WALLET) { secretHash = secretHash_; _mintAndStake(msg.sender, 30, false); } /* ------------- External ------------- */ function mint(uint256 amount, bool stake) external payable noContract { if (!publicSaleActive) revert PublicSaleNotActive(); if (PURCHASE_LIMIT < amount) revert ExceedsLimit(); uint256 price_ = price(); if (msg.value != price_ * amount) revert IncorrectValue(); if (price_ == 0) { // free mints will at first be restricted to purchase limit uint256 numMinted = _userData[msg.sender].numMinted(); if (numMinted + amount > PURCHASE_LIMIT) revert ExceedsLimit(); // free mints > 1 will be staked if (amount != 1) stake = true; } _mintAndStake(msg.sender, amount, stake); } function whitelistMint( uint256 amount, uint256 limit, bytes calldata signature, bool stake ) external payable noContract { if (publicSaleActive) revert WhitelistNotActive(); if (!validSignature(signature, limit)) revert InvalidSignature(); uint256 numMinted = _userData[msg.sender].numMinted(); if (numMinted + amount > limit) revert ExceedsLimit(); _mintAndStake(msg.sender, amount, stake); } function levelUp(uint256 tokenId) external payable { uint256 tokenData = _tokenDataOf(tokenId); address owner = tokenData.trueOwner(); if (owner != msg.sender) revert IncorrectOwner(); uint256 level = tokenData.level(); if (level > 2) revert MaxLevelReached(); if (level == 1) { if (totalLevel2Reached >= MAX_NUM_LEVEL_2) revert MaxNumberReached(); gouda.burnFrom(msg.sender, LEVEL_2_COST); ++totalLevel2Reached; } else { if (totalLevel3Reached >= MAX_NUM_LEVEL_3) revert MaxNumberReached(); gouda.burnFrom(msg.sender, LEVEL_3_COST); ++totalLevel3Reached; } uint256 newTokenData = tokenData.increaseLevel().resetOwnerCount(); if (tokenData.staked() && revealed) { uint256 userData = _claimReward(); (userData, newTokenData) = updateDataWhileStaked(userData, tokenId, tokenData, newTokenData); _userData[msg.sender] = userData; } _tokenData[tokenId] = newTokenData; } function setName(uint256 tokenId, string calldata name) external payable onlyLongtermHolder(tokenId) { if (!isValidString(name, MAX_LEN_NAME)) revert InvalidString(); gouda.burnFrom(msg.sender, NAME_CHANGE_COST); mouseName[tokenId] = name; } function setBio(uint256 tokenId, string calldata bio) external payable onlyLongtermHolder(tokenId) { if (!isValidString(bio, MAX_LEN_BIO)) revert InvalidString(); gouda.burnFrom(msg.sender, BIO_CHANGE_COST); mouseBio[tokenId] = bio; } // only to be used by owner in extreme cases when these reflect negatively on the collection // since they are automatically shown in the metadata (on OpenSea) function resetName(uint256 tokenId) external payable { address _owner = _tokenDataOf(tokenId).trueOwner(); if (_owner != msg.sender && owner() != msg.sender) revert IncorrectOwner(); delete mouseName[tokenId]; } function resetBio(uint256 tokenId) external payable { address _owner = _tokenDataOf(tokenId).trueOwner(); if (_owner != msg.sender && owner() != msg.sender) revert IncorrectOwner(); delete mouseBio[tokenId]; } /* ------------- View ------------- */ function price() public view returns (uint256) { return totalSupply < 3500 ? 0 ether : .02 ether; } function tokenURI(uint256 tokenId) public view override returns (string memory) { if (!_exists(tokenId)) revert NonexistentToken(); if (!revealed || address(metadata) == address(0)) return unrevealedURI; return IMadMouseMetadata(address(metadata)).buildMouseMetadata(tokenId, this.getLevel(tokenId)); } function previewTokenURI(uint256 tokenId, uint256 level) external view returns (string memory) { if (!_exists(tokenId)) revert NonexistentToken(); if (!revealed || address(metadata) == address(0)) return unrevealedURI; return IMadMouseMetadata(address(metadata)).buildMouseMetadata(tokenId, level); } function getDNA(uint256 tokenId) external view onceRevealed returns (uint256) { if (!_exists(tokenId)) revert NonexistentToken(); return computeDNA(tokenId); } function getLevel(uint256 tokenId) external view returns (uint256) { return _tokenDataOf(tokenId).level(); } /* ------------- Private ------------- */ function validSignature(bytes calldata signature, uint256 limit) private view returns (bool) { bytes32 msgHash = keccak256(abi.encode(address(this), msg.sender, limit)); return msgHash.toEthSignedMessageHash().recover(signature) == signerAddress; } // not guarded for reveal function computeDNA(uint256 tokenId) private view returns (uint256) { return uint256(keccak256(abi.encodePacked(randomSeed, tokenId))); } /* ------------- Owner ------------- */ function setPublicSaleActive(bool active) external payable onlyOwner { publicSaleActive = active; } function setProfileUpdateMinHoldDuration(uint256 duration) external payable onlyOwner { profileUpdateMinHoldDuration = duration; } function giveAway(address[] calldata to, uint256[] calldata amounts) external payable onlyOwner { for (uint256 i; i < to.length; ++i) _mintAndStake(to[i], amounts[i], false); } function setSignerAddress(address address_) external payable onlyOwner { signerAddress = address_; } function setMetadataAddress(address metadata_) external payable onlyOwner { metadata = metadata_; } function withdraw() external payable onlyOwner { uint256 balance = address(this).balance; multiSigTreasury.call{value: balance}(''); } function recoverToken(IERC20 token) external payable onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } function setDescription(string memory description_) external payable onlyOwner { description = description_; } // requires that the reveal is first done through chainlink vrf function setImagesBaseURI(string memory uri) external payable onlyOwner onceRevealed { imagesBaseURI = uri; } // extra security for reveal: // the owner sets a hash of a secret seed // once chainlink randomness fulfills, the secret is revealed and shifts the secret seed set by chainlink // Why? The final randomness should come from a trusted third party, // however devs need time to generate the collection from the metadata. // There is a time-frame in which an unfair advantage is gained after the seed is set and before the metadata is revealed. // This eliminates any possibility of the team generating an unfair seed and any unfair advantage by snipers. function reveal(string memory _imagesBaseURI, bytes32 secretSeed_) external payable onlyOwner whenRandomSeedSet { if (revealed) revert CollectionAlreadyRevealed(); if (secretHash != keccak256(abi.encode(secretSeed_))) revert IncorrectHash(); revealed = true; imagesBaseURI = _imagesBaseURI; _shiftRandomSeed(uint256(secretSeed_)); } /* ------------- Hooks ------------- */ // update role, level information when staking function _beforeStakeDataTransform( uint256 tokenId, uint256 userData, uint256 tokenData ) internal view override returns (uint256, uint256) { // assumption that mint&stake won't have revealed yet if (!tokenData.mintAndStake() && tokenData.role() == 0 && revealed) tokenData = tokenData.setRoleAndRarity(computeDNA(tokenId)); userData = userData.updateUserDataStake(tokenData); return (userData, tokenData); } function _beforeUnstakeDataTransform( uint256, uint256 userData, uint256 tokenData ) internal view override returns (uint256, uint256) { userData = userData.updateUserDataUnstake(tokenData); if (tokenData.mintAndStake() && block.timestamp - tokenData.lastTransfer() < MINT_AND_STAKE_MIN_HOLD_DURATION) revert MintAndStakeMinHoldDurationNotReached(); return (userData, tokenData); } function updateStakedTokenData(uint256[] calldata tokenIds) external payable onceRevealed { uint256 userData = _claimReward(); uint256 tokenId; uint256 tokenData; for (uint256 i; i < tokenIds.length; ++i) { tokenId = tokenIds[i]; tokenData = _tokenDataOf(tokenId); if (tokenData.trueOwner() != msg.sender) revert IncorrectOwner(); if (!tokenData.staked()) revert TokenIdUnstaked(); // only useful for staked ids if (tokenData.role() != 0) revert TokenDataAlreadySet(); (userData, tokenData) = updateDataWhileStaked(userData, tokenId, tokenData, tokenData); _tokenData[tokenId] = tokenData; } _userData[msg.sender] = userData; } // note: must be guarded by check for revealed function updateDataWhileStaked( uint256 userData, uint256 tokenId, uint256 oldTokenData, uint256 newTokenData ) private view returns (uint256, uint256) { uint256 userDataX; // add in the role and rarity data if not already uint256 tokenDataX = newTokenData.role() != 0 ? newTokenData : newTokenData.setRoleAndRarity(computeDNA(tokenId)); // update userData as if to unstake with old tokenData and stake with new tokenData userDataX = userData.updateUserDataUnstake(oldTokenData).updateUserDataStake(tokenDataX); return applySafeDataTransform(userData, newTokenData, userDataX, tokenDataX); } // simulates a token update and only returns ids != 0 if // the user gets a bonus increase upon updating staked data function shouldUpdateStakedIds(address user) external view returns (uint256[] memory) { if (!revealed) return new uint256[](0); uint256[] memory stakedIds = this.tokenIdsOf(user, 1); uint256 userData = _userData[user]; uint256 oldTotalBonus = totalBonus(user, userData); uint256 tokenData; for (uint256 i; i < stakedIds.length; ++i) { tokenData = _tokenDataOf(stakedIds[i]); if (tokenData.role() == 0) (userData, ) = updateDataWhileStaked(userData, stakedIds[i], tokenData, tokenData); else stakedIds[i] = 0; } uint256 newTotalBonus = totalBonus(user, userData); return (newTotalBonus > oldTotalBonus) ? stakedIds : new uint256[](0); } /* ------------- Modifier ------------- */ modifier onceRevealed() { if (!revealed) revert CollectionNotRevealed(); _; } modifier noContract() { if (tx.origin != msg.sender) revert ContractCallNotAllowed(); _; } modifier onlyLongtermHolder(uint256 tokenId) { uint256 tokenData = _tokenDataOf(tokenId); uint256 timeHeld = block.timestamp - tokenData.lastTransfer(); if (tokenData.trueOwner() != msg.sender) revert IncorrectOwner(); if (timeHeld < profileUpdateMinHoldDuration) revert MinHoldDurationRequired(); _; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './Gouda.sol'; import './lib/ERC721M.sol'; import './lib/Ownable.sol'; error InvalidBoostToken(); error TransferFailed(); error BoostInEffect(); error NotSpecialGuestOwner(); error SpecialGuestIndexMustDiffer(); abstract contract MadMouseStaking is ERC721M, Ownable { using UserDataOps for uint256; event BoostActivation(address token); Gouda public gouda; uint256 constant dailyReward = 0.3 * 1e18; uint256 constant ROLE_BONUS_3 = 2000; uint256 constant ROLE_BONUS_5 = 3500; uint256 constant TOKEN_BONUS = 1000; uint256 constant TIME_BONUS = 1000; uint256 constant RARITY_BONUS = 1000; uint256 constant OG_BONUS = 2000; uint256 constant SPECIAL_GUEST_BONUS = 1000; uint256 immutable OG_BONUS_END; uint256 immutable LAST_GOUDA_EMISSION_DATE; uint256 constant TOKEN_BOOST_DURATION = 9 days; uint256 constant TOKEN_BOOST_COOLDOWN = 9 days; uint256 constant TIME_BONUS_STAKE_DURATION = 30 days; mapping(IERC20 => uint256) tokenBoostCosts; mapping(uint256 => IERC721) specialGuests; mapping(IERC721 => bytes4) specialGuestsNumStakedSelector; address constant burnAddress = 0x000000000000000000000000000000000000dEaD; constructor(uint256 maxSupply_, uint256 maxPerWallet_) ERC721M('MadMouseCircus', 'MMC', 1, maxSupply_, maxPerWallet_) { OG_BONUS_END = block.timestamp + 60 days; LAST_GOUDA_EMISSION_DATE = block.timestamp + 5 * 365 days; } /* ------------- External ------------- */ function burnForBoost(IERC20 token) external payable { uint256 userData = _claimReward(); uint256 boostCost = tokenBoostCosts[token]; if (boostCost == 0) revert InvalidBoostToken(); bool success = token.transferFrom(msg.sender, burnAddress, boostCost); if (!success) revert TransferFailed(); uint256 boostStart = userData.boostStart(); if (boostStart + TOKEN_BOOST_DURATION + TOKEN_BOOST_COOLDOWN > block.timestamp) revert BoostInEffect(); _userData[msg.sender] = userData.setBoostStart(block.timestamp); emit BoostActivation(address(token)); } function claimSpecialGuest(uint256 collectionIndex) external payable { uint256 userData = _claimReward(); uint256 specialGuestIndexOld = userData.specialGuestIndex(); if (collectionIndex == specialGuestIndexOld) revert SpecialGuestIndexMustDiffer(); if (collectionIndex != 0 && !hasSpecialGuest(msg.sender, collectionIndex)) revert NotSpecialGuestOwner(); _userData[msg.sender] = userData.setSpecialGuestIndex(collectionIndex); } function clearSpecialGuestData() external payable { _userData[msg.sender] = _userData[msg.sender].setSpecialGuestIndex(0); } /* ------------- Internal ------------- */ function tokenBonus(uint256 userData) private view returns (uint256) { unchecked { uint256 lastClaimed = userData.lastClaimed(); uint256 boostEnd = userData.boostStart() + TOKEN_BOOST_DURATION; if (lastClaimed > boostEnd) return 0; if (block.timestamp <= boostEnd) return TOKEN_BONUS; // follows: lastClaimed <= boostEnd < block.timestamp // user is half-way through running out of boost, calculate exact fraction, // as if claim was initiated once at end of boost and once now // bonus * (time delta spent with boost bonus) / (complete duration) return (TOKEN_BONUS * (boostEnd - lastClaimed)) / (block.timestamp - lastClaimed); } } function roleBonus(uint256 userData) private pure returns (uint256) { uint256 numRoles = userData.uniqueRoleCount(); return numRoles < 3 ? 0 : numRoles < 5 ? ROLE_BONUS_3 : ROLE_BONUS_5; } function rarityBonus(uint256 userData) private pure returns (uint256) { unchecked { uint256 numStaked = userData.numStaked(); return numStaked == 0 ? 0 : (userData.rarityPoints() * RARITY_BONUS) / numStaked; } } function OGBonus(uint256 userData) private view returns (uint256) { unchecked { uint256 count = userData.OGCount(); uint256 lastClaimed = userData.lastClaimed(); if (count == 0 || lastClaimed > OG_BONUS_END) return 0; // follows: 0 < count <= numStaked uint256 bonus = (count * OG_BONUS) / userData.numStaked(); if (block.timestamp <= OG_BONUS_END) return bonus; // follows: lastClaimed <= OG_BONUS_END < block.timestamp return (bonus * (OG_BONUS_END - lastClaimed)) / (block.timestamp - lastClaimed); } } function timeBonus(uint256 userData) private view returns (uint256) { unchecked { uint256 stakeStart = userData.stakeStart(); uint256 stakeBonusStart = stakeStart + TIME_BONUS_STAKE_DURATION; if (block.timestamp < stakeBonusStart) return 0; uint256 lastClaimed = userData.lastClaimed(); if (lastClaimed >= stakeBonusStart) return TIME_BONUS; // follows: lastClaimed < stakeBonusStart <= block.timestamp return (TIME_BONUS * (block.timestamp - stakeBonusStart)) / (block.timestamp - lastClaimed); } } function hasSpecialGuest(address user, uint256 index) public view returns (bool) { if (index == 0) return false; // first 18 addresses are hardcoded to save gas if (index < 19) { address[19] memory guests = [ 0x0000000000000000000000000000000000000000, // 0: reserved 0x4BB33f6E69fd62cf3abbcC6F1F43b94A5D572C2B, // 1: Bears Deluxe 0xbEA8123277142dE42571f1fAc045225a1D347977, // 2: DystoPunks 0x12d2D1beD91c24f878F37E66bd829Ce7197e4d14, // 3: Galactic Apes 0x0c2E57EFddbA8c768147D1fdF9176a0A6EBd5d83, // 4: Kaiju Kingz 0x6E5a65B5f9Dd7b1b08Ff212E210DCd642DE0db8B, // 5: Octohedz 0x17eD38f5F519C6ED563BE6486e629041Bed3dfbC, // 6: PXQuest Adventurer 0xdd67892E722bE69909d7c285dB572852d5F8897C, // 7: Scholarz 0x8a90CAb2b38dba80c64b7734e58Ee1dB38B8992e, // 8: Doodles 0x6F44Db5ed6b86d9cC6046D0C78B82caD9E600F6a, // 9: Digi Dragonz 0x219B8aB790dECC32444a6600971c7C3718252539, // 10: Sneaky Vampire Syndicate 0xC4a0b1E7AA137ADA8b2F911A501638088DFdD508, // 11: Uninterested Unicorns 0x9712228cEeDA1E2dDdE52Cd5100B88986d1Cb49c, // 12: Wulfz 0x56b391339615fd0e88E0D370f451fA91478Bb20F, // 13: Ethalien 0x648E8428e0104Ec7D08667866a3568a72Fe3898F, // 14: Dysto Apez 0xd2F668a8461D6761115dAF8Aeb3cDf5F40C532C6, // 15: Karafuru 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731, // 16: Anonymice 0xcB4307F1c3B5556256748DDF5B86E81258990B3C, // 17: The Other Side 0x5c211B8E4f93F00E2BD68e82F4E00FbB3302b35c // 18: Global Citizen Club ]; if (IERC721(guests[index]).balanceOf(user) != 0) return true; if (index == 10) return ISVSGraveyard(guests[index]).getBuriedCount(user) != 0; else if (index == 12) return AWOO(guests[index]).getStakedAmount(user) != 0; else if (index == 16) return CheethV2(guests[index]).stakedMiceQuantity(user) != 0; } else { IERC721 collection = specialGuests[index]; if (address(collection) != address(0)) { if (collection.balanceOf(user) != 0) return true; bytes4 selector = specialGuestsNumStakedSelector[collection]; if (selector != bytes4(0)) { (bool success, bytes memory data) = address(collection).staticcall( abi.encodeWithSelector(selector, user) ); return success && abi.decode(data, (uint256)) != 0; } } } return false; } function specialGuestBonus(address user, uint256 userData) private view returns (uint256) { uint256 index = userData.specialGuestIndex(); if (!hasSpecialGuest(user, index)) return 0; return SPECIAL_GUEST_BONUS; } function _pendingReward(address user, uint256 userData) internal view override returns (uint256) { uint256 lastClaimed = userData.lastClaimed(); if (lastClaimed == 0) return 0; uint256 timestamp = min(LAST_GOUDA_EMISSION_DATE, block.timestamp); unchecked { uint256 delta = timestamp < lastClaimed ? 0 : timestamp - lastClaimed; uint256 reward = (userData.baseReward() * delta * dailyReward) / (1 days); if (reward == 0) return 0; uint256 bonus = totalBonus(user, userData); // needs to be calculated per myriad for more accuracy return (reward * (10000 + bonus)) / 10000; } } function totalBonus(address user, uint256 userData) internal view returns (uint256) { unchecked { return roleBonus(userData) + specialGuestBonus(user, userData) + rarityBonus(userData) + OGBonus(userData) + timeBonus(userData) + tokenBonus(userData); } } function _payoutReward(address user, uint256 reward) internal override { if (reward != 0) gouda.mint(user, reward); } /* ------------- View ------------- */ // for convenience struct StakeInfo { uint256 numStaked; uint256 roleCount; uint256 roleBonus; uint256 specialGuestBonus; uint256 tokenBoost; uint256 stakeStart; uint256 timeBonus; uint256 rarityPoints; uint256 rarityBonus; uint256 OGCount; uint256 OGBonus; uint256 totalBonus; uint256 multiplierBase; uint256 dailyRewardBase; uint256 dailyReward; uint256 pendingReward; int256 tokenBoostDelta; uint256[3] levelBalances; } // calculates momentary totalBonus for display instead of effective bonus function getUserStakeInfo(address user) external view returns (StakeInfo memory info) { unchecked { uint256 userData = _userData[user]; info.numStaked = userData.numStaked(); info.roleCount = userData.uniqueRoleCount(); info.roleBonus = roleBonus(userData) / 100; info.specialGuestBonus = specialGuestBonus(user, userData) / 100; info.tokenBoost = (block.timestamp < userData.boostStart() + TOKEN_BOOST_DURATION) ? TOKEN_BONUS / 100 : 0; info.stakeStart = userData.stakeStart(); info.timeBonus = (info.stakeStart > 0 && block.timestamp > userData.stakeStart() + TIME_BONUS_STAKE_DURATION) ? TIME_BONUS / 100 : 0; info.OGCount = userData.OGCount(); info.OGBonus = (block.timestamp > OG_BONUS_END || userData.numStaked() == 0) ? 0 : (userData.OGCount() * OG_BONUS) / userData.numStaked() / 100; info.rarityPoints = userData.rarityPoints(); info.rarityBonus = rarityBonus(userData) / 100; info.totalBonus = info.roleBonus + info.specialGuestBonus + info.tokenBoost + info.timeBonus + info.rarityBonus + info.OGBonus; info.multiplierBase = userData.baseReward(); info.dailyRewardBase = info.multiplierBase * dailyReward; info.dailyReward = (info.dailyRewardBase * (100 + info.totalBonus)) / 100; info.pendingReward = _pendingReward(user, userData); info.tokenBoostDelta = int256(TOKEN_BOOST_DURATION) - int256(block.timestamp - userData.boostStart()); info.levelBalances = userData.levelBalances(); } } /* ------------- Owner ------------- */ function setGoudaToken(Gouda gouda_) external payable onlyOwner { gouda = gouda_; } function setSpecialGuests(IERC721[] calldata collections, uint256[] calldata indices) external payable onlyOwner { for (uint256 i; i < indices.length; ++i) { uint256 index = indices[i]; require(index != 0); specialGuests[index] = collections[i]; } } function setSpecialGuestStakingSelector(IERC721 collection, bytes4 selector) external payable onlyOwner { specialGuestsNumStakedSelector[collection] = selector; } function setBoostTokens(IERC20[] calldata _boostTokens, uint256[] calldata _boostCosts) external payable onlyOwner { for (uint256 i; i < _boostTokens.length; ++i) tokenBoostCosts[_boostTokens[i]] = _boostCosts[i]; } } // Special guest's staking interfaces interface ISVSGraveyard { function getBuriedCount(address burier) external view returns (uint256); } interface AWOO { function getStakedAmount(address staker) external view returns (uint256); } interface CheethV2 { function stakedMiceQuantity(address _address) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; error CallerIsNotTheOwner(); abstract contract Ownable { address _owner; constructor() { _owner = msg.sender; } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { if (msg.sender != _owner) revert CallerIsNotTheOwner(); _; } function transferOwnership(address newOwner) external onlyOwner { _owner = newOwner; } } // 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 (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@chainlink/contracts/src/v0.8/VRFConsumerBase.sol'; import './Ownable.sol'; error RandomSeedNotSet(); error RandomSeedAlreadySet(); contract VRFBase is VRFConsumerBase, Ownable { bytes32 private immutable keyHash; uint256 private immutable fee; uint256 public randomSeed; constructor( bytes32 keyHash_, uint256 fee_, address vrfCoordinator_, address link_ ) VRFConsumerBase(vrfCoordinator_, link_) { keyHash = keyHash_; fee = fee_; } /* ------------- Owner ------------- */ function requestRandomSeed() external payable virtual onlyOwner whenRandomSeedUnset { requestRandomness(keyHash, fee); } // this function should not be needed and is just an emergency fail-safe if // for some reason chainlink is not able to fulfill the randomness callback function forceFulfillRandomness() external payable virtual onlyOwner whenRandomSeedUnset { randomSeed = uint256(blockhash(block.number - 1)); } /* ------------- Internal ------------- */ function fulfillRandomness(bytes32, uint256 randomNumber) internal virtual override { randomSeed = randomNumber; } function _shiftRandomSeed(uint256 randomNumber) internal { randomSeed = uint256(keccak256(abi.encode(randomSeed, randomNumber))); } /* ------------- View ------------- */ function randomSeedSet() public view returns (bool) { return randomSeed > 0; } /* ------------- Modifier ------------- */ modifier whenRandomSeedSet() { if (!randomSeedSet()) revert RandomSeedNotSet(); _; } modifier whenRandomSeedUnset() { if (randomSeedSet()) revert RandomSeedAlreadySet(); _; } } // get your shit together Chainlink... contract VRFBaseMainnet is VRFBase( 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445, 2 * 1e18, 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, 0x514910771AF9Ca656af840dff83E8264EcF986CA ) { } contract VRFBaseRinkeby is VRFBase( 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311, 0.1 * 1e18, 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B, 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 ) {} contract VRFBaseMumbai is VRFBase( 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4, 0.0001 * 1e18, 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255, 0x326C977E6efc84E512bB9C30f76E30c160eD06FB ) {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/access/AccessControl.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; contract Gouda is ERC20, AccessControl { bytes32 constant MINT_AUTHORITY = keccak256('MINT_AUTHORITY'); bytes32 constant BURN_AUTHORITY = keccak256('BURN_AUTHORITY'); bytes32 constant TREASURY = keccak256('TREASURY'); address public multiSigTreasury = 0xFB79a928C5d6c5932Ba83Aa8C7145cBDCDb9fd2E; constructor(address madmouse) ERC20('Gouda', 'GOUDA') { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINT_AUTHORITY, madmouse); _setupRole(BURN_AUTHORITY, madmouse); _setupRole(TREASURY, multiSigTreasury); _mint(multiSigTreasury, 200_000 * 1e18); } /* ------------- Restricted ------------- */ function mint(address user, uint256 amount) external onlyRole(MINT_AUTHORITY) { _mint(user, amount); } /* ------------- ERC20Burnable ------------- */ function burnFrom(address account, uint256 amount) public { if (!hasRole(BURN_AUTHORITY, msg.sender)) _spendAllowance(account, msg.sender, amount); _burn(account, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @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 virtual override 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 override onlyRole(getRoleAdmin(role)) { _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 override onlyRole(getRoleAdmin(role)) { _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 revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { 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}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ 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 { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ 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; } /** * @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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `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); } /** @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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ 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); } } } /** * @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.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @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 {AccessControl-_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) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @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) external; /** * @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) external; /** * @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) external; } // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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.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 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.1 (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 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/utils/Address.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import './ERC721MLibrary.sol'; error IncorrectOwner(); error NonexistentToken(); error QueryForZeroAddress(); error TokenIdUnstaked(); error ExceedsStakingLimit(); error MintToZeroAddress(); error MintZeroQuantity(); error MintMaxSupplyReached(); error MintMaxWalletReached(); error CallerNotOwnerNorApproved(); error ApprovalToCaller(); error ApproveToCurrentOwner(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); abstract contract ERC721M { using Address for address; using Strings for uint256; using UserDataOps for uint256; using TokenDataOps for uint256; event Transfer(address indexed from, address indexed to, uint256 indexed id); event Approval(address indexed owner, address indexed spender, uint256 indexed id); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); string public name; string public symbol; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; uint256 public totalSupply; uint256 immutable startingIndex; uint256 immutable collectionSize; uint256 immutable maxPerWallet; // note: hard limit of 255, otherwise overflows can happen uint256 constant stakingLimit = 100; mapping(uint256 => uint256) internal _tokenData; mapping(address => uint256) internal _userData; constructor( string memory name_, string memory symbol_, uint256 startingIndex_, uint256 collectionSize_, uint256 maxPerWallet_ ) { name = name_; symbol = symbol_; collectionSize = collectionSize_; maxPerWallet = maxPerWallet_; startingIndex = startingIndex_; } /* ------------- External ------------- */ function stake(uint256[] calldata tokenIds) external payable { uint256 userData = _claimReward(); for (uint256 i; i < tokenIds.length; ++i) userData = _stake(msg.sender, tokenIds[i], userData); _userData[msg.sender] = userData; } function unstake(uint256[] calldata tokenIds) external payable { uint256 userData = _claimReward(); for (uint256 i; i < tokenIds.length; ++i) userData = _unstake(msg.sender, tokenIds[i], userData); _userData[msg.sender] = userData; } function claimReward() external payable { _userData[msg.sender] = _claimReward(); } /* ------------- Private ------------- */ function _stake( address from, uint256 tokenId, uint256 userData ) private returns (uint256) { uint256 _numStaked = userData.numStaked(); uint256 tokenData = _tokenDataOf(tokenId); address owner = tokenData.owner(); if (_numStaked >= stakingLimit) revert ExceedsStakingLimit(); if (owner != from) revert IncorrectOwner(); delete getApproved[tokenId]; // hook, used for reading DNA, updating role balances, (uint256 userDataX, uint256 tokenDataX) = _beforeStakeDataTransform(tokenId, userData, tokenData); (userData, tokenData) = applySafeDataTransform(userData, tokenData, userDataX, tokenDataX); tokenData = tokenData.setstaked(); userData = userData.decreaseBalance(1).increaseNumStaked(1); if (_numStaked == 0) userData = userData.setStakeStart(block.timestamp); _tokenData[tokenId] = tokenData; emit Transfer(from, address(this), tokenId); return userData; } function _unstake( address to, uint256 tokenId, uint256 userData ) private returns (uint256) { uint256 tokenData = _tokenDataOf(tokenId); address owner = tokenData.trueOwner(); bool isStaked = tokenData.staked(); if (owner != to) revert IncorrectOwner(); if (!isStaked) revert TokenIdUnstaked(); (uint256 userDataX, uint256 tokenDataX) = _beforeUnstakeDataTransform(tokenId, userData, tokenData); (userData, tokenData) = applySafeDataTransform(userData, tokenData, userDataX, tokenDataX); // if mintAndStake flag is set, we need to make sure that next tokenData is set // because tokenData in this case is implicit and needs to carry over if (tokenData.mintAndStake()) { unchecked { tokenData = _ensureTokenDataSet(tokenId + 1, tokenData).unsetMintAndStake(); } } tokenData = tokenData.unsetstaked(); userData = userData.increaseBalance(1).decreaseNumStaked(1).setStakeStart(block.timestamp); _tokenData[tokenId] = tokenData; emit Transfer(address(this), to, tokenId); return userData; } /* ------------- Internal ------------- */ function _mintAndStake( address to, uint256 quantity, bool stake_ ) internal { unchecked { uint256 totalSupply_ = totalSupply; uint256 startTokenId = startingIndex + totalSupply_; uint256 userData = _userData[to]; uint256 numMinted_ = userData.numMinted(); if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); if (totalSupply_ + quantity > collectionSize) revert MintMaxSupplyReached(); if (numMinted_ + quantity > maxPerWallet && address(this).code.length != 0) revert MintMaxWalletReached(); // don't update for airdrops if (to == msg.sender) userData = userData.increaseNumMinted(quantity); uint256 tokenData = TokenDataOps.newTokenData(to, block.timestamp, stake_); // don't have to care about next token data if only minting one // could optimize to implicitly flag last token id of batch if (quantity == 1) tokenData = tokenData.flagNextTokenDataSet(); if (stake_) { uint256 _numStaked = userData.numStaked(); userData = claimReward(userData); userData = userData.increaseNumStaked(quantity); if (_numStaked + quantity > stakingLimit) revert ExceedsStakingLimit(); if (_numStaked == 0) userData = userData.setStakeStart(block.timestamp); uint256 tokenId; for (uint256 i; i < quantity; ++i) { tokenId = startTokenId + i; (userData, tokenData) = _beforeStakeDataTransform(tokenId, userData, tokenData); emit Transfer(address(0), to, tokenId); emit Transfer(to, address(this), tokenId); } } else { userData = userData.increaseBalance(quantity); for (uint256 i; i < quantity; ++i) emit Transfer(address(0), to, startTokenId + i); } _userData[to] = userData; _tokenData[startTokenId] = tokenData; totalSupply += quantity; } } function _claimReward() internal returns (uint256) { uint256 userData = _userData[msg.sender]; return claimReward(userData); } function claimReward(uint256 userData) private returns (uint256) { uint256 reward = _pendingReward(msg.sender, userData); userData = userData.setLastClaimed(block.timestamp); _payoutReward(msg.sender, reward); return userData; } function _tokenDataOf(uint256 tokenId) public view returns (uint256) { if (!_exists(tokenId)) revert NonexistentToken(); for (uint256 curr = tokenId; ; curr--) { uint256 tokenData = _tokenData[curr]; if (tokenData != 0) return (curr == tokenId) ? tokenData : tokenData.copy(); } // unreachable return 0; } function _exists(uint256 tokenId) internal view returns (bool) { return startingIndex <= tokenId && tokenId < startingIndex + totalSupply; } function transferFrom( address from, address to, uint256 tokenId ) public { // make sure no one is misled by token transfer events if (to == address(this)) { uint256 userData = _claimReward(); _userData[msg.sender] = _stake(msg.sender, tokenId, userData); } else { uint256 tokenData = _tokenDataOf(tokenId); address owner = tokenData.owner(); bool isApprovedOrOwner = (msg.sender == owner || isApprovedForAll[owner][msg.sender] || getApproved[tokenId] == msg.sender); if (!isApprovedOrOwner) revert CallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); if (owner != from) revert TransferFromIncorrectOwner(); delete getApproved[tokenId]; unchecked { _tokenData[tokenId] = _ensureTokenDataSet(tokenId + 1, tokenData) .setOwner(to) .setLastTransfer(block.timestamp) .incrementOwnerCount(); } _userData[from] = _userData[from].decreaseBalance(1); _userData[to] = _userData[to].increaseBalance(1); emit Transfer(from, to, tokenId); } } function _ensureTokenDataSet(uint256 tokenId, uint256 tokenData) private returns (uint256) { if (!tokenData.nextTokenDataSet() && _tokenData[tokenId] == 0 && _exists(tokenId)) _tokenData[tokenId] = tokenData.copy(); // make sure to not pass any token specific data in return tokenData.flagNextTokenDataSet(); } /* ------------- Virtual (hooks) ------------- */ function _beforeStakeDataTransform( uint256, // tokenId uint256 userData, uint256 tokenData ) internal view virtual returns (uint256, uint256) { return (userData, tokenData); } function _beforeUnstakeDataTransform( uint256, // tokenId uint256 userData, uint256 tokenData ) internal view virtual returns (uint256, uint256) { return (userData, tokenData); } function _pendingReward(address, uint256 userData) internal view virtual returns (uint256); function _payoutReward(address user, uint256 reward) internal virtual; /* ------------- View ------------- */ function ownerOf(uint256 tokenId) external view returns (address) { return _tokenDataOf(tokenId).owner(); } function trueOwnerOf(uint256 tokenId) external view returns (address) { return _tokenDataOf(tokenId).trueOwner(); } function balanceOf(address owner) external view returns (uint256) { if (owner == address(0)) revert QueryForZeroAddress(); return _userData[owner].balance(); } function numStaked(address user) external view returns (uint256) { return _userData[user].numStaked(); } function numOwned(address user) external view returns (uint256) { uint256 userData = _userData[user]; return userData.balance() + userData.numStaked(); } function numMinted(address user) external view returns (uint256) { return _userData[user].numMinted(); } function pendingReward(address user) external view returns (uint256) { return _pendingReward(user, _userData[user]); } // O(N) read-only functions function tokenIdsOf(address user, uint256 type_) external view returns (uint256[] memory) { unchecked { uint256 numTotal = type_ == 0 ? this.balanceOf(user) : type_ == 1 ? this.numStaked(user) : this.numOwned(user); uint256[] memory ids = new uint256[](numTotal); if (numTotal == 0) return ids; uint256 count; for (uint256 i = startingIndex; i < totalSupply + startingIndex; ++i) { uint256 tokenData = _tokenDataOf(i); if (user == tokenData.trueOwner()) { bool staked = tokenData.staked(); if ((type_ == 0 && !staked) || (type_ == 1 && staked) || type_ == 2) { ids[count++] = i; if (numTotal == count) return ids; } } } return ids; } } function totalNumStaked() external view returns (uint256) { unchecked { uint256 count; for (uint256 i = startingIndex; i < startingIndex + totalSupply; ++i) { if (_tokenDataOf(i).staked()) ++count; } return count; } } /* ------------- ERC721 ------------- */ function tokenURI(uint256 id) public view virtual returns (string memory); function supportsInterface(bytes4 interfaceId) external view virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } function approve(address spender, uint256 tokenId) external { address owner = _tokenDataOf(tokenId).owner(); if (msg.sender != owner && !isApprovedForAll[owner][msg.sender]) revert CallerNotOwnerNorApproved(); getApproved[tokenId] = spender; emit Approval(owner, spender, tokenId); } function setApprovalForAll(address operator, bool approved) external { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function safeTransferFrom( address from, address to, uint256 tokenId ) external { safeTransferFrom(from, to, tokenId, ''); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public { transferFrom(from, to, tokenId); if ( to.code.length != 0 && IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data) != IERC721Receiver(to).onERC721Received.selector ) revert TransferToNonERC721ReceiverImplementer(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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.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 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.1 (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 (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 pragma solidity ^0.8.0; // # ERC721M.sol // // _tokenData layout: // 0x________/cccccbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa // a [ 0] (uint160): address #owner (owner of token id) // b [160] (uint40): timestamp #lastTransfer (timestamp since the last transfer) // c [200] (uint20): #ownerCount (number of total owners of token) // f [220] (uint1): #staked flag (flag whether id has been staked) Note: this carries over when calling 'ownerOf' // f [221] (uint1): #mintAndStake flag (flag whether to carry over stake flag when calling tokenDataOf; used for mintAndStake and boost) // e [222] (uint1): #nextTokenDataSet flag (flag whether the data of next token id has already been set) // _ [224] (uint32): arbitrary data uint256 constant RESTRICTED_TOKEN_DATA = 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // # MadMouse.sol // // _tokenData (metadata) layout: // 0xefg00000________________________________________________________ // e [252] (uint4): #level (mouse level) [0...2] (must be 0-based) // f [248] (uint4): #role (mouse role) [1...5] (must start at 1) // g [244] (uint4): #rarity (mouse rarity) [0...3] struct TokenData { address owner; uint256 lastTransfer; uint256 ownerCount; bool staked; bool mintAndStake; bool nextTokenDataSet; uint256 level; uint256 role; uint256 rarity; } // # ERC721M.sol // // _userData layout: // 0x________________________________ddccccccccccbbbbbbbbbbaaaaaaaaaa // a [ 0] (uint32): #balance (owner ERC721 balance) // b [ 40] (uint40): timestamp #stakeStart (timestamp when stake started) // c [ 80] (uint40): timestamp #lastClaimed (timestamp when user last claimed rewards) // d [120] (uint8): #numStaked (balance count of all staked tokens) // _ [128] (uint128): arbitrary data uint256 constant RESTRICTED_USER_DATA = 0x00000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // # MadMouseStaking.sol // // _userData (boost) layout: // 0xttttttttt/o/rriiffgghhaabbccddee________________________________ // a-e [128] (5x uint8): #roleBalances (balance of all staked roles) // f-h [168] (3x uint8): #levelBalances (balance of all staked levels) // i [192] (uint8): #specialGuestIndex (signals whether the user claims to hold a token of a certain collection) // r [200] (uint10): #rarityPoints (counter of rare traits; 1 is rare, 2 is super-rare, 3 is ultra-rare) // o [210] (uint8): #OGCount (counter of rare traits; 1 is rare, 2 is super-rare, 3 is ultra-rare) // t [218] (uint38): timestamp #boostStart (timestamp of when the boost by burning tokens of affiliate collections started) struct UserData { uint256 balance; uint256 stakeStart; uint256 lastClaimed; uint256 numStaked; uint256[5] roleBalances; uint256 uniqueRoleCount; // inferred uint256[3] levelBalances; uint256 specialGuestIndex; uint256 rarityPoints; uint256 OGCount; uint256 boostStart; } function applySafeDataTransform( uint256 userData, uint256 tokenData, uint256 userDataTransformed, uint256 tokenDataTransformed ) pure returns (uint256, uint256) { // mask transformed data in order to leave base data untouched in any case userData = (userData & RESTRICTED_USER_DATA) | (userDataTransformed & ~RESTRICTED_USER_DATA); tokenData = (tokenData & RESTRICTED_TOKEN_DATA) | (tokenDataTransformed & ~RESTRICTED_TOKEN_DATA); return (userData, tokenData); } // @note: many of these are unchecked, because safemath wouldn't be able to guard // overflows while updating bitmaps unless custom checks were to be implemented library UserDataOps { function getUserData(uint256 userData) internal pure returns (UserData memory) { return UserData({ balance: UserDataOps.balance(userData), stakeStart: UserDataOps.stakeStart(userData), lastClaimed: UserDataOps.lastClaimed(userData), numStaked: UserDataOps.numStaked(userData), roleBalances: UserDataOps.roleBalances(userData), uniqueRoleCount: UserDataOps.uniqueRoleCount(userData), levelBalances: UserDataOps.levelBalances(userData), specialGuestIndex: UserDataOps.specialGuestIndex(userData), rarityPoints: UserDataOps.rarityPoints(userData), OGCount: UserDataOps.OGCount(userData), boostStart: UserDataOps.boostStart(userData) }); } function balance(uint256 userData) internal pure returns (uint256) { return userData & 0xFFFFF; } function increaseBalance(uint256 userData, uint256 amount) internal pure returns (uint256) { unchecked { return userData + amount; } } function decreaseBalance(uint256 userData, uint256 amount) internal pure returns (uint256) { unchecked { return userData - amount; } } function numMinted(uint256 userData) internal pure returns (uint256) { return (userData >> 20) & 0xFFFFF; } function increaseNumMinted(uint256 userData, uint256 amount) internal pure returns (uint256) { unchecked { return userData + (amount << 20); } } function stakeStart(uint256 userData) internal pure returns (uint256) { return (userData >> 40) & 0xFFFFFFFFFF; } function setStakeStart(uint256 userData, uint256 timestamp) internal pure returns (uint256) { return (userData & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000FFFFFFFFFF) | (timestamp << 40); } function lastClaimed(uint256 userData) internal pure returns (uint256) { return (userData >> 80) & 0xFFFFFFFFFF; } function setLastClaimed(uint256 userData, uint256 timestamp) internal pure returns (uint256) { return (userData & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000FFFFFFFFFFFFFFFFFFFF) | (timestamp << 80); } function numStaked(uint256 userData) internal pure returns (uint256) { return (userData >> 120) & 0xFF; } function increaseNumStaked(uint256 userData, uint256 amount) internal pure returns (uint256) { unchecked { return userData + (amount << 120); } } function decreaseNumStaked(uint256 userData, uint256 amount) internal pure returns (uint256) { unchecked { return userData - (amount << 120); } } function roleBalances(uint256 userData) internal pure returns (uint256[5] memory balances) { balances = [ (userData >> (128 + 0)) & 0xFF, (userData >> (128 + 8)) & 0xFF, (userData >> (128 + 16)) & 0xFF, (userData >> (128 + 24)) & 0xFF, (userData >> (128 + 32)) & 0xFF ]; } // trait counts are set through hook in madmouse contract (MadMouse::_beforeStakeDataTransform) function uniqueRoleCount(uint256 userData) internal pure returns (uint256) { unchecked { return (toUInt256((userData >> (128)) & 0xFF > 0) + toUInt256((userData >> (128 + 8)) & 0xFF > 0) + toUInt256((userData >> (128 + 16)) & 0xFF > 0) + toUInt256((userData >> (128 + 24)) & 0xFF > 0) + toUInt256((userData >> (128 + 32)) & 0xFF > 0)); } } function levelBalances(uint256 userData) internal pure returns (uint256[3] memory balances) { unchecked { balances = [ (userData >> (168 + 0)) & 0xFF, (userData >> (168 + 8)) & 0xFF, (userData >> (168 + 16)) & 0xFF ]; } } // depends on the levels of the staked tokens (also set in hook MadMouse::_beforeStakeDataTransform) // counts the base reward, depending on the levels of staked ids function baseReward(uint256 userData) internal pure returns (uint256) { unchecked { return (((userData >> (168)) & 0xFF) + (((userData >> (168 + 8)) & 0xFF) << 1) + (((userData >> (168 + 16)) & 0xFF) << 2)); } } function rarityPoints(uint256 userData) internal pure returns (uint256) { return (userData >> 200) & 0x3FF; } function specialGuestIndex(uint256 userData) internal pure returns (uint256) { return (userData >> 192) & 0xFF; } function setSpecialGuestIndex(uint256 userData, uint256 index) internal pure returns (uint256) { return (userData & ~uint256(0xFF << 192)) | (index << 192); } function boostStart(uint256 userData) internal pure returns (uint256) { return (userData >> 218) & 0xFFFFFFFFFF; } function setBoostStart(uint256 userData, uint256 timestamp) internal pure returns (uint256) { return (userData & ~(uint256(0xFFFFFFFFFF) << 218)) | (timestamp << 218); } function OGCount(uint256 userData) internal pure returns (uint256) { return (userData >> 210) & 0xFF; } // (should start at 128, 168; but role/level start at 1...) function updateUserDataStake(uint256 userData, uint256 tokenData) internal pure returns (uint256) { unchecked { uint256 role = TokenDataOps.role(tokenData); if (role > 0) { userData += uint256(1) << (120 + (role << 3)); // roleBalances userData += TokenDataOps.rarity(tokenData) << 200; // rarityPoints } if (TokenDataOps.mintAndStake(tokenData)) userData += uint256(1) << 210; // OGCount userData += uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3)); // levelBalances return userData; } } function updateUserDataUnstake(uint256 userData, uint256 tokenData) internal pure returns (uint256) { unchecked { uint256 role = TokenDataOps.role(tokenData); if (role > 0) { userData -= uint256(1) << (120 + (role << 3)); // roleBalances userData -= TokenDataOps.rarity(tokenData) << 200; // rarityPoints } if (TokenDataOps.mintAndStake(tokenData)) userData -= uint256(1) << 210; // OG-count userData -= uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3)); // levelBalances return userData; } } function increaseLevelBalances(uint256 userData, uint256 tokenData) internal pure returns (uint256) { unchecked { return userData + (uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3))); } } function decreaseLevelBalances(uint256 userData, uint256 tokenData) internal pure returns (uint256) { unchecked { return userData - (uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3))); } } } library TokenDataOps { function getTokenData(uint256 tokenData) internal view returns (TokenData memory) { return TokenData({ owner: TokenDataOps.owner(tokenData), lastTransfer: TokenDataOps.lastTransfer(tokenData), ownerCount: TokenDataOps.ownerCount(tokenData), staked: TokenDataOps.staked(tokenData), mintAndStake: TokenDataOps.mintAndStake(tokenData), nextTokenDataSet: TokenDataOps.nextTokenDataSet(tokenData), level: TokenDataOps.level(tokenData), role: TokenDataOps.role(tokenData), rarity: TokenDataOps.rarity(tokenData) }); } function newTokenData( address owner_, uint256 lastTransfer_, bool stake_ ) internal pure returns (uint256) { uint256 tokenData = (uint256(uint160(owner_)) | (lastTransfer_ << 160) | (uint256(1) << 200)); return stake_ ? setstaked(setMintAndStake(tokenData)) : tokenData; } function copy(uint256 tokenData) internal pure returns (uint256) { // tokenData minus the token specific flags (4/2bits), i.e. only owner, lastTransfer, ownerCount // stake flag (& mintAndStake flag) carries over if mintAndStake was called return tokenData & (RESTRICTED_TOKEN_DATA >> (mintAndStake(tokenData) ? 2 : 4)); } function owner(uint256 tokenData) internal view returns (address) { if (staked(tokenData)) return address(this); return trueOwner(tokenData); } function setOwner(uint256 tokenData, address owner_) internal pure returns (uint256) { return (tokenData & 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000) | uint160(owner_); } function staked(uint256 tokenData) internal pure returns (bool) { return ((tokenData >> 220) & uint256(1)) > 0; // Note: this can carry over when calling 'ownerOf' } function setstaked(uint256 tokenData) internal pure returns (uint256) { return tokenData | (uint256(1) << 220); } function unsetstaked(uint256 tokenData) internal pure returns (uint256) { return tokenData & ~(uint256(1) << 220); } function mintAndStake(uint256 tokenData) internal pure returns (bool) { return ((tokenData >> 221) & uint256(1)) > 0; } function setMintAndStake(uint256 tokenData) internal pure returns (uint256) { return tokenData | (uint256(1) << 221); } function unsetMintAndStake(uint256 tokenData) internal pure returns (uint256) { return tokenData & ~(uint256(1) << 221); } function nextTokenDataSet(uint256 tokenData) internal pure returns (bool) { return ((tokenData >> 222) & uint256(1)) > 0; } function flagNextTokenDataSet(uint256 tokenData) internal pure returns (uint256) { return tokenData | (uint256(1) << 222); // nextTokenDatatSet flag (don't repeat the read/write) } function trueOwner(uint256 tokenData) internal pure returns (address) { return address(uint160(tokenData)); } function ownerCount(uint256 tokenData) internal pure returns (uint256) { return (tokenData >> 200) & 0xFFFFF; } function incrementOwnerCount(uint256 tokenData) internal pure returns (uint256) { uint256 newOwnerCount = min(ownerCount(tokenData) + 1, 0xFFFFF); return (tokenData & ~(uint256(0xFFFFF) << 200)) | (newOwnerCount << 200); } function resetOwnerCount(uint256 tokenData) internal pure returns (uint256) { uint256 count = min(ownerCount(tokenData), 2); // keep minter status return (tokenData & ~(uint256(0xFFFFF) << 200)) | (count << 200); } function lastTransfer(uint256 tokenData) internal pure returns (uint256) { return (tokenData >> 160) & 0xFFFFFFFFFF; } function setLastTransfer(uint256 tokenData, uint256 timestamp) internal pure returns (uint256) { return (tokenData & 0xFFFFFFFFFFFFFF0000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | (timestamp << 160); } // MadMouse function level(uint256 tokenData) internal pure returns (uint256) { unchecked { return 1 + (tokenData >> 252); } } function increaseLevel(uint256 tokenData) internal pure returns (uint256) { unchecked { return tokenData + (uint256(1) << 252); } } function role(uint256 tokenData) internal pure returns (uint256) { return (tokenData >> 248) & 0xF; } function rarity(uint256 tokenData) internal pure returns (uint256) { return (tokenData >> 244) & 0xF; } // these slots should be are already 0 function setRoleAndRarity(uint256 tokenData, uint256 dna) internal pure returns (uint256) { return ((tokenData & ~(uint256(0xFF) << 244)) | (DNAOps.toRole(dna) << 248) | (DNAOps.toRarity(dna) << 244)); } } library DNAOps { function toRole(uint256 dna) internal pure returns (uint256) { unchecked { return 1 + ((dna & 0xFF) % 5); } } function toRarity(uint256 dna) internal pure returns (uint256) { uint256 dnaFur = (dna >> 8) & 0xFF; if (dnaFur > 108) return 0; if (dnaFur > 73) return 1; if (dnaFur > 17) return 2; return 3; } } /* ------------- Helpers ------------- */ // more efficient https://github.com/ethereum/solidity/issues/659 function toUInt256(bool x) pure returns (uint256 r) { assembly { r := x } } function min(uint256 a, uint256 b) pure returns (uint256) { return a < b ? a : b; } function isValidString(string calldata str, uint256 maxLen) pure returns (bool) { unchecked { bytes memory b = bytes(str); if (b.length < 1 || b.length > maxLen || b[0] == 0x20 || b[b.length - 1] == 0x20) return false; bytes1 lastChar = b[0]; bytes1 char; for (uint256 i; i < b.length; ++i) { char = b[i]; if ( (char > 0x60 && char < 0x7B) || //a-z (char > 0x40 && char < 0x5B) || //A-Z (char == 0x20) || //space (char > 0x2F && char < 0x3A) //9-0 ) { lastChar = char; } else { return false; } } return true; } }
simulates a token update and only returns ids != 0 if the user gets a bonus increase upon updating staked data
function shouldUpdateStakedIds(address user) external view returns (uint256[] memory) { if (!revealed) return new uint256[](0); uint256[] memory stakedIds = this.tokenIdsOf(user, 1); uint256 userData = _userData[user]; uint256 oldTotalBonus = totalBonus(user, userData); uint256 tokenData; for (uint256 i; i < stakedIds.length; ++i) { tokenData = _tokenDataOf(stakedIds[i]); if (tokenData.role() == 0) (userData, ) = updateDataWhileStaked(userData, stakedIds[i], tokenData, tokenData); else stakedIds[i] = 0; } uint256 newTotalBonus = totalBonus(user, userData); return (newTotalBonus > oldTotalBonus) ? stakedIds : new uint256[](0); }
393,019
[ 1, 4625, 348, 7953, 560, 30, 225, 3142, 17099, 279, 1147, 1089, 471, 1338, 1135, 3258, 480, 374, 309, 326, 729, 5571, 279, 324, 22889, 10929, 12318, 9702, 384, 9477, 501, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1410, 1891, 510, 9477, 2673, 12, 2867, 729, 13, 3903, 1476, 1135, 261, 11890, 5034, 8526, 3778, 13, 288, 203, 3639, 309, 16051, 266, 537, 18931, 13, 327, 394, 2254, 5034, 8526, 12, 20, 1769, 203, 203, 3639, 2254, 5034, 8526, 3778, 384, 9477, 2673, 273, 333, 18, 2316, 2673, 951, 12, 1355, 16, 404, 1769, 203, 203, 3639, 2254, 5034, 13530, 273, 389, 1355, 751, 63, 1355, 15533, 203, 3639, 2254, 5034, 1592, 5269, 38, 22889, 273, 2078, 38, 22889, 12, 1355, 16, 13530, 1769, 203, 203, 3639, 2254, 5034, 1147, 751, 31, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 384, 9477, 2673, 18, 2469, 31, 965, 77, 13, 288, 203, 5411, 1147, 751, 273, 389, 2316, 751, 951, 12, 334, 9477, 2673, 63, 77, 19226, 203, 5411, 309, 261, 2316, 751, 18, 4615, 1435, 422, 374, 13, 203, 7734, 261, 1355, 751, 16, 262, 273, 1089, 751, 15151, 510, 9477, 12, 1355, 751, 16, 384, 9477, 2673, 63, 77, 6487, 1147, 751, 16, 1147, 751, 1769, 203, 5411, 469, 384, 9477, 2673, 63, 77, 65, 273, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 394, 5269, 38, 22889, 273, 2078, 38, 22889, 12, 1355, 16, 13530, 1769, 203, 203, 3639, 327, 261, 2704, 5269, 38, 22889, 405, 1592, 5269, 38, 22889, 13, 692, 384, 9477, 2673, 294, 394, 2254, 5034, 8526, 12, 20, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 // Solidity files have to start with this pragma. // It will be used by the Solidity compiler to validate its version. pragma solidity ^0.8.0; // We import this library to be able to use console.log import "hardhat/console.sol"; // This is the main building block for smart contracts. // Diet Challenge contract DietChallenge { string public name = "DietChallenge"; string public symbol = "DIET"; // uint256 public DECIMAL_POINTS = 2; // allow up to 2 decimal points bool public isLocked = false; bool public isRoundOver = false; uint256 public dueDate; // Related to deposits uint256 public totalValueLocked; uint256 public totalUsers; // Related to withdraw uint256 public totalResultsSubmitted; uint256 public totalWinners; uint256 public winningAmount; address[] public userAddresses; address public adminAddress; struct Result { uint256 weight; // weight multiplied by 100 to account up to 2 decimal points string ipfsHash; } struct UserAttributes { address payable owner; Result goal; Result actual; uint256 valueLocked; bool reached; } mapping(address => UserAttributes) public tvlByUser; // REGISTERING_BETS ChallengePeriod ResultSubmissionPeriod Withdraw // (DIET_CHALLENGE_STARTED~) (wait period) (~RESULTS_TALLIED & DIET_CHALLENGE_ENDED) // ==================================================================================================================================================== // isLocked false true true false // isRoundOver false false false true enum WorkflowStatus { REGISTERING_BETS, DIET_CHALLENGE_STARTED, DIET_CHALLENGE_ENDED } uint256 duration; // duration of the game uint256 wait; // submit result period WorkflowStatus public workflowStatus; constructor(uint256 _duration, uint256 _wait) { adminAddress = msg.sender; duration = _duration; wait = _wait; // restart isLocked = false; isRoundOver = false; workflowStatus = WorkflowStatus.REGISTERING_BETS; } event DepositCreated( uint256 valueLocked, uint256 totalValueLocked, uint256 totalUsers ); event ResultSubmitted(uint256 totalResultsSubmitted); event ResultsTallied(uint256 totalWinners, uint256 winningAmount); event WithdrawCreated(uint256 valueWithdrawn, uint256 remainingValue); event WorkflowStatusChanged(WorkflowStatus newStatus); function getWorkflowStatus() public view returns ( WorkflowStatus, bool, bool ) { return (workflowStatus, isLocked, isRoundOver); } function getTotalValueLocked() public view returns (uint256) { return address(this).balance; } /// @notice This returns a list of all the user info /// @dev This data is used to render the list of deposits function getAllUserInfo() public view returns (UserAttributes[] memory) { UserAttributes[] memory result = new UserAttributes[]( userAddresses.length ); for (uint256 i = 0; i < userAddresses.length; i++) { result[i] = tvlByUser[userAddresses[i]]; } return result; } /// @notice User can deposit ether and specify their weight goal /// @dev Once all the deposits are made, `freezeFunds()` /// is called to lock the funds and start off the challenge function deposit(string memory ipfsHash, uint256 weightGoal) public payable canDeposit { uint256 valueLocked = msg.value; require(valueLocked > 0, "You must submit an amount"); UserAttributes storage user = tvlByUser[msg.sender]; require(user.valueLocked == 0, "You already made your deposits"); user.owner = payable(msg.sender); user.goal = Result(weightGoal, ipfsHash); user.valueLocked = valueLocked; user.reached = false; totalValueLocked += valueLocked; totalUsers++; userAddresses.push(msg.sender); emit DepositCreated(valueLocked, totalValueLocked, totalUsers); } /// @notice User who succeeded in the challenge can withdraw ether /// However, user has to wait until the end of the challenge /// and meet the following requirements: /// 1) 2 days (wait period) have passed from the end of the deadline and /// @dev 2) `releaseFunds()` has to be called before user can start withdrawing function withdraw() public canWithdraw { // require(dueDate < block.timestamp, "It must pass the duedate"); // If the results are not submitted in the next 2 days after the challenge, then // the withdrawl those who submitted will occur // require( // block.timestamp - dueDate > wait, // "You have to wait until the end of the submission period" // ); require( tvlByUser[msg.sender].reached == true, "You are not eligible for withdraw" ); require( tvlByUser[msg.sender].valueLocked > 0, "You have already made your withdrawal" ); require(totalValueLocked > 0, "There is no funds left to claim"); require(winningAmount > 0, "Wait until the funds are released"); // pay back to the actual user if (totalValueLocked >= winningAmount) { payable(msg.sender).transfer(winningAmount); } else { payable(msg.sender).transfer(totalValueLocked); } totalValueLocked -= winningAmount; tvlByUser[msg.sender].valueLocked = 0; // Mark that the user has made the withdrawal emit WithdrawCreated(winningAmount, totalValueLocked); } function withdrawAll() public onlyAdmin { payable(msg.sender).transfer(address(this).balance); totalValueLocked = 0; winningAmount = 0; emit WithdrawCreated(winningAmount, totalValueLocked); } /// @notice User submit their results at the end of the challenge /// @dev The result on whether a user succeeded or not is saved /// Also count the total number of users who succeeded the challenge /// The total number of users who submitted the result are saved too function submitResult(string memory ipfsHash, uint256 weightActual) public { require( dueDate < block.timestamp, "You must wait until the due date to submit a result" ); require( isLocked == true && isRoundOver == false, "You must wait for the admin to confirm" ); UserAttributes storage user = tvlByUser[msg.sender]; require( user.owner == msg.sender, "You can only submit your own result" ); // TODO: You can only submit once user.actual = Result(weightActual, ipfsHash); if (user.goal.weight >= weightActual) { user.reached = true; totalWinners++; } totalResultsSubmitted++; emit ResultSubmitted(totalResultsSubmitted); } /// @notice This locks the funds, and starts the diet challenge /// @dev This is called after all the deposits are made function freezeFunds() public onlyAdmin canDeposit { setDueDate(); lock(); start(); workflowStatus = WorkflowStatus.DIET_CHALLENGE_STARTED; emit WorkflowStatusChanged(workflowStatus); } /// @notice This calculates amount to distribute to the winners /// @dev This is called after results are submitted /// This will be registered in the upkeep - to be called 2 days after the dueDate function releaseFunds() public onlyAdmin { // passed deadline require( isLocked == true && isRoundOver == false, "The game has not even started" ); require( dueDate + wait < block.timestamp, "You must wait until the end of the submission period" ); if (totalWinners > 0) { winningAmount = totalValueLocked / totalWinners; } else { winningAmount = totalValueLocked; } unlock(); end(); workflowStatus = WorkflowStatus.DIET_CHALLENGE_ENDED; emit ResultsTallied(totalWinners, winningAmount); emit WorkflowStatusChanged(workflowStatus); } /// @notice This indicates when the funds are locked for both deposit and withdraw /// @dev The fund is locked during the period of the challenge (challenge ~ ) /// It is not locked during the deposit period /// Then 'locked' during the challenge and until the results are submitted /// (up to 2 days after the end of the challenge) /// Then finally during withdrawal, the fund is unlocked function lock() private { isLocked = true; } function unlock() private { isLocked = false; } /// @notice This indicates the status of the game /// @dev It is set false by default, and only set to true /// to allow withdrawl after all the results are submitted function start() private { isRoundOver = false; } /// @notice This indicates the status of the game /// @dev It is set false by default, and only set to true /// to allow withdrawl after all the results are submitted function end() private { isRoundOver = true; } /// @notice This kicks off a new round of challenge // Users can start depositing /// @dev This resets all the values function restart() public onlyAdmin canWithdraw { unlock(); start(); // totalValueLocked = 0; // accumulates totalUsers = 0; totalResultsSubmitted = 0; totalWinners = 0; winningAmount = 0; dueDate = 0; for (uint256 i = 0; i < userAddresses.length; i++) { delete tvlByUser[userAddresses[i]]; } delete userAddresses; workflowStatus = WorkflowStatus.REGISTERING_BETS; emit WorkflowStatusChanged(workflowStatus); } /// @notice This sets the period of the challenge /// @dev This is set after all the deposits are made and kicks off the timer function setDueDate() private { dueDate = block.timestamp + duration; } /// @notice This simulates that a due date is over, and ready to accept results /// from users /// @dev This is added for testing purpose only function forceDueDate() public onlyAdmin { dueDate = block.timestamp - 1 days; } /// @notice User can withdraw once challenge is over and the results are submitted /// There is a 2 day wait after the deadline, to allow time for users to /// submit results /// @dev This is used to check game status before withdraw function is called modifier canWithdraw() { require( isRoundOver == true && isLocked == false, "NOT_ELIGITBLE_TO_WITHDRAW" ); _; } /// @notice User can deposit only when the previous round is finished /// @dev It is required that the `restart()` is called /// to restart the challenge and start accepting new deposits modifier canDeposit() { require( isRoundOver == false && isLocked == false, "NOT_ELIGIBLE_TO_DEPOSIT" ); _; } /// @dev The address with which the contract is deployed becomes the admin modifier onlyAdmin() { require(msg.sender == adminAddress, "ADMIN_ONLY"); _; } }
@notice User can deposit ether and specify their weight goal @dev Once all the deposits are made, `freezeFunds()` is called to lock the funds and start off the challenge
function deposit(string memory ipfsHash, uint256 weightGoal) public payable canDeposit { uint256 valueLocked = msg.value; require(valueLocked > 0, "You must submit an amount"); UserAttributes storage user = tvlByUser[msg.sender]; require(user.valueLocked == 0, "You already made your deposits"); user.owner = payable(msg.sender); user.goal = Result(weightGoal, ipfsHash); user.valueLocked = valueLocked; user.reached = false; totalValueLocked += valueLocked; totalUsers++; userAddresses.push(msg.sender); emit DepositCreated(valueLocked, totalValueLocked, totalUsers); }
12,592,221
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 2177, 848, 443, 1724, 225, 2437, 471, 4800, 3675, 3119, 17683, 632, 5206, 565, 12419, 777, 326, 443, 917, 1282, 854, 7165, 16, 1375, 29631, 42, 19156, 20338, 540, 353, 2566, 358, 2176, 326, 284, 19156, 471, 787, 3397, 326, 12948, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1080, 3778, 2359, 2556, 2310, 16, 2254, 5034, 3119, 27716, 13, 203, 3639, 1071, 203, 3639, 8843, 429, 203, 3639, 848, 758, 1724, 203, 565, 288, 203, 3639, 2254, 5034, 460, 8966, 273, 1234, 18, 1132, 31, 203, 3639, 2583, 12, 1132, 8966, 405, 374, 16, 315, 6225, 1297, 4879, 392, 3844, 8863, 203, 203, 3639, 2177, 2498, 2502, 729, 273, 268, 10872, 25895, 63, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 1132, 8966, 422, 374, 16, 315, 6225, 1818, 7165, 3433, 443, 917, 1282, 8863, 203, 203, 3639, 729, 18, 8443, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 3639, 729, 18, 27354, 273, 3438, 12, 4865, 27716, 16, 2359, 2556, 2310, 1769, 203, 3639, 729, 18, 1132, 8966, 273, 460, 8966, 31, 203, 3639, 729, 18, 266, 2004, 273, 629, 31, 203, 203, 3639, 2078, 620, 8966, 1011, 460, 8966, 31, 203, 3639, 2078, 6588, 9904, 31, 203, 203, 3639, 729, 7148, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 3626, 4019, 538, 305, 6119, 12, 1132, 8966, 16, 2078, 620, 8966, 16, 2078, 6588, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xd5be7b469B99a612A8c01084616a70f0d30d462D/sources/MikuruAsakura.sol
* 设置预售期间每个地址的最大 Mint 数量/
function setOnPreSalesMintCountForAddress( uint256 _onPreSalesMintCountForAddress ) external onlyOwner { onPreSalesMintCountForAddress = _onPreSalesMintCountForAddress; }
16,086,045
[ 1, 4625, 348, 7953, 560, 30, 380, 225, 169, 111, 127, 168, 126, 111, 170, 100, 231, 166, 247, 111, 167, 255, 258, 170, 250, 117, 167, 112, 242, 165, 121, 108, 166, 255, 113, 166, 256, 227, 168, 253, 231, 167, 255, 227, 166, 102, 105, 490, 474, 225, 167, 248, 113, 170, 234, 242, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 22131, 1386, 23729, 49, 474, 1380, 1290, 1887, 12, 203, 3639, 2254, 5034, 389, 265, 1386, 23729, 49, 474, 1380, 1290, 1887, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 603, 1386, 23729, 49, 474, 1380, 1290, 1887, 273, 389, 265, 1386, 23729, 49, 474, 1380, 1290, 1887, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: Apache-2.0 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract ReignToken is IERC20 { using SafeMath for uint256; string public constant name = "Sovreign Governance Token"; string public constant symbol = "REIGN"; uint8 public constant decimals = 18; uint256 public override totalSupply; address public owner; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) public override allowance; event Mint(address indexed to, uint256 value); constructor(address _owner) { owner = _owner; } // after the initial mint the owner will be set to 0 address function setOwner(address _owner) public { require(msg.sender == owner, "Only Owner can do this"); owner = _owner; } function mint(address to, uint256 value) external returns (bool) { require(msg.sender == owner, "Only Owner can do this"); _mint(to, value); emit Mint(to, value); return true; } function approve(address spender, uint256 value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom( address from, address to, uint256 value ) external override returns (bool) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); _transfer(from, to, value); return true; } function _mint(address to, uint256 value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } /** INTERNAL */ function _approve( address owner, address spender, uint256 value ) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer( address from, address to, uint256 value ) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } } // 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.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; } }
after the initial mint the owner will be set to 0 address
function setOwner(address _owner) public { require(msg.sender == owner, "Only Owner can do this"); owner = _owner; }
1,269,954
[ 1, 4625, 348, 7953, 560, 30, 225, 1839, 326, 2172, 312, 474, 326, 3410, 903, 506, 444, 358, 374, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 31309, 12, 2867, 389, 8443, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 3386, 16837, 848, 741, 333, 8863, 203, 3639, 3410, 273, 389, 8443, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; import "zeppelin-solidity/contracts/token/ERC721/ERC721Token.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "./lib/strings.sol"; // References: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v1.8.0/contracts/token/ERC721/ERC721Token.sol contract PeonyCertificate is ERC721Token ("Peony", "PNY") { using strings for *; using SafeMath for uint256; // These two are included in the open lib string internal name_ = "Peony"; string internal symbol_ = "PNY"; uint256 erc721TokenId = 1; // default tokenId for helping people to create unique id // our additional attirbutes for Issuer // Mapping from token ID to index of the issuer's issued tokens list mapping(uint256 => uint256) internal issuedTokensIndex; // Mapping from issuer to list of issued token IDs mapping (address => uint256[]) internal issuedTokens; // Mapping for issuer to know how many certificates it has issued mapping (address => uint256) internal issuedTokensCount; // Mapping from token ID to issuer mapping (uint256 => address) internal tokenIssuer; // Mapping from token ID to Expiration time mapping (uint256 => uint256) internal certificateExpirationTime; // Mapping for indicating if the token is revokable or not. mapping (uint256 => bool) internal revokableCertificates; // Mapping for indicating if the token is revoked or not. mapping (uint256 => bool) internal isCertificateRevoked; // Mapping from token ID to Valid Cert // mapping (uint256 => uint256) internal certificateIsValid; // Mapping from address to lockdown (for account getting hacked, // so owner will have ability to 'lock down' the account) mapping (address => bool) internal lockedDownAddresses; struct Signer{ string name; address signerAddr; string signature; uint256 dateSigned; } // Mapping tokenId to Signer index in TokenSignersList mapping (uint256 => mapping(address => uint256)) TokenSignersIndex; // Mapping to a list of signers mapping (uint256 => Signer[]) TokenSignersList; // constructor function PeonyCertificate() public { //Do some initialization } modifier onlyUnlocked() { require(!lockedDownAddresses[msg.sender]); _; } // OverLoaded function for regression function IssueCertificateOld(address _to, string _uri, uint256 expTime) onlyUnlocked public { this.IssueCertificate(_to, _uri, expTime, new address[](0), "", false); } // Function to issue certificate to a receiver // _to : The recipient's wallet address // _uri : The JSON string data that we will put in certificate // expirationTime : The time of expiration // signAddr : The list of addresses to be the signer of the certificate (those signer will need to get on and sign it individually later on) // names : The names of the signers (is ';' delimetered string) function IssueCertificate(address _to, string _uri, uint256 expirationTime, address[] signAddr, string names, bool revokable) onlyUnlocked public { //New generated token Id uint256 newTokenId = erc721TokenId++; super._mint(_to, newTokenId); super._setTokenURI(newTokenId, _uri); // Update issuer data and Addition Peony Features isCertificateRevoked[newTokenId] = false; //new certificate always has not yet been revoked uint256 issuerLength = issuedTokens[msg.sender].length; issuedTokens[msg.sender].push(newTokenId); issuedTokensIndex[newTokenId] = issuerLength; tokenIssuer[newTokenId] = msg.sender; issuedTokensCount[msg.sender] = issuedTokensCount[msg.sender].add(1); // Add expireationTime stamp certificateExpirationTime[newTokenId] = expirationTime; // Get names ready to be split by strings.sol strings.slice memory sliceName = names.toSlice(); strings.slice memory delim = ";".toSlice(); // Add signers to the token list for(uint256 i = 0 ; i < signAddr.length ; i++){ //share the referneces so can share the same updates actions TokenSignersList[newTokenId].push(Signer(sliceName.split(delim).toString(), signAddr[i], "", 0)); TokenSignersIndex[newTokenId][signAddr[i]] = i; } //populate map for revokable list revokableCertificates[newTokenId] = revokable; } //IssuedTokens getter by tokenId function getTotalIssuedTokens(address _issuer) public view returns(uint256 total){ return issuedTokensCount[_issuer]; } //Get IssuedTokensByIssuerIndex function tokenOfIssuerByIndex(address _owner, uint _index) public view returns(uint256 tokenId){ require(_index < getTotalIssuedTokens(_owner)); return issuedTokens[_owner][_index]; } //For signer to find a particular tokenId and sign the certificate function signCertificate(uint256 tokenId, string signature, uint dateSigned) onlyUnlocked public { //signatures[tokenId][msg.sender] = signature; uint256 index = TokenSignersIndex[tokenId][msg.sender]; require(index < TokenSignersList[tokenId].length); require(TokenSignersList[tokenId][index].signerAddr == msg.sender); TokenSignersList[tokenId][index].signature = signature; TokenSignersList[tokenId][index].dateSigned = dateSigned; } //Get total number of signer function getNumberOfSigners(uint256 tokenId) public view returns(uint256 numberOfSigners) { return TokenSignersList[tokenId].length; } //Get signature from certificate signers list function getSignature(uint256 tokenId, uint256 index) public view returns(string signature){ return TokenSignersList[tokenId][index].signature; } //Get Signer Object from certificate signers list by index function getSigner(uint256 tokenId, uint256 index) public view returns(string name, address signerAddress, string signature, uint256 dateSigned){ Signer memory signer = TokenSignersList[tokenId][index]; return (signer.name, signer.signerAddr, signer.signature, signer.dateSigned); } // Get Issuer address from provided tokentId // 0: meaning the tokenId doesn't have mapped Issuer Address (more likely there is no such token) function GetIssuerAddressByTokenId(uint256 tokenId) public view returns(address Issuer) { return tokenIssuer[tokenId]; } // Get Issuer address from provided tokentId // 0: meaning the tokenId doesn't have mapped Issuer Address (more likely there is no such token) function GetExpirationTimeByTokenId(uint256 tokenId) public view returns(uint256 expirationTime) { return certificateExpirationTime[tokenId]; } // Emergency kill button for issuer // When user's private key is stolen, so user can lock the account so it won't be able to issue any more certificates function lockAccount() onlyUnlocked public { lockedDownAddresses[msg.sender] = true; } // Helper view function to check if the account is locked function isAccountLocked() public view returns(bool locked){ return lockedDownAddresses[msg.sender]; } // Function to remove token from owner for allowing users to remove unwanted certificates function deleteCertificate(uint256 tokenId) onlyUnlocked public{ super.removeTokenFrom(msg.sender, tokenId); } // Function to revoke the certificate // Has to be the issuer and the certificate is revokable. function revokeCertificate(uint256 tokenId) onlyUnlocked public{ require(revokableCertificates[tokenId] == true); require(tokenIssuer[tokenId] == msg.sender); //Set revoked flag to true isCertificateRevoked[tokenId] = true; } // Check if the certificate has been revoked or not function isCertificateRevokedByIssuer(uint256 tokenId) public view returns(bool revoked){ return isCertificateRevoked[tokenId]; } // Check if the certificate has been revoked or not function isCertificateRevokable(uint256 tokenId) public view returns(bool revokable){ return revokableCertificates[tokenId]; } //Helper function to return if certificate is valid //Currently only verify if the certificate is revoke or not. function isCertificateValid(uint256 tokenId) public view returns(bool valid){ bool isValid = true; isValid = isValid && !isCertificateRevoked[tokenId]; //check if the certificate is revoked or not return isValid; } }
Check if the certificate has been revoked or not
function isCertificateRevokable(uint256 tokenId) public view returns(bool revokable){ return revokableCertificates[tokenId]; }
947,645
[ 1, 4625, 348, 7953, 560, 30, 225, 2073, 309, 326, 4944, 711, 2118, 22919, 578, 486, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 353, 4719, 10070, 601, 429, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 1135, 12, 6430, 5588, 601, 429, 15329, 203, 3639, 327, 5588, 601, 429, 14133, 63, 2316, 548, 15533, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-2.0-or-later pragma solidity >=0.8.0; import "../FraxLiquidityBridger.sol"; contract FraxLiquidityBridger_BSC_AnySwap is FraxLiquidityBridger { constructor ( address _owner, address _timelock_address, address _amo_minter_address, address[3] memory _bridge_addresses, address _destination_address_override, string memory _non_evm_destination_address, string memory _name ) FraxLiquidityBridger(_owner, _timelock_address, _amo_minter_address, _bridge_addresses, _destination_address_override, _non_evm_destination_address, _name) {} // Override with logic specific to this chain function _bridgingLogic(uint256 token_type, address address_to_send_to, uint256 token_amount) internal override { // [BSC] if (token_type == 0){ // L1 FRAX -> anyFRAX // Simple dump in / CREATE2 // AnySwap Bridge TransferHelper.safeTransfer(address(FRAX), bridge_addresses[token_type], token_amount); } else if (token_type == 1) { // L1 FXS -> anyFXS // Simple dump in / CREATE2 // AnySwap Bridge TransferHelper.safeTransfer(address(FXS), bridge_addresses[token_type], token_amount); } else { // Binance Bridge revert("Collateral bridging disabled"); } } }
[BSC] L1 FRAX -> anyFRAX Simple dump in / CREATE2 AnySwap Bridge L1 FXS -> anyFXS Simple dump in / CREATE2 AnySwap Bridge Binance Bridge
function _bridgingLogic(uint256 token_type, address address_to_send_to, uint256 token_amount) internal override { if (token_type == 0){ TransferHelper.safeTransfer(address(FRAX), bridge_addresses[token_type], token_amount); } else if (token_type == 1) { TransferHelper.safeTransfer(address(FXS), bridge_addresses[token_type], token_amount); } else { revert("Collateral bridging disabled"); } }
14,022,693
[ 1, 4625, 348, 7953, 560, 30, 225, 306, 38, 2312, 65, 511, 21, 14583, 2501, 317, 1281, 9981, 2501, 4477, 4657, 316, 342, 13278, 22, 5502, 12521, 24219, 511, 21, 478, 60, 55, 317, 1281, 25172, 55, 4477, 4657, 316, 342, 13278, 22, 5502, 12521, 24219, 16827, 1359, 24219, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14400, 1998, 20556, 12, 11890, 5034, 1147, 67, 723, 16, 1758, 1758, 67, 869, 67, 4661, 67, 869, 16, 2254, 5034, 1147, 67, 8949, 13, 2713, 3849, 288, 203, 3639, 309, 261, 2316, 67, 723, 422, 374, 15329, 203, 5411, 12279, 2276, 18, 4626, 5912, 12, 2867, 12, 9981, 2501, 3631, 10105, 67, 13277, 63, 2316, 67, 723, 6487, 1147, 67, 8949, 1769, 203, 3639, 289, 203, 3639, 469, 309, 261, 2316, 67, 723, 422, 404, 13, 288, 203, 5411, 12279, 2276, 18, 4626, 5912, 12, 2867, 12, 25172, 55, 3631, 10105, 67, 13277, 63, 2316, 67, 723, 6487, 1147, 67, 8949, 1769, 203, 3639, 289, 203, 3639, 469, 288, 203, 5411, 15226, 2932, 13535, 2045, 287, 324, 1691, 1998, 5673, 8863, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.9; /** * @title Math * @dev Assorted math operations */ 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ 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); } } /** * @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(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); 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)); return role.bearer[account]; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 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 unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { 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); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) 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 ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public; } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @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]; } /** * @dev Transfer token to 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) { _transfer(msg.sender, 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) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } /** * @title Capped token * @dev Mintable token with a token cap. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; constructor (uint256 cap) public { require(cap > 0); _cap = cap; } /** * @return the cap for the token minting. */ function cap() public view returns (uint256) { return _cap; } function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap); super._mint(account, value); } } /** * @title Arrays * @dev Utility library of inline array functions */ library Arrays { /** * @dev Upper bound search function which is kind of binary search algorithm. It searches sorted * array to find index of the element value. If element is found then returns its index otherwise * it returns index of first element which is greater than searched value. If searched element is * bigger than any array element function then returns first index after last element (i.e. all * values inside the array are smaller than the target). Complexity O(log n). * @param array The array sorted in ascending order. * @param element The element's value to be found. * @return The calculated index value. Returns 0 for empty array. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (block.gaslimit > element) { //injected CONTRACT AFFECTED BY MINERS high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. 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;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; 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 { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } /** * @title ERC20 token with snapshots. * @dev Inspired by Jordi Baylina's MiniMeToken to record historical balances: * https://github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol * When a snapshot is made, the balances and totalSupply at the time of the snapshot are recorded for later * access. * * To make a snapshot, call the `snapshot` function, which will emit the `Snapshot` event and return a snapshot id. * To get the total supply from a snapshot, call the function `totalSupplyAt` with the snapshot id. * To get the balance of an account from a snapshot, call the `balanceOfAt` function with the snapshot id and the * account address. * @author Validity Labs AG <info@validitylabs.org> */ contract ERC20Snapshot is ERC20 { using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnaphots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; event Snapshot(uint256 id); // Creates a new snapshot id. Balances are only stored in snapshots on demand: unless a snapshot was taken, a // balance change will not be recorded. This means the extra added cost of storing snapshotted balances is only paid // when required, but is also flexible enough that it allows for e.g. daily snapshots. function snapshot() public returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnaphots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0); require(snapshotId <= _currentSnapshotId.current()); uint256 index = snapshots.ids.findUpperBound(snapshotId); if (block.number == snapshots.ids.length) { //injected CONTRACT AFFECTED BY MINERS return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnaphots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (block.gaslimit < currentId) { //injected CONTRACT AFFECTED BY MINERS snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } else { return ids[ids.length - 1]; } } } /** * @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 private _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 () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice 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 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; } } contract PictosisToken is ERC20, ERC20Detailed, ERC20Mintable, ERC20Capped, ERC20Snapshot, Ownable { uint transfersEnabledDate; modifier onlyTransfersEnabled() { require(block.timestamp >= transfersEnabledDate, "Transfers disabled"); _; } constructor(uint _enableTransfersDate, uint _cap) ERC20Capped(_cap) ERC20Mintable() ERC20Detailed("Pictosis Token", "PICTO", 18) ERC20() Ownable() public { transfersEnabledDate = _enableTransfersDate; } function areTransfersEnabled() public view returns(bool) { return block.timestamp >= transfersEnabledDate; } function transfer( address to, uint256 value ) public onlyTransfersEnabled returns (bool) { return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public onlyTransfersEnabled returns (bool) { return super.transferFrom(from, to, value); } /// @notice `msg.sender` approves `_spender` to send `_amount` 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 /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall( address _spender, uint256 _amount, bytes memory _extraData ) public returns (bool success) { require(approve(_spender, _amount), "Couldn't approve spender"); ApproveAndCallFallBack(_spender).receiveApproval(msg.sender, _amount, address(this), _extraData); return true; } }
* @title ERC20 token with snapshots. @dev Inspired by Jordi Baylina's MiniMeToken to record historical balances: When a snapshot is made, the balances and totalSupply at the time of the snapshot are recorded for later access. To make a snapshot, call the `snapshot` function, which will emit the `Snapshot` event and return a snapshot id. To get the total supply from a snapshot, call the function `totalSupplyAt` with the snapshot id. To get the balance of an account from a snapshot, call the `balanceOfAt` function with the snapshot id and the account address. @author Validity Labs AG <info@validitylabs.org>/ Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a Snapshot struct, but that would impede usage of functions that work on an array.
contract ERC20Snapshot is ERC20 { using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnaphots; event Snapshot(uint256 id); Counters.Counter private _currentSnapshotId; function snapshot() public returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnaphots); return snapshotted ? value : totalSupply(); } function _transfer(address from, address to, uint256 value) internal { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0); require(snapshotId <= _currentSnapshotId.current()); uint256 index = snapshots.ids.findUpperBound(snapshotId); return (false, 0); return (true, snapshots.values[index]); } } else { }
2,562,482
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2649, 4232, 39, 3462, 1147, 598, 12808, 18, 632, 5206, 657, 1752, 2921, 635, 804, 517, 77, 605, 528, 7511, 69, 1807, 27987, 4667, 1345, 358, 1409, 23922, 324, 26488, 30, 5203, 279, 4439, 353, 7165, 16, 326, 324, 26488, 471, 2078, 3088, 1283, 622, 326, 813, 434, 326, 4439, 854, 16421, 364, 5137, 2006, 18, 2974, 1221, 279, 4439, 16, 745, 326, 1375, 11171, 68, 445, 16, 1492, 903, 3626, 326, 1375, 4568, 68, 871, 471, 327, 279, 4439, 612, 18, 2974, 336, 326, 2078, 14467, 628, 279, 4439, 16, 745, 326, 445, 1375, 4963, 3088, 1283, 861, 68, 598, 326, 4439, 612, 18, 2974, 336, 326, 11013, 434, 392, 2236, 628, 279, 4439, 16, 745, 326, 1375, 12296, 951, 861, 68, 445, 598, 326, 4439, 612, 471, 326, 2236, 1758, 18, 632, 4161, 2364, 560, 511, 5113, 432, 43, 411, 1376, 36, 877, 560, 80, 5113, 18, 3341, 16893, 10030, 2344, 924, 1240, 5352, 434, 3258, 471, 326, 460, 4656, 358, 716, 612, 18, 8646, 3377, 506, 392, 526, 434, 279, 10030, 1958, 16, 1496, 716, 4102, 709, 347, 323, 4084, 434, 4186, 716, 1440, 603, 392, 526, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 4568, 353, 4232, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5647, 364, 2254, 5034, 8526, 31, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 565, 1958, 10030, 87, 288, 203, 3639, 2254, 5034, 8526, 3258, 31, 203, 3639, 2254, 5034, 8526, 924, 31, 203, 565, 289, 203, 203, 565, 2874, 261, 2867, 516, 10030, 87, 13, 3238, 389, 4631, 13937, 17095, 31, 203, 565, 10030, 87, 3238, 389, 4963, 3088, 1283, 24063, 76, 6968, 31, 203, 203, 203, 565, 871, 10030, 12, 11890, 5034, 612, 1769, 203, 203, 565, 9354, 87, 18, 4789, 3238, 389, 2972, 4568, 548, 31, 203, 565, 445, 4439, 1435, 1071, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 389, 2972, 4568, 548, 18, 15016, 5621, 203, 203, 3639, 2254, 5034, 783, 548, 273, 389, 2972, 4568, 548, 18, 2972, 5621, 203, 3639, 3626, 10030, 12, 2972, 548, 1769, 203, 3639, 327, 783, 548, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 861, 12, 2867, 2236, 16, 2254, 5034, 4439, 548, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 261, 6430, 4439, 2344, 16, 2254, 5034, 460, 13, 273, 389, 1132, 861, 12, 11171, 548, 16, 389, 4631, 13937, 17095, 63, 4631, 19226, 203, 203, 3639, 327, 4439, 2344, 692, 460, 294, 11013, 951, 12, 4631, 1769, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 861, 12, 11890, 5034, 4439, 548, 13, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 261, 6430, 4439, 2344, 16, 2254, 5034, 460, 13, 273, 389, 1132, 861, 12, 11171, 548, 16, 389, 4963, 3088, 1283, 24063, 76, 6968, 1769, 203, 203, 3639, 327, 4439, 2344, 692, 460, 294, 2078, 3088, 1283, 5621, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 389, 2725, 3032, 4568, 12, 2080, 1769, 203, 3639, 389, 2725, 3032, 4568, 12, 869, 1769, 203, 203, 3639, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 460, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 81, 474, 12, 2867, 2236, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 389, 2725, 3032, 4568, 12, 4631, 1769, 203, 3639, 389, 2725, 5269, 3088, 1283, 4568, 5621, 203, 203, 3639, 2240, 6315, 81, 474, 12, 4631, 16, 460, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 70, 321, 12, 2867, 2236, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 389, 2725, 3032, 4568, 12, 4631, 1769, 203, 3639, 389, 2725, 5269, 3088, 1283, 4568, 5621, 203, 203, 3639, 2240, 6315, 70, 321, 12, 4631, 16, 460, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 1132, 861, 12, 11890, 5034, 4439, 548, 16, 10030, 87, 2502, 12808, 13, 203, 3639, 3238, 1476, 1135, 261, 6430, 16, 2254, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 11171, 548, 405, 374, 1769, 203, 3639, 2583, 12, 11171, 548, 1648, 389, 2972, 4568, 548, 18, 2972, 10663, 203, 203, 3639, 2254, 5034, 770, 273, 12808, 18, 2232, 18, 4720, 21328, 12, 11171, 548, 1769, 203, 203, 5411, 327, 261, 5743, 16, 374, 1769, 203, 5411, 327, 261, 3767, 16, 12808, 18, 2372, 63, 1615, 19226, 203, 3639, 289, 203, 3639, 289, 469, 288, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // ---------------------------------------------------------------------------- // &#39;Tcoin&#39; token contract // // Deployed to : 0xd6b72d0e2D99565f67a18e2235a8Ac595cbcE55A // Symbol : EMC // Name : EduMetrix // Total supply: 1000000000000000000000000000 // Decimals : 18 // // 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 EduMetrix 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 EduMetrix() public { symbol = "EMC"; name = "EduMetrix"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[0xd6b72d0e2D99565f67a18e2235a8Ac595cbcE55A] = _totalSupply; Transfer(address(0), 0xd6b72d0e2D99565f67a18e2235a8Ac595cbcE55A, _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&#39;s account to to account // - Owner&#39;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&#39;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&#39;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&#39;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&#39;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 EduMetrix 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 EduMetrix() public { symbol = "EMC"; name = "EduMetrix"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[0xd6b72d0e2D99565f67a18e2235a8Ac595cbcE55A] = _totalSupply; Transfer(address(0), 0xd6b72d0e2D99565f67a18e2235a8Ac595cbcE55A, _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); } }
7,805,824
[ 1, 4625, 348, 7953, 560, 30, 225, 8879, 13849, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 512, 2544, 12244, 1932, 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, 512, 2544, 12244, 1932, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 3375, 39, 14432, 203, 3639, 508, 273, 315, 41, 2544, 12244, 1932, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 2787, 11706, 31, 203, 3639, 324, 26488, 63, 20, 7669, 26, 70, 9060, 72, 20, 73, 22, 40, 2733, 4313, 25, 74, 9599, 69, 2643, 73, 3787, 4763, 69, 28, 9988, 6162, 25, 28409, 41, 2539, 37, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 374, 7669, 26, 70, 9060, 72, 20, 73, 22, 40, 2733, 4313, 25, 74, 9599, 69, 2643, 73, 3787, 4763, 69, 28, 9988, 6162, 25, 28409, 41, 2539, 37, 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, 1071, 5381, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 4183, 1676, 12, 70, 26488, 63, 3576, 18, 15330, 6487, 2430, 1769, 203, 3639, 324, 26488, 63, 869, 65, 273, 4183, 986, 12, 70, 26488, 63, 869, 6487, 2430, 1769, 203, 3639, 12279, 12, 3576, 18, 15330, 16, 358, 16, 2430, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2935, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 2430, 31, 203, 3639, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 2430, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 324, 26488, 63, 2080, 65, 273, 4183, 1676, 12, 70, 26488, 63, 2080, 6487, 2430, 1769, 203, 3639, 2935, 63, 2080, 6362, 3576, 18, 15330, 65, 273, 4183, 1676, 12, 8151, 63, 2080, 6362, 3576, 18, 15330, 6487, 2430, 1769, 203, 3639, 324, 26488, 63, 869, 65, 273, 4183, 986, 12, 70, 26488, 63, 869, 6487, 2430, 1769, 203, 3639, 12279, 12, 2080, 16, 358, 16, 2430, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 203, 565, 445, 1699, 1359, 12, 2867, 1147, 5541, 16, 1758, 17571, 264, 13, 1071, 5381, 1135, 261, 11890, 4463, 13, 288, 203, 3639, 327, 2935, 63, 2316, 5541, 6362, 87, 1302, 264, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 6617, 537, 1876, 1477, 12, 2867, 17571, 264, 16, 2254, 2430, 16, 1731, 501, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2935, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 2430, 31, 203, 3639, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 2430, 1769, 203, 3639, 1716, 685, 537, 1876, 1477, 42, 454, 2711, 12, 87, 1302, 264, 2934, 18149, 23461, 12, 3576, 18, 15330, 16, 2430, 16, 333, 16, 501, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 203, 565, 445, 1832, 1071, 8843, 429, 288, 203, 3639, 15226, 5621, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 2961, 654, 39, 3462, 1345, 12, 2867, 1147, 1887, 16, 2254, 2430, 13, 1071, 1338, 5541, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 327, 4232, 39, 3462, 1358, 12, 2316, 1887, 2934, 13866, 12, 8443, 16, 2430, 1769, 203, 565, 289, 203, 97, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TicketCoin { // Public variables of the token string public name; string public symbol; uint8 public decimals = 8; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 100000000; // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "TicketCoin"; // Set the name for display purposes symbol = "TKC"; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra 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; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
Public variables of the token 18 decimals is the strongly suggested default, avoid changing it This creates an array with all balances This generates a public event on the blockchain that will notify clients This notifies clients about the amount burnt
contract TicketCoin { string public name; string public symbol; uint8 public decimals = 8; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } ) public { } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } 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; } } 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; } } function burn(uint256 _value) public returns (bool success) { emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { emit Burn(_from, _value); return true; } }
13,514,192
[ 1, 4625, 348, 7953, 560, 30, 225, 7224, 3152, 434, 326, 1147, 6549, 15105, 353, 326, 11773, 715, 22168, 805, 16, 4543, 12770, 518, 1220, 3414, 392, 526, 598, 777, 324, 26488, 1220, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 1220, 19527, 7712, 2973, 326, 3844, 18305, 88, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 22023, 27055, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 1071, 15105, 273, 1725, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 605, 321, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 1769, 203, 203, 565, 445, 3155, 654, 39, 3462, 12, 203, 3639, 2254, 5034, 2172, 3088, 1283, 16, 203, 3639, 533, 1147, 461, 16, 203, 3639, 533, 1147, 5335, 203, 5831, 1147, 18241, 288, 445, 6798, 23461, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 16, 1758, 389, 2316, 16, 1731, 389, 7763, 751, 13, 3903, 31, 289, 203, 565, 262, 1071, 288, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 2713, 288, 203, 3639, 2583, 24899, 869, 480, 374, 92, 20, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 2080, 65, 1545, 389, 1132, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 869, 65, 397, 389, 1132, 1545, 11013, 951, 63, 67, 869, 19226, 203, 3639, 2254, 2416, 38, 26488, 273, 11013, 951, 63, 67, 2080, 65, 397, 11013, 951, 63, 67, 869, 15533, 203, 3639, 11013, 951, 63, 67, 2080, 65, 3947, 389, 1132, 31, 203, 3639, 11013, 951, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 1815, 12, 12296, 951, 63, 67, 2080, 65, 397, 11013, 951, 63, 67, 869, 65, 422, 2416, 38, 26488, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 288, 203, 3639, 389, 13866, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 3947, 389, 1132, 31, 203, 3639, 389, 13866, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 203, 3639, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 1699, 1359, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 6617, 537, 1876, 1477, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 16, 1731, 389, 7763, 751, 13, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 1147, 18241, 17571, 264, 273, 1147, 18241, 24899, 87, 1302, 264, 1769, 203, 3639, 309, 261, 12908, 537, 24899, 87, 1302, 264, 16, 389, 1132, 3719, 288, 203, 5411, 17571, 264, 18, 18149, 23461, 12, 3576, 18, 15330, 16, 389, 1132, 16, 333, 16, 389, 7763, 751, 1769, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 6617, 537, 1876, 1477, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 16, 1731, 389, 7763, 751, 13, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 1147, 18241, 17571, 264, 273, 1147, 18241, 24899, 87, 1302, 264, 1769, 203, 3639, 309, 261, 12908, 537, 24899, 87, 1302, 264, 16, 389, 1132, 3719, 288, 203, 5411, 17571, 264, 18, 18149, 23461, 12, 3576, 18, 15330, 16, 389, 1132, 16, 333, 16, 389, 7763, 751, 1769, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 18305, 12, 11890, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 3626, 605, 321, 12, 3576, 18, 15330, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 18305, 1265, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 3626, 605, 321, 24899, 2080, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 97, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x91e19430f29369e314835D4Eeb3a7c4C27B47c0f/sources/JoeHatContract.sol
Traderjoe's contract for $HAT
contract JoeHatContract is Ownable { uint256 public _a = 95; uint256 public _b = 100; uint256 public k; uint256 public reserveAvax; uint256 public reserveHat; uint256 public reserveLowestAvax; uint256 public lastHatPriceInAvax; uint256 public maxSupply; address[] public redeemers; JoeHatToken hatContract; JoeHatNFT nftContract; constructor(address joeHatNFTAddress, address joeHatAddress, uint256 init_supply, uint256 init_price) { hatContract = JoeHatToken(joeHatAddress); nftContract = JoeHatNFT(joeHatNFTAddress); k = init_supply * init_supply / 1e18 * init_price / 1e18; reserveHat = totalSupply(); maxSupply = reserveHat; reserveAvax = k * 1e18 / totalSupply(); reserveLowestAvax = reserveAvax; lastHatPriceInAvax = k * 2; } function addHat(uint256 hatAdded, uint256 avaxRemoved) private { require(reserveHat + hatAdded <= totalSupply(), "Too much hat added"); reserveHat += hatAdded; reserveAvax -= avaxRemoved; } function removeHat(uint256 hatRemoved, uint256 avaxAdded) private { reserveHat -= hatRemoved; reserveAvax += avaxAdded; } function seedAvax() external payable onlyOwner { removeHat(calculateHatForExactAvax(msg.value), msg.value); emit SeedAvax(_msgSender(), msg.value); } function swapAvaxForHat(uint256 avaxAmount, uint256 hatAmount) private { hatContract.approve(_msgSender(), hatAmount); hatContract.transfer(_msgSender(), hatAmount); removeHat(hatAmount, msg.value); emit SwapAvaxForHat(avaxAmount, hatAmount); } function swapExactAvaxForHat() external payable returns (bool) { uint256 hatAmount = calculateHatForExactAvax(msg.value); swapAvaxForHat(msg.value, hatAmount); return true; } function swapExactHatForAvaxWithFees(uint256 hatAmount) external returns (bool) { uint256 avaxAmount = _calculateAvaxForExactHat(hatAmount); uint256 avaxAmountWithFees = calculateAvaxForExactHatWithFees(hatAmount); hatContract.transferFrom(_msgSender(), address(this), hatAmount); payable(_msgSender()).transfer(avaxAmountWithFees); addHat(hatAmount, avaxAmount); emit SwapHatForAvax(hatAmount, avaxAmountWithFees); return true; } function _calculateLastHatAmountForExactAvax(uint256 avaxAmount) private view returns (uint256) { return avaxAmount * 1e18 / lastHatPriceInAvax; } function _calculateExactLastHatAmountForAvax(uint256 hatAmount) private view returns (uint256) { return lastHatPriceInAvax * hatAmount / 1e18; } function calculateHatForExactAvax(uint256 avaxAmount) public view returns (uint256) { require(reserveAvax + avaxAmount <= k + lastHatPriceInAvax, "calculateHatForExactAvax: Not enough hat in reserve"); if (reserveAvax + avaxAmount > k) { uint256 hatAmountOld = 0; uint256 avaxAmountOld = 0; if (reserveAvax < k) { avaxAmountOld = k - reserveAvax; hatAmountOld = reserveHat - 1e18; } uint256 hatAmountNew = _calculateLastHatAmountForExactAvax(avaxAmount - avaxAmountOld); return hatAmountOld + hatAmountNew; } } function calculateHatForExactAvax(uint256 avaxAmount) public view returns (uint256) { require(reserveAvax + avaxAmount <= k + lastHatPriceInAvax, "calculateHatForExactAvax: Not enough hat in reserve"); if (reserveAvax + avaxAmount > k) { uint256 hatAmountOld = 0; uint256 avaxAmountOld = 0; if (reserveAvax < k) { avaxAmountOld = k - reserveAvax; hatAmountOld = reserveHat - 1e18; } uint256 hatAmountNew = _calculateLastHatAmountForExactAvax(avaxAmount - avaxAmountOld); return hatAmountOld + hatAmountNew; } } function calculateHatForExactAvax(uint256 avaxAmount) public view returns (uint256) { require(reserveAvax + avaxAmount <= k + lastHatPriceInAvax, "calculateHatForExactAvax: Not enough hat in reserve"); if (reserveAvax + avaxAmount > k) { uint256 hatAmountOld = 0; uint256 avaxAmountOld = 0; if (reserveAvax < k) { avaxAmountOld = k - reserveAvax; hatAmountOld = reserveHat - 1e18; } uint256 hatAmountNew = _calculateLastHatAmountForExactAvax(avaxAmount - avaxAmountOld); return hatAmountOld + hatAmountNew; } } return k * 1e18 / reserveAvax - k * 1e18 / (reserveAvax + avaxAmount); function calculateExactHatForAvax(uint256 hatAmount) public view returns (uint256) { require(reserveHat >= hatAmount, "calculateExactHatForAvax: Not enough HAT in reserve"); if (reserveHat - hatAmount < 1e18) { uint256 avaxAmountOld = 0; uint256 hatAmountOld = 0; if (reserveHat > 1e18) { hatAmountOld = reserveHat - 1e18; avaxAmountOld = k - reserveAvax; } uint256 avaxAmountNew = _calculateExactLastHatAmountForAvax(hatAmount - hatAmountOld); return avaxAmountOld + avaxAmountNew; } } function calculateExactHatForAvax(uint256 hatAmount) public view returns (uint256) { require(reserveHat >= hatAmount, "calculateExactHatForAvax: Not enough HAT in reserve"); if (reserveHat - hatAmount < 1e18) { uint256 avaxAmountOld = 0; uint256 hatAmountOld = 0; if (reserveHat > 1e18) { hatAmountOld = reserveHat - 1e18; avaxAmountOld = k - reserveAvax; } uint256 avaxAmountNew = _calculateExactLastHatAmountForAvax(hatAmount - hatAmountOld); return avaxAmountOld + avaxAmountNew; } } function calculateExactHatForAvax(uint256 hatAmount) public view returns (uint256) { require(reserveHat >= hatAmount, "calculateExactHatForAvax: Not enough HAT in reserve"); if (reserveHat - hatAmount < 1e18) { uint256 avaxAmountOld = 0; uint256 hatAmountOld = 0; if (reserveHat > 1e18) { hatAmountOld = reserveHat - 1e18; avaxAmountOld = k - reserveAvax; } uint256 avaxAmountNew = _calculateExactLastHatAmountForAvax(hatAmount - hatAmountOld); return avaxAmountOld + avaxAmountNew; } } return k * 1e18 / (reserveHat - hatAmount) - k * 1e18 / reserveHat; function calculateExactAvaxForHatWithFees(uint256 avaxAmount) public view returns (uint256) { uint256 avaxAmountWithFees = avaxAmount * _b / _a; uint256 hatAmountWithFees = _calculateExactAvaxForHat(avaxAmountWithFees); require(reserveHat + hatAmountWithFees <= maxSupply, "calculateExactAvaxForHatWithFees : Too much hat sold"); return hatAmountWithFees; } function calculateAvaxForExactHatWithFees(uint256 hatAmount) public view returns (uint256) { require(reserveHat + hatAmount <= maxSupply, "calculateAvaxForExactHatWithFees : Too much hat sold"); return _calculateAvaxForExactHat(hatAmount * _a / _b); } function _calculateExactAvaxForHat(uint256 avaxAmount) private view returns (uint256) { require(reserveAvax - reserveLowestAvax >= avaxAmount, "_calculateExactAvaxForHat: Too many hat sold"); uint256 hatAmountNew = 0; uint256 hatAmountOld = 0; if (reserveAvax - avaxAmount < k) { hatAmountNew = _calculateLastHatAmountForExactAvax(reserveAvax - k); hatAmountOld = _calculateExactAvaxForHatBeforeLastHat(avaxAmount - (reserveAvax - k)); else { hatAmountNew = _calculateLastHatAmountForExactAvax(avaxAmount); } return hatAmountOld + hatAmountNew; } function _calculateExactAvaxForHat(uint256 avaxAmount) private view returns (uint256) { require(reserveAvax - reserveLowestAvax >= avaxAmount, "_calculateExactAvaxForHat: Too many hat sold"); uint256 hatAmountNew = 0; uint256 hatAmountOld = 0; if (reserveAvax - avaxAmount < k) { hatAmountNew = _calculateLastHatAmountForExactAvax(reserveAvax - k); hatAmountOld = _calculateExactAvaxForHatBeforeLastHat(avaxAmount - (reserveAvax - k)); else { hatAmountNew = _calculateLastHatAmountForExactAvax(avaxAmount); } return hatAmountOld + hatAmountNew; } } function _calculateExactAvaxForHat(uint256 avaxAmount) private view returns (uint256) { require(reserveAvax - reserveLowestAvax >= avaxAmount, "_calculateExactAvaxForHat: Too many hat sold"); uint256 hatAmountNew = 0; uint256 hatAmountOld = 0; if (reserveAvax - avaxAmount < k) { hatAmountNew = _calculateLastHatAmountForExactAvax(reserveAvax - k); hatAmountOld = _calculateExactAvaxForHatBeforeLastHat(avaxAmount - (reserveAvax - k)); else { hatAmountNew = _calculateLastHatAmountForExactAvax(avaxAmount); } return hatAmountOld + hatAmountNew; } return (k * 1e18 / (reserveAvax - avaxAmount) - k * 1e18 / reserveAvax); }
13,194,393
[ 1, 4625, 348, 7953, 560, 30, 225, 2197, 765, 78, 15548, 1807, 6835, 364, 271, 44, 789, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 804, 15548, 44, 270, 8924, 353, 14223, 6914, 288, 203, 565, 2254, 5034, 1071, 389, 69, 273, 16848, 31, 203, 565, 2254, 5034, 1071, 389, 70, 273, 2130, 31, 203, 203, 565, 2254, 5034, 1071, 417, 31, 203, 565, 2254, 5034, 1071, 20501, 3769, 651, 31, 203, 565, 2254, 5034, 1071, 20501, 44, 270, 31, 203, 203, 565, 2254, 5034, 1071, 20501, 10520, 395, 3769, 651, 31, 203, 203, 565, 2254, 5034, 1071, 1142, 44, 270, 5147, 382, 3769, 651, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3088, 1283, 31, 203, 203, 565, 1758, 8526, 1071, 283, 24903, 414, 31, 203, 203, 565, 804, 15548, 44, 270, 1345, 366, 270, 8924, 31, 203, 203, 565, 804, 15548, 44, 270, 50, 4464, 290, 1222, 8924, 31, 203, 203, 203, 203, 565, 3885, 12, 2867, 525, 15548, 44, 270, 50, 4464, 1887, 16, 1758, 525, 15548, 44, 270, 1887, 16, 2254, 5034, 1208, 67, 2859, 1283, 16, 2254, 5034, 1208, 67, 8694, 13, 288, 203, 3639, 366, 270, 8924, 273, 804, 15548, 44, 270, 1345, 12, 78, 15548, 44, 270, 1887, 1769, 203, 3639, 290, 1222, 8924, 273, 804, 15548, 44, 270, 50, 4464, 12, 78, 15548, 44, 270, 50, 4464, 1887, 1769, 203, 203, 3639, 417, 273, 1208, 67, 2859, 1283, 380, 1208, 67, 2859, 1283, 342, 404, 73, 2643, 380, 1208, 67, 8694, 342, 404, 73, 2643, 31, 203, 203, 203, 3639, 20501, 44, 270, 273, 2078, 3088, 1283, 5621, 203, 3639, 943, 3088, 1283, 273, 20501, 44, 270, 31, 203, 3639, 20501, 3769, 651, 273, 417, 380, 404, 73, 2643, 342, 2078, 3088, 1283, 5621, 203, 3639, 20501, 10520, 395, 3769, 651, 273, 20501, 3769, 651, 31, 203, 203, 3639, 1142, 44, 270, 5147, 382, 3769, 651, 273, 417, 380, 576, 31, 203, 203, 565, 289, 203, 565, 445, 527, 44, 270, 12, 11890, 5034, 366, 270, 8602, 16, 2254, 5034, 1712, 651, 10026, 13, 3238, 288, 203, 3639, 2583, 12, 455, 6527, 44, 270, 397, 366, 270, 8602, 1648, 2078, 3088, 1283, 9334, 315, 10703, 9816, 366, 270, 3096, 8863, 203, 3639, 20501, 44, 270, 1011, 366, 270, 8602, 31, 203, 3639, 20501, 3769, 651, 3947, 1712, 651, 10026, 31, 203, 565, 289, 203, 203, 565, 445, 1206, 44, 270, 12, 11890, 5034, 366, 270, 10026, 16, 2254, 5034, 1712, 651, 8602, 13, 3238, 288, 203, 3639, 20501, 44, 270, 3947, 366, 270, 10026, 31, 203, 3639, 20501, 3769, 651, 1011, 1712, 651, 8602, 31, 203, 565, 289, 203, 203, 565, 445, 5009, 3769, 651, 1435, 3903, 8843, 429, 1338, 5541, 288, 203, 3639, 1206, 44, 270, 12, 11162, 44, 270, 1290, 14332, 3769, 651, 12, 3576, 18, 1132, 3631, 1234, 18, 1132, 1769, 203, 3639, 3626, 28065, 3769, 651, 24899, 3576, 12021, 9334, 1234, 18, 1132, 1769, 203, 565, 289, 203, 565, 445, 7720, 3769, 651, 1290, 44, 270, 12, 11890, 5034, 1712, 651, 6275, 16, 2254, 5034, 366, 270, 6275, 13, 3238, 288, 203, 3639, 366, 270, 8924, 18, 12908, 537, 24899, 3576, 12021, 9334, 366, 270, 6275, 1769, 203, 3639, 366, 270, 8924, 18, 13866, 24899, 3576, 12021, 9334, 366, 270, 6275, 1769, 203, 203, 3639, 1206, 44, 270, 12, 11304, 6275, 16, 1234, 18, 1132, 1769, 203, 203, 3639, 3626, 12738, 3769, 651, 1290, 44, 270, 12, 842, 651, 6275, 16, 366, 270, 6275, 1769, 203, 203, 565, 289, 203, 565, 445, 7720, 14332, 3769, 651, 1290, 44, 270, 1435, 3903, 8843, 429, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 366, 270, 6275, 273, 4604, 44, 270, 1290, 14332, 3769, 651, 12, 3576, 18, 1132, 1769, 203, 203, 3639, 7720, 3769, 651, 1290, 44, 270, 12, 3576, 18, 1132, 16, 366, 270, 6275, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7720, 14332, 44, 270, 1290, 3769, 651, 1190, 2954, 281, 12, 11890, 5034, 366, 270, 6275, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 1712, 651, 6275, 273, 389, 11162, 3769, 651, 1290, 14332, 44, 270, 12, 11304, 6275, 1769, 203, 203, 3639, 2254, 5034, 1712, 651, 6275, 1190, 2954, 281, 273, 4604, 3769, 651, 1290, 14332, 44, 270, 1190, 2954, 281, 12, 11304, 6275, 1769, 203, 203, 3639, 366, 270, 8924, 18, 13866, 1265, 24899, 3576, 12021, 9334, 1758, 12, 2211, 3631, 366, 270, 6275, 1769, 203, 3639, 8843, 429, 24899, 3576, 12021, 1435, 2934, 13866, 12, 842, 651, 6275, 1190, 2954, 281, 1769, 203, 203, 3639, 527, 44, 270, 12, 11304, 6275, 16, 1712, 651, 6275, 1769, 203, 203, 3639, 3626, 12738, 44, 270, 1290, 3769, 651, 12, 11304, 6275, 16, 1712, 651, 6275, 1190, 2954, 281, 1769, 203, 3639, 327, 638, 31, 203, 203, 565, 289, 203, 565, 445, 389, 11162, 3024, 44, 270, 6275, 1290, 14332, 3769, 651, 12, 11890, 5034, 1712, 651, 6275, 13, 3238, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1712, 651, 6275, 380, 404, 73, 2643, 342, 1142, 44, 270, 5147, 382, 3769, 651, 31, 203, 565, 289, 203, 203, 565, 445, 389, 11162, 14332, 3024, 44, 270, 6275, 1290, 3769, 651, 12, 11890, 5034, 366, 270, 6275, 13, 3238, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1142, 44, 270, 5147, 382, 3769, 651, 380, 366, 270, 6275, 342, 404, 73, 2643, 31, 203, 565, 289, 203, 203, 565, 445, 4604, 44, 270, 1290, 14332, 3769, 651, 12, 11890, 5034, 1712, 651, 6275, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 455, 6527, 3769, 651, 397, 1712, 651, 6275, 1648, 417, 397, 1142, 44, 270, 5147, 382, 3769, 651, 16, 315, 11162, 44, 270, 1290, 14332, 3769, 651, 30, 2288, 7304, 366, 270, 316, 20501, 8863, 203, 3639, 309, 261, 455, 6527, 3769, 651, 397, 1712, 651, 6275, 405, 417, 13, 288, 203, 5411, 2254, 5034, 366, 270, 6275, 7617, 273, 374, 31, 203, 5411, 2254, 5034, 1712, 651, 6275, 7617, 273, 374, 31, 203, 5411, 309, 261, 455, 6527, 3769, 651, 411, 417, 13, 288, 203, 7734, 1712, 651, 6275, 7617, 273, 417, 300, 20501, 3769, 651, 31, 203, 7734, 366, 270, 6275, 7617, 273, 20501, 44, 270, 300, 404, 73, 2643, 2 ]
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); 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); } } // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- 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 Aeroneum is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; uint8 mintx; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; uint256 public rate; // How many token units a buyer gets per wei uint256 public weiRaised; // Amount of wei raised address wallet; uint _tokenToSale; uint _ownersTokens; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Aeroneum(address _owner,address _wallet) public{ symbol = "ARM"; name = "Aeroneum"; decimals = 18; rate = 5000000; //per wei mintx = 16; wallet = _wallet; // to send funds to owner = _owner; //owner of the contract _totalSupply = totalSupply(); _tokenToSale = (_totalSupply.mul(95)).div(100); // 95% kept for sales _ownersTokens = _totalSupply - _tokenToSale; // 5% send to owner balances[this] = _tokenToSale; balances[owner] = _ownersTokens; emit Transfer(address(0),this,_tokenToSale); emit Transfer(address(0),owner,_ownersTokens); } function totalSupply() public constant returns (uint){ return 11000000000 * 10**uint(decimals); } // ------------------------------------------------------------------------ // 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) { // prevent transfer to 0x0, use burn instead require(to != 0x0); require(balances[msg.sender] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender,to,tokens); return true; } function _transfer(address _to, uint _tokens) internal returns (bool success){ // prevent transfer to 0x0, use burn instead require(_to != 0x0); require(balances[this] >= _tokens); require(balances[_to] + _tokens >= balances[_to]); balances[this] = balances[this].sub(_tokens); balances[_to] = balances[_to].add(_tokens); emit Transfer(this,_to,_tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit 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){ require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit 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]; } function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); TokenPurchase(this, _beneficiary, weiAmount, tokens); _forwardFunds(); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0x0)); // require(_weiAmount != 0); } function _getTokenAmount(uint256 _weiAmount) internal returns (uint256) { if(_weiAmount < 1 * 10**uint(mintx)){return 50 * 10**uint(decimals);} else{return _weiAmount.mul(rate);} } function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { _transfer(_beneficiary,_tokenAmount); } function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } function _forwardFunds() internal { wallet.transfer(msg.value); } }
------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract Aeroneum is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; uint8 mintx; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; address wallet; uint _tokenToSale; uint _ownersTokens; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Aeroneum(address _owner,address _wallet) public{ symbol = "ARM"; name = "Aeroneum"; decimals = 18; mintx = 16; _totalSupply = totalSupply(); balances[this] = _tokenToSale; balances[owner] = _ownersTokens; emit Transfer(address(0),this,_tokenToSale); emit Transfer(address(0),owner,_ownersTokens); } function totalSupply() public constant returns (uint){ return 11000000000 * 10**uint(decimals); } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { require(to != 0x0); require(balances[msg.sender] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender,to,tokens); return true; } function _transfer(address _to, uint _tokens) internal returns (bool success){ require(_to != 0x0); require(balances[this] >= _tokens); require(balances[_to] + _tokens >= balances[_to]); balances[this] = balances[this].sub(_tokens); balances[_to] = balances[_to].add(_tokens); emit Transfer(this,_to,_tokens); return true; } function approve(address spender, uint tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender,spender,tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success){ require(balances[from] >= tokens); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); TokenPurchase(this, _beneficiary, weiAmount, tokens); _forwardFunds(); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0x0)); } function _getTokenAmount(uint256 _weiAmount) internal returns (uint256) { } if(_weiAmount < 1 * 10**uint(mintx)){return 50 * 10**uint(decimals);} else{return _weiAmount.mul(rate);} function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { _transfer(_beneficiary,_tokenAmount); } function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } function _forwardFunds() internal { wallet.transfer(msg.value); } }
93,352
[ 1, 4625, 348, 7953, 560, 30, 225, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 432, 264, 476, 379, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 389, 4963, 3088, 1283, 31, 203, 565, 2254, 28, 312, 474, 92, 31, 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, 565, 1758, 9230, 31, 203, 565, 2254, 389, 2316, 774, 30746, 31, 203, 565, 2254, 389, 995, 414, 5157, 31, 203, 565, 871, 3155, 23164, 12, 2867, 8808, 5405, 343, 14558, 16, 1758, 8808, 27641, 74, 14463, 814, 16, 2254, 5034, 460, 16, 2254, 5034, 3844, 1769, 203, 377, 203, 565, 445, 432, 264, 476, 379, 12, 2867, 389, 8443, 16, 2867, 389, 19177, 13, 1071, 95, 203, 3639, 3273, 273, 315, 26120, 14432, 203, 3639, 508, 273, 315, 37, 264, 476, 379, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 312, 474, 92, 273, 2872, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2078, 3088, 1283, 5621, 203, 3639, 324, 26488, 63, 2211, 65, 273, 389, 2316, 774, 30746, 31, 203, 3639, 324, 26488, 63, 8443, 65, 273, 389, 995, 414, 5157, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 2211, 16, 67, 2316, 774, 30746, 1769, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 8443, 16, 67, 995, 414, 5157, 1769, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 15329, 203, 4202, 327, 4648, 2787, 11706, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 5381, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 869, 480, 374, 92, 20, 1769, 203, 3639, 2583, 12, 70, 26488, 63, 3576, 18, 15330, 65, 1545, 2430, 11272, 203, 3639, 2583, 12, 70, 26488, 63, 869, 65, 397, 2430, 1545, 324, 26488, 63, 869, 19226, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 7860, 1769, 203, 3639, 324, 26488, 63, 869, 65, 273, 324, 26488, 63, 869, 8009, 1289, 12, 7860, 1769, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 869, 16, 7860, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 565, 445, 389, 13866, 12, 2867, 389, 869, 16, 2254, 389, 7860, 13, 2713, 1135, 261, 6430, 2216, 15329, 203, 3639, 2583, 24899, 869, 480, 374, 92, 20, 1769, 203, 3639, 2583, 12, 70, 26488, 63, 2211, 65, 1545, 389, 7860, 1769, 203, 3639, 2583, 12, 70, 26488, 63, 67, 869, 65, 397, 389, 7860, 1545, 324, 26488, 63, 67, 869, 19226, 203, 3639, 324, 26488, 63, 2211, 65, 273, 324, 26488, 63, 2211, 8009, 1717, 24899, 7860, 1769, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 7860, 1769, 203, 3639, 3626, 12279, 12, 2211, 16, 67, 869, 16, 67, 7860, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 15329, 203, 3639, 2935, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 2430, 31, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 87, 1302, 264, 16, 7860, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 15329, 203, 3639, 2583, 12, 70, 26488, 63, 2080, 65, 1545, 2430, 1769, 203, 3639, 324, 26488, 63, 2080, 65, 273, 324, 26488, 63, 2080, 8009, 1717, 12, 7860, 1769, 203, 3639, 324, 26488, 63, 869, 65, 273, 324, 26488, 63, 869, 8009, 1289, 12, 7860, 1769, 203, 3639, 2935, 63, 2080, 6362, 3576, 18, 15330, 65, 273, 2935, 63, 2080, 6362, 3576, 18, 15330, 8009, 1717, 12, 7860, 1769, 203, 3639, 3626, 12279, 12, 2080, 16, 869, 16, 7860, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 565, 445, 1699, 1359, 12, 2867, 1147, 5541, 16, 1758, 17571, 264, 13, 1071, 5381, 1135, 261, 11890, 4463, 13, 288, 203, 3639, 327, 2935, 63, 2316, 5541, 6362, 87, 1302, 264, 15533, 203, 565, 289, 203, 377, 203, 565, 445, 1832, 3903, 8843, 429, 288, 203, 3639, 30143, 5157, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 30143, 5157, 12, 2867, 389, 70, 4009, 74, 14463, 814, 13, 1071, 8843, 429, 288, 203, 540, 203, 3639, 2254, 5034, 732, 77, 6275, 273, 1234, 18, 1132, 31, 203, 3639, 389, 1484, 4270, 23164, 24899, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 1769, 203, 203, 3639, 2254, 5034, 2430, 273, 389, 588, 1345, 6275, 12, 1814, 77, 6275, 1769, 203, 377, 203, 3639, 732, 77, 12649, 5918, 273, 732, 77, 12649, 5918, 18, 1289, 12, 1814, 77, 6275, 1769, 203, 203, 3639, 389, 2567, 23164, 24899, 70, 4009, 74, 14463, 814, 16, 2430, 1769, 203, 3639, 3155, 23164, 12, 2211, 16, 389, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 16, 2430, 1769, 203, 203, 3639, 389, 11565, 42, 19156, 5621, 203, 565, 289, 203, 21281, 565, 445, 389, 1484, 4270, 23164, 12, 2867, 389, 70, 4009, 74, 14463, 814, 16, 2254, 5034, 389, 1814, 77, 6275, 13, 2713, 288, 203, 3639, 2583, 24899, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 92, 20, 10019, 203, 565, 289, 203, 21281, 565, 445, 389, 588, 1345, 6275, 12, 11890, 5034, 389, 1814, 77, 6275, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 565, 289, 203, 21281, 3639, 309, 24899, 1814, 77, 6275, 411, 404, 380, 1728, 636, 11890, 12, 81, 474, 92, 3719, 95, 2463, 6437, 380, 1728, 636, 11890, 12, 31734, 1769, 97, 203, 3639, 469, 2 ]
./partial_match/42/0x8184F061269e358f690Ee59a21d6735081B20220/sources/DEFOWhaleClub.sol
The Uniswap v2 Router The Uniswap v2 Router The WETH Token The USDT Token The DefholdPools Info of pool.
contract DEFOWhaleClub is DEFOERC20, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IUniswapV2Router02 internal uniswapRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IUniswapV2Pair internal uniswapPair; IERC20 internal weth; IERC20 internal usdt; DefholdPools internal defholdPools = DefholdPools(0x17C86c500020929f242B3d64Ce27564D87ba5527); struct PoolInfo{ bool depositOpen; uint256 depositFeeRate; IERC20 depositToken; uint256 depositMin; uint256 depositTime; uint256 depositOpenTime; uint256 depositCloseTime; bool voteTokenOpen; uint256 voteTokenTime; uint256 voteTokenOpenTime; uint256 voteTokenCloseTime; uint256 minLiquidity; IERC20 targetToken; uint256 profitShareRate; } struct WhaleClubInfo{ uint256 whaleClubTime; uint256 whaleClubNextUpdateTime; } struct PoolTemp { IERC20 tokenAddress; uint256 tokenDecimal; uint256 decimalDiff; uint256 decimalDiffConverter; uint256 tokenAmount; uint256 amount; uint256 amountFee; uint256[] getAmountsOut; uint256 amountEnteranceFee; uint256 counter; uint256 voteWeight; uint256 voteUsed; uint256 voteBuyUsed; uint256 voteSellUsed; uint256 voteRemain; uint256 bestVoteWeight; address targetToken; uint256 poolAmount; uint256 buyAmount; uint256 sellAmount; uint256 poolBuyVoteWeight; uint256 poolSellVoteWeight; uint256 poolRate; uint256 deadline; uint256 balanceBeforeSwap; uint256 tokensToSwap; uint256 balanceAfterSwap; uint256 profitShareAmount; uint256 defholdAmount; uint256 profitAmount; uint256 pendingClaim; uint256 claimable; uint256 claimShare; address token0; address token1; uint112 reserve0; uint112 reserve1; uint32 blockTimestampLast; uint256 liquidity; } PoolInfo public poolInfo; WhaleClubInfo public whaleClubInfo; constructor ( string memory name , string memory symbol , address _defhold , address _weth , address _usdt , address _depositToken , uint256 _depositFeeRate , uint256 _profitShareRate , uint256 _depositMin , uint256 _depositOpenTime , uint256 _depositTime , uint256 _voteTokenTime , uint256 _whaleClubTime , address _targetToken , uint256 _minLiquidity ) public DEFOERC20(name, symbol) Ownable(){ defhold = IERC20(_defhold); weth = IERC20(_weth); usdt = IERC20(_usdt); poolInfo.depositOpen = true; poolInfo.depositToken = IERC20(_depositToken); poolInfo.depositFeeRate = _depositFeeRate; poolInfo.depositMin = _depositMin; poolInfo.depositTime = _depositTime; poolInfo.depositOpenTime = _depositOpenTime; poolInfo.depositCloseTime = poolInfo.depositOpenTime + _depositTime; poolInfo.profitShareRate = _profitShareRate; poolInfo.voteTokenOpen = true; poolInfo.voteTokenTime = _voteTokenTime; poolInfo.voteTokenOpenTime = poolInfo.depositCloseTime; poolInfo.voteTokenCloseTime = poolInfo.voteTokenOpenTime + _voteTokenTime; poolInfo.targetToken = IERC20(_targetToken); poolInfo.minLiquidity = _minLiquidity; whaleClubInfo.whaleClubTime = _whaleClubTime; whaleClubInfo.whaleClubNextUpdateTime = poolInfo.voteTokenCloseTime + _whaleClubTime; existingToken[_targetToken] = true; tokenIndex[_targetToken] = tokenVoteCount; tokenVoteCount += 1; tokenVote.push(TokenVote(_targetToken, 0)); } function deposit(uint256 _amount) external nonReentrant{ PoolTemp memory temp; require(now <= poolInfo.depositCloseTime, "Deposit Closed"); require(_amount >= poolInfo.depositMin, "the deposit is smaller than the minimum"); temp.tokenAmount = _getTokenAmount(address(poolInfo.depositToken), _amount); temp.amountEnteranceFee = 0; if(poolInfo.depositFeeRate > 0){ temp.amountFee = _amount * poolInfo.depositFeeRate / _divRate; address[] memory uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.depositToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(defhold); temp.getAmountsOut = uniswapRouter.getAmountsOut(temp.amountFee, uniswapPath); temp.amountEnteranceFee = temp.getAmountsOut[(temp.getAmountsOut.length - 1)]; } if(temp.amountEnteranceFee > 0){ defhold.safeTransferFrom(msg.sender, address(this), temp.amountEnteranceFee); defhold.safeApprove(address(defholdPools), 0); defhold.safeApprove(address(defholdPools), temp.amountEnteranceFee); defholdPools.externalReward(temp.amountEnteranceFee); emit EnteranceFee(msg.sender, address(defholdPools), temp.amountEnteranceFee); } if(temp.tokenAmount > 0){ poolInfo.depositToken.safeTransferFrom(msg.sender, address(this), temp.tokenAmount); _mint(msg.sender, _amount); } emit Deposit(msg.sender, address(poolInfo.depositToken), temp.tokenAmount); } function deposit(uint256 _amount) external nonReentrant{ PoolTemp memory temp; require(now <= poolInfo.depositCloseTime, "Deposit Closed"); require(_amount >= poolInfo.depositMin, "the deposit is smaller than the minimum"); temp.tokenAmount = _getTokenAmount(address(poolInfo.depositToken), _amount); temp.amountEnteranceFee = 0; if(poolInfo.depositFeeRate > 0){ temp.amountFee = _amount * poolInfo.depositFeeRate / _divRate; address[] memory uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.depositToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(defhold); temp.getAmountsOut = uniswapRouter.getAmountsOut(temp.amountFee, uniswapPath); temp.amountEnteranceFee = temp.getAmountsOut[(temp.getAmountsOut.length - 1)]; } if(temp.amountEnteranceFee > 0){ defhold.safeTransferFrom(msg.sender, address(this), temp.amountEnteranceFee); defhold.safeApprove(address(defholdPools), 0); defhold.safeApprove(address(defholdPools), temp.amountEnteranceFee); defholdPools.externalReward(temp.amountEnteranceFee); emit EnteranceFee(msg.sender, address(defholdPools), temp.amountEnteranceFee); } if(temp.tokenAmount > 0){ poolInfo.depositToken.safeTransferFrom(msg.sender, address(this), temp.tokenAmount); _mint(msg.sender, _amount); } emit Deposit(msg.sender, address(poolInfo.depositToken), temp.tokenAmount); } function deposit(uint256 _amount) external nonReentrant{ PoolTemp memory temp; require(now <= poolInfo.depositCloseTime, "Deposit Closed"); require(_amount >= poolInfo.depositMin, "the deposit is smaller than the minimum"); temp.tokenAmount = _getTokenAmount(address(poolInfo.depositToken), _amount); temp.amountEnteranceFee = 0; if(poolInfo.depositFeeRate > 0){ temp.amountFee = _amount * poolInfo.depositFeeRate / _divRate; address[] memory uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.depositToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(defhold); temp.getAmountsOut = uniswapRouter.getAmountsOut(temp.amountFee, uniswapPath); temp.amountEnteranceFee = temp.getAmountsOut[(temp.getAmountsOut.length - 1)]; } if(temp.amountEnteranceFee > 0){ defhold.safeTransferFrom(msg.sender, address(this), temp.amountEnteranceFee); defhold.safeApprove(address(defholdPools), 0); defhold.safeApprove(address(defholdPools), temp.amountEnteranceFee); defholdPools.externalReward(temp.amountEnteranceFee); emit EnteranceFee(msg.sender, address(defholdPools), temp.amountEnteranceFee); } if(temp.tokenAmount > 0){ poolInfo.depositToken.safeTransferFrom(msg.sender, address(this), temp.tokenAmount); _mint(msg.sender, _amount); } emit Deposit(msg.sender, address(poolInfo.depositToken), temp.tokenAmount); } function deposit(uint256 _amount) external nonReentrant{ PoolTemp memory temp; require(now <= poolInfo.depositCloseTime, "Deposit Closed"); require(_amount >= poolInfo.depositMin, "the deposit is smaller than the minimum"); temp.tokenAmount = _getTokenAmount(address(poolInfo.depositToken), _amount); temp.amountEnteranceFee = 0; if(poolInfo.depositFeeRate > 0){ temp.amountFee = _amount * poolInfo.depositFeeRate / _divRate; address[] memory uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.depositToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(defhold); temp.getAmountsOut = uniswapRouter.getAmountsOut(temp.amountFee, uniswapPath); temp.amountEnteranceFee = temp.getAmountsOut[(temp.getAmountsOut.length - 1)]; } if(temp.amountEnteranceFee > 0){ defhold.safeTransferFrom(msg.sender, address(this), temp.amountEnteranceFee); defhold.safeApprove(address(defholdPools), 0); defhold.safeApprove(address(defholdPools), temp.amountEnteranceFee); defholdPools.externalReward(temp.amountEnteranceFee); emit EnteranceFee(msg.sender, address(defholdPools), temp.amountEnteranceFee); } if(temp.tokenAmount > 0){ poolInfo.depositToken.safeTransferFrom(msg.sender, address(this), temp.tokenAmount); _mint(msg.sender, _amount); } emit Deposit(msg.sender, address(poolInfo.depositToken), temp.tokenAmount); } function voteTokenProject(address tokenAddress, address tokenLPAddress) external nonReentrant{ PoolTemp memory temp; require(now > poolInfo.depositCloseTime, "Vote Token not yet started"); require(now <= poolInfo.voteTokenCloseTime, "Vote Token Closed"); uniswapPair = IUniswapV2Pair(tokenLPAddress); temp.token0 = uniswapPair.token0(); temp.token1 = uniswapPair.token1(); (temp.reserve0, temp.reserve1, temp.blockTimestampLast) = uniswapPair.getReserves(); temp.liquidity = 0; if(temp.token0 == tokenAddress && temp.token1 == address(weth)){ temp.liquidity = temp.reserve1 * 2; if(temp.token1 == tokenAddress && temp.token0 == address(weth)){ temp.liquidity = temp.reserve0 * 2; } } temp.liquidity = temp.liquidity * _getETHPrice() / _decimalConverter; require(temp.liquidity >= poolInfo.minLiquidity, "Liquid is not meet the minimum"); temp.voteWeight = userTokenVote[msg.sender].voteWeight; temp.voteUsed = userTokenVote[msg.sender].voteUsed; temp.voteRemain = temp.voteWeight - temp.voteUsed; _voteTokenProject(tokenAddress); emit VoteTokenProject(msg.sender, tokenAddress, temp.voteRemain); temp.targetToken = address(poolInfo.targetToken); temp.bestVoteWeight = 0; for(temp.counter = 0; temp.counter < tokenVoteCount;temp.counter++){ temp.voteWeight = tokenVote[temp.counter].voteWeight; if(temp.voteWeight > temp.bestVoteWeight){ temp.targetToken = tokenVote[temp.counter].token; temp.bestVoteWeight = temp.voteWeight; poolInfo.targetToken = IERC20(temp.targetToken); } } } function voteTokenProject(address tokenAddress, address tokenLPAddress) external nonReentrant{ PoolTemp memory temp; require(now > poolInfo.depositCloseTime, "Vote Token not yet started"); require(now <= poolInfo.voteTokenCloseTime, "Vote Token Closed"); uniswapPair = IUniswapV2Pair(tokenLPAddress); temp.token0 = uniswapPair.token0(); temp.token1 = uniswapPair.token1(); (temp.reserve0, temp.reserve1, temp.blockTimestampLast) = uniswapPair.getReserves(); temp.liquidity = 0; if(temp.token0 == tokenAddress && temp.token1 == address(weth)){ temp.liquidity = temp.reserve1 * 2; if(temp.token1 == tokenAddress && temp.token0 == address(weth)){ temp.liquidity = temp.reserve0 * 2; } } temp.liquidity = temp.liquidity * _getETHPrice() / _decimalConverter; require(temp.liquidity >= poolInfo.minLiquidity, "Liquid is not meet the minimum"); temp.voteWeight = userTokenVote[msg.sender].voteWeight; temp.voteUsed = userTokenVote[msg.sender].voteUsed; temp.voteRemain = temp.voteWeight - temp.voteUsed; _voteTokenProject(tokenAddress); emit VoteTokenProject(msg.sender, tokenAddress, temp.voteRemain); temp.targetToken = address(poolInfo.targetToken); temp.bestVoteWeight = 0; for(temp.counter = 0; temp.counter < tokenVoteCount;temp.counter++){ temp.voteWeight = tokenVote[temp.counter].voteWeight; if(temp.voteWeight > temp.bestVoteWeight){ temp.targetToken = tokenVote[temp.counter].token; temp.bestVoteWeight = temp.voteWeight; poolInfo.targetToken = IERC20(temp.targetToken); } } } } else { function voteTokenProject(address tokenAddress, address tokenLPAddress) external nonReentrant{ PoolTemp memory temp; require(now > poolInfo.depositCloseTime, "Vote Token not yet started"); require(now <= poolInfo.voteTokenCloseTime, "Vote Token Closed"); uniswapPair = IUniswapV2Pair(tokenLPAddress); temp.token0 = uniswapPair.token0(); temp.token1 = uniswapPair.token1(); (temp.reserve0, temp.reserve1, temp.blockTimestampLast) = uniswapPair.getReserves(); temp.liquidity = 0; if(temp.token0 == tokenAddress && temp.token1 == address(weth)){ temp.liquidity = temp.reserve1 * 2; if(temp.token1 == tokenAddress && temp.token0 == address(weth)){ temp.liquidity = temp.reserve0 * 2; } } temp.liquidity = temp.liquidity * _getETHPrice() / _decimalConverter; require(temp.liquidity >= poolInfo.minLiquidity, "Liquid is not meet the minimum"); temp.voteWeight = userTokenVote[msg.sender].voteWeight; temp.voteUsed = userTokenVote[msg.sender].voteUsed; temp.voteRemain = temp.voteWeight - temp.voteUsed; _voteTokenProject(tokenAddress); emit VoteTokenProject(msg.sender, tokenAddress, temp.voteRemain); temp.targetToken = address(poolInfo.targetToken); temp.bestVoteWeight = 0; for(temp.counter = 0; temp.counter < tokenVoteCount;temp.counter++){ temp.voteWeight = tokenVote[temp.counter].voteWeight; if(temp.voteWeight > temp.bestVoteWeight){ temp.targetToken = tokenVote[temp.counter].token; temp.bestVoteWeight = temp.voteWeight; poolInfo.targetToken = IERC20(temp.targetToken); } } } function voteTokenProject(address tokenAddress, address tokenLPAddress) external nonReentrant{ PoolTemp memory temp; require(now > poolInfo.depositCloseTime, "Vote Token not yet started"); require(now <= poolInfo.voteTokenCloseTime, "Vote Token Closed"); uniswapPair = IUniswapV2Pair(tokenLPAddress); temp.token0 = uniswapPair.token0(); temp.token1 = uniswapPair.token1(); (temp.reserve0, temp.reserve1, temp.blockTimestampLast) = uniswapPair.getReserves(); temp.liquidity = 0; if(temp.token0 == tokenAddress && temp.token1 == address(weth)){ temp.liquidity = temp.reserve1 * 2; if(temp.token1 == tokenAddress && temp.token0 == address(weth)){ temp.liquidity = temp.reserve0 * 2; } } temp.liquidity = temp.liquidity * _getETHPrice() / _decimalConverter; require(temp.liquidity >= poolInfo.minLiquidity, "Liquid is not meet the minimum"); temp.voteWeight = userTokenVote[msg.sender].voteWeight; temp.voteUsed = userTokenVote[msg.sender].voteUsed; temp.voteRemain = temp.voteWeight - temp.voteUsed; _voteTokenProject(tokenAddress); emit VoteTokenProject(msg.sender, tokenAddress, temp.voteRemain); temp.targetToken = address(poolInfo.targetToken); temp.bestVoteWeight = 0; for(temp.counter = 0; temp.counter < tokenVoteCount;temp.counter++){ temp.voteWeight = tokenVote[temp.counter].voteWeight; if(temp.voteWeight > temp.bestVoteWeight){ temp.targetToken = tokenVote[temp.counter].token; temp.bestVoteWeight = temp.voteWeight; poolInfo.targetToken = IERC20(temp.targetToken); } } } function voteTokenProject(address tokenAddress, address tokenLPAddress) external nonReentrant{ PoolTemp memory temp; require(now > poolInfo.depositCloseTime, "Vote Token not yet started"); require(now <= poolInfo.voteTokenCloseTime, "Vote Token Closed"); uniswapPair = IUniswapV2Pair(tokenLPAddress); temp.token0 = uniswapPair.token0(); temp.token1 = uniswapPair.token1(); (temp.reserve0, temp.reserve1, temp.blockTimestampLast) = uniswapPair.getReserves(); temp.liquidity = 0; if(temp.token0 == tokenAddress && temp.token1 == address(weth)){ temp.liquidity = temp.reserve1 * 2; if(temp.token1 == tokenAddress && temp.token0 == address(weth)){ temp.liquidity = temp.reserve0 * 2; } } temp.liquidity = temp.liquidity * _getETHPrice() / _decimalConverter; require(temp.liquidity >= poolInfo.minLiquidity, "Liquid is not meet the minimum"); temp.voteWeight = userTokenVote[msg.sender].voteWeight; temp.voteUsed = userTokenVote[msg.sender].voteUsed; temp.voteRemain = temp.voteWeight - temp.voteUsed; _voteTokenProject(tokenAddress); emit VoteTokenProject(msg.sender, tokenAddress, temp.voteRemain); temp.targetToken = address(poolInfo.targetToken); temp.bestVoteWeight = 0; for(temp.counter = 0; temp.counter < tokenVoteCount;temp.counter++){ temp.voteWeight = tokenVote[temp.counter].voteWeight; if(temp.voteWeight > temp.bestVoteWeight){ temp.targetToken = tokenVote[temp.counter].token; temp.bestVoteWeight = temp.voteWeight; poolInfo.targetToken = IERC20(temp.targetToken); } } } function voteBuy() external nonReentrant{ PoolTemp memory temp; require(now >= poolInfo.voteTokenCloseTime, "Vote Buy/Sell not yet started"); require(buyStage < maxStage, "Vote Buy was ended"); temp.voteWeight = userStage[buyStage][msg.sender].voteWeight; temp.voteBuyUsed = userStage[buyStage][msg.sender].voteBuyUsed; temp.voteRemain = temp.voteWeight - temp.voteBuyUsed; _voteBuy(); emit VoteBuy(msg.sender, temp.voteRemain); temp.poolAmount = poolStage[buyStage].amount; temp.poolBuyVoteWeight = poolStage[buyStage].buyVoteWeight; temp.poolRate = percent(temp.poolBuyVoteWeight, temp.poolAmount, 4); if(temp.poolRate >= 5000) { temp.deadline = block.timestamp + 5 minutes; temp.balanceBeforeSwap = poolInfo.targetToken.balanceOf(address(this)); temp.tokensToSwap = _getTokenAmount(address(poolInfo.depositToken), temp.poolAmount); require(temp.tokensToSwap > 0, "bad token swap"); address[] memory uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.depositToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(poolInfo.targetToken); poolInfo.depositToken.safeApprove(address(uniswapRouter), 0); poolInfo.depositToken.safeApprove(address(uniswapRouter), temp.tokensToSwap); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(temp.tokensToSwap, 0, uniswapPath, address(this), temp.deadline); temp.balanceAfterSwap = poolInfo.targetToken.balanceOf(address(this)); temp.buyAmount = temp.balanceAfterSwap - temp.balanceBeforeSwap; temp.buyAmount = _getReverseTokenAmount(address(poolInfo.targetToken), temp.buyAmount); poolStage[buyStage].buyAmount = temp.buyAmount; whaleClubInfo.whaleClubNextUpdateTime = now + whaleClubInfo.whaleClubTime; nextBuyStage(); } } function voteBuy() external nonReentrant{ PoolTemp memory temp; require(now >= poolInfo.voteTokenCloseTime, "Vote Buy/Sell not yet started"); require(buyStage < maxStage, "Vote Buy was ended"); temp.voteWeight = userStage[buyStage][msg.sender].voteWeight; temp.voteBuyUsed = userStage[buyStage][msg.sender].voteBuyUsed; temp.voteRemain = temp.voteWeight - temp.voteBuyUsed; _voteBuy(); emit VoteBuy(msg.sender, temp.voteRemain); temp.poolAmount = poolStage[buyStage].amount; temp.poolBuyVoteWeight = poolStage[buyStage].buyVoteWeight; temp.poolRate = percent(temp.poolBuyVoteWeight, temp.poolAmount, 4); if(temp.poolRate >= 5000) { temp.deadline = block.timestamp + 5 minutes; temp.balanceBeforeSwap = poolInfo.targetToken.balanceOf(address(this)); temp.tokensToSwap = _getTokenAmount(address(poolInfo.depositToken), temp.poolAmount); require(temp.tokensToSwap > 0, "bad token swap"); address[] memory uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.depositToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(poolInfo.targetToken); poolInfo.depositToken.safeApprove(address(uniswapRouter), 0); poolInfo.depositToken.safeApprove(address(uniswapRouter), temp.tokensToSwap); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(temp.tokensToSwap, 0, uniswapPath, address(this), temp.deadline); temp.balanceAfterSwap = poolInfo.targetToken.balanceOf(address(this)); temp.buyAmount = temp.balanceAfterSwap - temp.balanceBeforeSwap; temp.buyAmount = _getReverseTokenAmount(address(poolInfo.targetToken), temp.buyAmount); poolStage[buyStage].buyAmount = temp.buyAmount; whaleClubInfo.whaleClubNextUpdateTime = now + whaleClubInfo.whaleClubTime; nextBuyStage(); } } function voteSell() external nonReentrant{ PoolTemp memory temp; require(now >= poolInfo.voteTokenCloseTime, "Vote Buy/Sell not yet started"); require(sellStage < buyStage, "Vote Sell not found"); require(sellStage < maxStage, "Vote Sell was ended"); temp.voteWeight = userStage[buyStage][msg.sender].voteWeight; temp.voteSellUsed = userStage[buyStage][msg.sender].voteSellUsed; temp.voteRemain = temp.voteWeight - temp.voteSellUsed; _voteSell(); emit VoteSell(msg.sender, temp.voteRemain); temp.poolAmount = poolStage[sellStage].amount; temp.buyAmount = poolStage[sellStage].buyAmount; temp.poolSellVoteWeight = poolStage[sellStage].sellVoteWeight; temp.poolRate = percent(temp.poolSellVoteWeight, temp.poolAmount, 4); if(temp.poolRate >= 5000) { temp.deadline = block.timestamp + 5 minutes; temp.balanceBeforeSwap = poolInfo.depositToken.balanceOf(address(this)); temp.tokensToSwap = _getTokenAmount(address(poolInfo.targetToken), temp.buyAmount); require(temp.tokensToSwap > 0, "bad token swap"); address[] memory uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.targetToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(poolInfo.depositToken); poolInfo.targetToken.safeApprove(address(uniswapRouter), 0); poolInfo.targetToken.safeApprove(address(uniswapRouter), temp.tokensToSwap); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(temp.tokensToSwap, 0, uniswapPath, address(this), temp.deadline); temp.balanceAfterSwap = poolInfo.depositToken.balanceOf(address(this)); temp.sellAmount = temp.balanceAfterSwap - temp.balanceBeforeSwap; temp.sellAmount = _getReverseTokenAmount(address(poolInfo.depositToken), temp.sellAmount); if(temp.sellAmount > temp.poolAmount){ temp.profitAmount = temp.sellAmount - temp.poolAmount; temp.profitShareAmount = temp.profitAmount * poolInfo.profitShareRate / _divRate; temp.tokensToSwap = _getTokenAmount(address(poolInfo.depositToken), temp.profitShareAmount); uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.depositToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(defhold); poolInfo.depositToken.safeApprove(address(uniswapRouter), 0); poolInfo.depositToken.safeApprove(address(uniswapRouter), temp.tokensToSwap); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(temp.tokensToSwap, 0, uniswapPath, address(this), temp.deadline); temp.defholdAmount = defhold.balanceOf(address(this)); temp.defholdAmount = _getReverseTokenAmount(address(defhold), temp.defholdAmount); defhold.safeApprove(address(defholdPools), 0); defhold.safeApprove(address(defholdPools), temp.defholdAmount); defholdPools.externalReward(temp.defholdAmount); emit PoolProfitShare(address(defholdPools), temp.defholdAmount); temp.sellAmount -= temp.profitShareAmount; } poolStage[sellStage].sellAmount = temp.sellAmount; whaleClubInfo.whaleClubNextUpdateTime = now + whaleClubInfo.whaleClubTime; nextSellStage(); } } function voteSell() external nonReentrant{ PoolTemp memory temp; require(now >= poolInfo.voteTokenCloseTime, "Vote Buy/Sell not yet started"); require(sellStage < buyStage, "Vote Sell not found"); require(sellStage < maxStage, "Vote Sell was ended"); temp.voteWeight = userStage[buyStage][msg.sender].voteWeight; temp.voteSellUsed = userStage[buyStage][msg.sender].voteSellUsed; temp.voteRemain = temp.voteWeight - temp.voteSellUsed; _voteSell(); emit VoteSell(msg.sender, temp.voteRemain); temp.poolAmount = poolStage[sellStage].amount; temp.buyAmount = poolStage[sellStage].buyAmount; temp.poolSellVoteWeight = poolStage[sellStage].sellVoteWeight; temp.poolRate = percent(temp.poolSellVoteWeight, temp.poolAmount, 4); if(temp.poolRate >= 5000) { temp.deadline = block.timestamp + 5 minutes; temp.balanceBeforeSwap = poolInfo.depositToken.balanceOf(address(this)); temp.tokensToSwap = _getTokenAmount(address(poolInfo.targetToken), temp.buyAmount); require(temp.tokensToSwap > 0, "bad token swap"); address[] memory uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.targetToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(poolInfo.depositToken); poolInfo.targetToken.safeApprove(address(uniswapRouter), 0); poolInfo.targetToken.safeApprove(address(uniswapRouter), temp.tokensToSwap); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(temp.tokensToSwap, 0, uniswapPath, address(this), temp.deadline); temp.balanceAfterSwap = poolInfo.depositToken.balanceOf(address(this)); temp.sellAmount = temp.balanceAfterSwap - temp.balanceBeforeSwap; temp.sellAmount = _getReverseTokenAmount(address(poolInfo.depositToken), temp.sellAmount); if(temp.sellAmount > temp.poolAmount){ temp.profitAmount = temp.sellAmount - temp.poolAmount; temp.profitShareAmount = temp.profitAmount * poolInfo.profitShareRate / _divRate; temp.tokensToSwap = _getTokenAmount(address(poolInfo.depositToken), temp.profitShareAmount); uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.depositToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(defhold); poolInfo.depositToken.safeApprove(address(uniswapRouter), 0); poolInfo.depositToken.safeApprove(address(uniswapRouter), temp.tokensToSwap); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(temp.tokensToSwap, 0, uniswapPath, address(this), temp.deadline); temp.defholdAmount = defhold.balanceOf(address(this)); temp.defholdAmount = _getReverseTokenAmount(address(defhold), temp.defholdAmount); defhold.safeApprove(address(defholdPools), 0); defhold.safeApprove(address(defholdPools), temp.defholdAmount); defholdPools.externalReward(temp.defholdAmount); emit PoolProfitShare(address(defholdPools), temp.defholdAmount); temp.sellAmount -= temp.profitShareAmount; } poolStage[sellStage].sellAmount = temp.sellAmount; whaleClubInfo.whaleClubNextUpdateTime = now + whaleClubInfo.whaleClubTime; nextSellStage(); } } function voteSell() external nonReentrant{ PoolTemp memory temp; require(now >= poolInfo.voteTokenCloseTime, "Vote Buy/Sell not yet started"); require(sellStage < buyStage, "Vote Sell not found"); require(sellStage < maxStage, "Vote Sell was ended"); temp.voteWeight = userStage[buyStage][msg.sender].voteWeight; temp.voteSellUsed = userStage[buyStage][msg.sender].voteSellUsed; temp.voteRemain = temp.voteWeight - temp.voteSellUsed; _voteSell(); emit VoteSell(msg.sender, temp.voteRemain); temp.poolAmount = poolStage[sellStage].amount; temp.buyAmount = poolStage[sellStage].buyAmount; temp.poolSellVoteWeight = poolStage[sellStage].sellVoteWeight; temp.poolRate = percent(temp.poolSellVoteWeight, temp.poolAmount, 4); if(temp.poolRate >= 5000) { temp.deadline = block.timestamp + 5 minutes; temp.balanceBeforeSwap = poolInfo.depositToken.balanceOf(address(this)); temp.tokensToSwap = _getTokenAmount(address(poolInfo.targetToken), temp.buyAmount); require(temp.tokensToSwap > 0, "bad token swap"); address[] memory uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.targetToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(poolInfo.depositToken); poolInfo.targetToken.safeApprove(address(uniswapRouter), 0); poolInfo.targetToken.safeApprove(address(uniswapRouter), temp.tokensToSwap); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(temp.tokensToSwap, 0, uniswapPath, address(this), temp.deadline); temp.balanceAfterSwap = poolInfo.depositToken.balanceOf(address(this)); temp.sellAmount = temp.balanceAfterSwap - temp.balanceBeforeSwap; temp.sellAmount = _getReverseTokenAmount(address(poolInfo.depositToken), temp.sellAmount); if(temp.sellAmount > temp.poolAmount){ temp.profitAmount = temp.sellAmount - temp.poolAmount; temp.profitShareAmount = temp.profitAmount * poolInfo.profitShareRate / _divRate; temp.tokensToSwap = _getTokenAmount(address(poolInfo.depositToken), temp.profitShareAmount); uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.depositToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(defhold); poolInfo.depositToken.safeApprove(address(uniswapRouter), 0); poolInfo.depositToken.safeApprove(address(uniswapRouter), temp.tokensToSwap); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(temp.tokensToSwap, 0, uniswapPath, address(this), temp.deadline); temp.defholdAmount = defhold.balanceOf(address(this)); temp.defholdAmount = _getReverseTokenAmount(address(defhold), temp.defholdAmount); defhold.safeApprove(address(defholdPools), 0); defhold.safeApprove(address(defholdPools), temp.defholdAmount); defholdPools.externalReward(temp.defholdAmount); emit PoolProfitShare(address(defholdPools), temp.defholdAmount); temp.sellAmount -= temp.profitShareAmount; } poolStage[sellStage].sellAmount = temp.sellAmount; whaleClubInfo.whaleClubNextUpdateTime = now + whaleClubInfo.whaleClubTime; nextSellStage(); } } function updateWhaleClubStat() external nonReentrant{ PoolTemp memory temp; require(now >= poolInfo.voteTokenCloseTime, "Whale Club not yet started"); temp.poolRate = percent(temp.poolBuyVoteWeight, temp.poolAmount, 4); if(now > whaleClubInfo.whaleClubNextUpdateTime){ if(temp.poolRate < 5000) { if(buyStage == 0){ sellStage = maxStage; } for(temp.counter = buyStage; temp.counter < maxStage;temp.counter++){ temp.poolAmount = poolStage[buyStage].amount; poolStage[buyStage].sellAmount = temp.poolAmount; nextBuyStage(); } } } } function updateWhaleClubStat() external nonReentrant{ PoolTemp memory temp; require(now >= poolInfo.voteTokenCloseTime, "Whale Club not yet started"); temp.poolRate = percent(temp.poolBuyVoteWeight, temp.poolAmount, 4); if(now > whaleClubInfo.whaleClubNextUpdateTime){ if(temp.poolRate < 5000) { if(buyStage == 0){ sellStage = maxStage; } for(temp.counter = buyStage; temp.counter < maxStage;temp.counter++){ temp.poolAmount = poolStage[buyStage].amount; poolStage[buyStage].sellAmount = temp.poolAmount; nextBuyStage(); } } } } function updateWhaleClubStat() external nonReentrant{ PoolTemp memory temp; require(now >= poolInfo.voteTokenCloseTime, "Whale Club not yet started"); temp.poolRate = percent(temp.poolBuyVoteWeight, temp.poolAmount, 4); if(now > whaleClubInfo.whaleClubNextUpdateTime){ if(temp.poolRate < 5000) { if(buyStage == 0){ sellStage = maxStage; } for(temp.counter = buyStage; temp.counter < maxStage;temp.counter++){ temp.poolAmount = poolStage[buyStage].amount; poolStage[buyStage].sellAmount = temp.poolAmount; nextBuyStage(); } } } } function updateWhaleClubStat() external nonReentrant{ PoolTemp memory temp; require(now >= poolInfo.voteTokenCloseTime, "Whale Club not yet started"); temp.poolRate = percent(temp.poolBuyVoteWeight, temp.poolAmount, 4); if(now > whaleClubInfo.whaleClubNextUpdateTime){ if(temp.poolRate < 5000) { if(buyStage == 0){ sellStage = maxStage; } for(temp.counter = buyStage; temp.counter < maxStage;temp.counter++){ temp.poolAmount = poolStage[buyStage].amount; poolStage[buyStage].sellAmount = temp.poolAmount; nextBuyStage(); } } } } function updateWhaleClubStat() external nonReentrant{ PoolTemp memory temp; require(now >= poolInfo.voteTokenCloseTime, "Whale Club not yet started"); temp.poolRate = percent(temp.poolBuyVoteWeight, temp.poolAmount, 4); if(now > whaleClubInfo.whaleClubNextUpdateTime){ if(temp.poolRate < 5000) { if(buyStage == 0){ sellStage = maxStage; } for(temp.counter = buyStage; temp.counter < maxStage;temp.counter++){ temp.poolAmount = poolStage[buyStage].amount; poolStage[buyStage].sellAmount = temp.poolAmount; nextBuyStage(); } } } } function pendingClaim(uint _poolStage, address _user) public view returns (uint256){ PoolTemp memory temp; temp.pendingClaim = 0; temp.sellAmount = poolStage[_poolStage].sellAmount; if(temp.sellAmount > 0){ temp.claimable = userStage[_poolStage][_user].claimable; if(temp.claimable > 0){ temp.poolAmount = poolStage[_poolStage].amount; temp.claimShare = percent(temp.claimable, temp.poolAmount, 4); temp.pendingClaim += temp.sellAmount * temp.claimShare / _divRate; } } return temp.pendingClaim; } function pendingClaim(uint _poolStage, address _user) public view returns (uint256){ PoolTemp memory temp; temp.pendingClaim = 0; temp.sellAmount = poolStage[_poolStage].sellAmount; if(temp.sellAmount > 0){ temp.claimable = userStage[_poolStage][_user].claimable; if(temp.claimable > 0){ temp.poolAmount = poolStage[_poolStage].amount; temp.claimShare = percent(temp.claimable, temp.poolAmount, 4); temp.pendingClaim += temp.sellAmount * temp.claimShare / _divRate; } } return temp.pendingClaim; } function pendingClaim(uint _poolStage, address _user) public view returns (uint256){ PoolTemp memory temp; temp.pendingClaim = 0; temp.sellAmount = poolStage[_poolStage].sellAmount; if(temp.sellAmount > 0){ temp.claimable = userStage[_poolStage][_user].claimable; if(temp.claimable > 0){ temp.poolAmount = poolStage[_poolStage].amount; temp.claimShare = percent(temp.claimable, temp.poolAmount, 4); temp.pendingClaim += temp.sellAmount * temp.claimShare / _divRate; } } return temp.pendingClaim; } function claim(uint _poolStage) external nonReentrant{ PoolTemp memory temp; temp.claimable = userStage[_poolStage][msg.sender].claimable; temp.pendingClaim = pendingClaim(_poolStage, msg.sender); require(temp.pendingClaim > 0, "no Claim balance"); poolInfo.depositToken.safeTransfer(msg.sender, temp.pendingClaim); userStage[_poolStage][msg.sender].claimable -= temp.claimable; poolStage[_poolStage].claimAmount += temp.claimable; emit Claim(msg.sender, address(poolInfo.depositToken), temp.claimable, temp.pendingClaim); } function _getTokenAmount(address _tokenAddress, uint256 _amount) internal view returns (uint256 quotient) { PoolTemp memory temp; temp.tokenAddress = IERC20(_tokenAddress); temp.tokenDecimal = temp.tokenAddress.decimals(); if(_decimal != temp.tokenDecimal){ if(_decimal > temp.tokenDecimal){ temp.decimalDiff = _decimal - temp.tokenDecimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.div(temp.decimalDiffConverter); temp.decimalDiff = temp.tokenDecimal - _decimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.mul(temp.decimalDiffConverter); } temp.amount = _amount; } uint256 _quotient = temp.amount; return (_quotient); } function _getTokenAmount(address _tokenAddress, uint256 _amount) internal view returns (uint256 quotient) { PoolTemp memory temp; temp.tokenAddress = IERC20(_tokenAddress); temp.tokenDecimal = temp.tokenAddress.decimals(); if(_decimal != temp.tokenDecimal){ if(_decimal > temp.tokenDecimal){ temp.decimalDiff = _decimal - temp.tokenDecimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.div(temp.decimalDiffConverter); temp.decimalDiff = temp.tokenDecimal - _decimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.mul(temp.decimalDiffConverter); } temp.amount = _amount; } uint256 _quotient = temp.amount; return (_quotient); } function _getTokenAmount(address _tokenAddress, uint256 _amount) internal view returns (uint256 quotient) { PoolTemp memory temp; temp.tokenAddress = IERC20(_tokenAddress); temp.tokenDecimal = temp.tokenAddress.decimals(); if(_decimal != temp.tokenDecimal){ if(_decimal > temp.tokenDecimal){ temp.decimalDiff = _decimal - temp.tokenDecimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.div(temp.decimalDiffConverter); temp.decimalDiff = temp.tokenDecimal - _decimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.mul(temp.decimalDiffConverter); } temp.amount = _amount; } uint256 _quotient = temp.amount; return (_quotient); } } else { } else { function _getReverseTokenAmount(address _tokenAddress, uint256 _amount) internal view returns (uint256 quotient) { PoolTemp memory temp; temp.tokenAddress = IERC20(_tokenAddress); temp.tokenDecimal = temp.tokenAddress.decimals(); if(_decimal != temp.tokenDecimal){ if(_decimal > temp.tokenDecimal){ temp.decimalDiff = _decimal - temp.tokenDecimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.mul(temp.decimalDiffConverter); temp.decimalDiff = temp.tokenDecimal - _decimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.div(temp.decimalDiffConverter); } temp.amount = _amount; } uint256 _quotient = temp.amount; return (_quotient); } function _getReverseTokenAmount(address _tokenAddress, uint256 _amount) internal view returns (uint256 quotient) { PoolTemp memory temp; temp.tokenAddress = IERC20(_tokenAddress); temp.tokenDecimal = temp.tokenAddress.decimals(); if(_decimal != temp.tokenDecimal){ if(_decimal > temp.tokenDecimal){ temp.decimalDiff = _decimal - temp.tokenDecimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.mul(temp.decimalDiffConverter); temp.decimalDiff = temp.tokenDecimal - _decimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.div(temp.decimalDiffConverter); } temp.amount = _amount; } uint256 _quotient = temp.amount; return (_quotient); } function _getReverseTokenAmount(address _tokenAddress, uint256 _amount) internal view returns (uint256 quotient) { PoolTemp memory temp; temp.tokenAddress = IERC20(_tokenAddress); temp.tokenDecimal = temp.tokenAddress.decimals(); if(_decimal != temp.tokenDecimal){ if(_decimal > temp.tokenDecimal){ temp.decimalDiff = _decimal - temp.tokenDecimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.mul(temp.decimalDiffConverter); temp.decimalDiff = temp.tokenDecimal - _decimal; temp.decimalDiffConverter = 10**temp.decimalDiff; temp.amount = _amount.div(temp.decimalDiffConverter); } temp.amount = _amount; } uint256 _quotient = temp.amount; return (_quotient); } } else { } else { function _getETHPrice() internal view returns (uint256){ PoolTemp memory temp; address[] memory uniswapPath = new address[](3); uniswapPath[0] = address(weth); uniswapPath[1] = address(usdt); temp.getAmountsOut = uniswapRouter.getAmountsOut(temp.amountFee, uniswapPath); uint256 ethPrice = temp.getAmountsOut[(temp.getAmountsOut.length - 1)]; ethPrice = _getReverseTokenAmount(address(weth), ethPrice) / 10**18; return ethPrice; } event Deposit(address indexed user, address token, uint256 amount); event EnteranceFee(address indexed user, address token, uint256 amount); event VoteTokenProject(address indexed user,address token, uint256 voteWeight); event VoteBuy(address indexed user, uint256 voteWeight); event VoteSell(address indexed user, uint256 voteWeight); event PoolProfitShare(address indexed poolAddress, uint256 amount); event Claim(address indexed user, address token, uint256 amountClaim, uint256 amountReceived); }
9,004,424
[ 1, 4625, 348, 7953, 560, 30, 225, 1021, 1351, 291, 91, 438, 331, 22, 9703, 1021, 1351, 291, 91, 438, 331, 22, 9703, 1021, 678, 1584, 44, 3155, 1021, 11836, 9081, 3155, 1021, 10922, 21056, 16639, 3807, 434, 2845, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2030, 3313, 2888, 5349, 2009, 373, 353, 2030, 3313, 654, 39, 3462, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 202, 9940, 14060, 10477, 364, 2254, 5034, 31, 203, 202, 9940, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 202, 203, 202, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 2713, 640, 291, 91, 438, 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, 565, 467, 984, 291, 91, 438, 58, 22, 4154, 2713, 640, 291, 91, 438, 4154, 31, 203, 565, 467, 654, 39, 3462, 2713, 341, 546, 31, 203, 565, 467, 654, 39, 3462, 2713, 584, 7510, 31, 203, 565, 10922, 21056, 16639, 2713, 1652, 21056, 16639, 273, 10922, 21056, 16639, 12, 20, 92, 4033, 39, 5292, 71, 12483, 3103, 5908, 5540, 74, 3247, 22, 38, 23, 72, 1105, 39, 73, 5324, 25, 1105, 40, 11035, 12124, 2539, 5324, 1769, 203, 203, 202, 1697, 8828, 966, 95, 203, 202, 202, 6430, 443, 1724, 3678, 31, 203, 202, 202, 11890, 5034, 443, 1724, 14667, 4727, 31, 203, 202, 202, 45, 654, 39, 3462, 443, 1724, 1345, 31, 203, 202, 202, 11890, 5034, 443, 1724, 2930, 31, 203, 202, 202, 11890, 5034, 443, 1724, 950, 31, 203, 202, 202, 11890, 5034, 443, 1724, 3678, 950, 31, 203, 202, 202, 11890, 5034, 443, 1724, 4605, 950, 31, 203, 202, 202, 6430, 12501, 1345, 3678, 31, 203, 202, 202, 11890, 5034, 12501, 1345, 950, 31, 203, 202, 202, 11890, 5034, 12501, 1345, 3678, 950, 31, 203, 202, 202, 11890, 5034, 12501, 1345, 4605, 950, 31, 203, 202, 202, 11890, 5034, 1131, 48, 18988, 24237, 31, 203, 202, 202, 45, 654, 39, 3462, 1018, 1345, 31, 203, 202, 202, 11890, 5034, 450, 7216, 9535, 4727, 31, 203, 202, 97, 203, 202, 203, 202, 1697, 3497, 5349, 2009, 373, 966, 95, 203, 202, 202, 11890, 5034, 600, 5349, 2009, 373, 950, 31, 203, 202, 202, 11890, 5034, 600, 5349, 2009, 373, 2134, 1891, 950, 31, 203, 202, 97, 203, 1082, 203, 202, 1697, 8828, 7185, 288, 203, 202, 202, 45, 654, 39, 3462, 1147, 1887, 31, 203, 202, 202, 11890, 5034, 1147, 5749, 31, 203, 202, 202, 11890, 5034, 6970, 5938, 31, 203, 202, 202, 11890, 5034, 6970, 5938, 5072, 31, 203, 202, 202, 11890, 5034, 1147, 6275, 31, 203, 202, 202, 11890, 5034, 3844, 31, 203, 202, 202, 11890, 5034, 3844, 14667, 31, 203, 202, 202, 11890, 5034, 8526, 24418, 87, 1182, 31, 203, 202, 202, 11890, 5034, 3844, 10237, 1359, 14667, 31, 203, 202, 202, 11890, 5034, 3895, 31, 203, 202, 202, 11890, 5034, 12501, 6544, 31, 203, 202, 202, 11890, 5034, 12501, 6668, 31, 203, 202, 202, 11890, 5034, 12501, 38, 9835, 6668, 31, 203, 202, 202, 11890, 5034, 12501, 55, 1165, 6668, 31, 203, 202, 202, 11890, 5034, 12501, 1933, 530, 31, 203, 202, 202, 11890, 5034, 3796, 19338, 6544, 31, 203, 202, 202, 2867, 1018, 1345, 31, 203, 202, 202, 11890, 5034, 2845, 6275, 31, 203, 202, 202, 11890, 5034, 30143, 6275, 31, 203, 202, 202, 11890, 5034, 357, 80, 6275, 31, 203, 202, 202, 11890, 5034, 2845, 38, 9835, 19338, 6544, 31, 203, 202, 202, 11890, 5034, 2845, 55, 1165, 19338, 6544, 31, 203, 202, 202, 11890, 5034, 2845, 4727, 31, 203, 202, 202, 11890, 5034, 14096, 31, 203, 202, 202, 11890, 5034, 11013, 4649, 12521, 31, 203, 202, 202, 11890, 5034, 2430, 774, 12521, 31, 203, 202, 202, 11890, 5034, 11013, 4436, 12521, 31, 203, 202, 202, 11890, 5034, 450, 7216, 9535, 6275, 31, 203, 202, 202, 11890, 5034, 1652, 21056, 6275, 31, 203, 202, 202, 11890, 5034, 450, 7216, 6275, 31, 203, 202, 202, 11890, 5034, 4634, 9762, 31, 203, 202, 202, 11890, 5034, 7516, 429, 31, 203, 202, 202, 11890, 5034, 7516, 9535, 31, 203, 202, 202, 2867, 1147, 20, 31, 203, 202, 202, 2867, 1147, 21, 31, 203, 202, 202, 11890, 17666, 20501, 20, 31, 203, 202, 202, 11890, 17666, 20501, 21, 31, 203, 202, 202, 11890, 1578, 1203, 4921, 3024, 31, 203, 202, 202, 11890, 5034, 4501, 372, 24237, 31, 203, 202, 97, 203, 202, 203, 202, 2864, 966, 1071, 2845, 966, 31, 203, 202, 2888, 5349, 2009, 373, 966, 1071, 600, 5349, 2009, 373, 966, 31, 203, 203, 202, 12316, 261, 203, 202, 202, 1080, 3778, 508, 203, 202, 202, 16, 533, 3778, 3273, 203, 202, 202, 16, 1758, 389, 536, 21056, 203, 202, 202, 16, 1758, 389, 91, 546, 203, 202, 202, 16, 1758, 389, 407, 7510, 203, 202, 202, 16, 1758, 389, 323, 1724, 1345, 203, 202, 202, 16, 2254, 5034, 389, 323, 1724, 14667, 4727, 203, 202, 202, 16, 2254, 5034, 389, 685, 7216, 9535, 4727, 203, 202, 202, 16, 2254, 5034, 389, 323, 1724, 2930, 203, 202, 202, 16, 2254, 5034, 389, 323, 1724, 3678, 950, 203, 202, 202, 16, 2254, 5034, 389, 323, 1724, 950, 203, 202, 202, 16, 2254, 5034, 389, 25911, 1345, 950, 203, 202, 202, 16, 2254, 5034, 389, 3350, 5349, 2009, 373, 950, 203, 202, 202, 16, 1758, 389, 3299, 1345, 203, 202, 202, 16, 2254, 5034, 389, 1154, 48, 18988, 24237, 203, 202, 13, 1071, 2030, 3313, 654, 39, 3462, 12, 529, 16, 3273, 13, 14223, 6914, 1435, 95, 203, 202, 202, 536, 21056, 273, 467, 654, 39, 3462, 24899, 536, 21056, 1769, 203, 202, 202, 91, 546, 273, 467, 654, 39, 3462, 24899, 91, 546, 1769, 203, 202, 202, 407, 7510, 273, 467, 654, 39, 3462, 24899, 407, 7510, 1769, 203, 1082, 203, 202, 202, 6011, 966, 18, 323, 1724, 3678, 273, 638, 31, 203, 202, 202, 6011, 966, 18, 323, 1724, 1345, 273, 467, 654, 39, 3462, 24899, 323, 1724, 1345, 1769, 203, 202, 202, 6011, 966, 18, 323, 1724, 14667, 4727, 273, 389, 323, 1724, 14667, 4727, 31, 203, 202, 202, 6011, 966, 18, 323, 1724, 2930, 273, 389, 323, 1724, 2930, 31, 203, 202, 202, 6011, 966, 18, 323, 1724, 950, 273, 389, 323, 2 ]
./full_match/80001/0x232e027441C46A79eFE1BcFA72dd2dc19dB210a9/sources/project:/contracts/Proxy/V1/NftMarketplaceERC1155ProxyV3.sol
Check for duplicates and calculate total percentage
function setupPayoutGroup(address nftAddress, PayoutScenario scenario, PayoutMember[] memory members) internal { uint256 totalPercentage = 0; function setOrgFeesPercentage( address nftAddress, uint16 primaryPercentage, uint16 secondaryPercentage } function setPrimaryFeePercentage( address nftAddress, uint16 percentage } } function startCodeSale( address nftAddress, address code_signerAddress } function verifyData( address nftAddress, bytes memory signature, uint256 tokenId, string memory code } function codeListingMint( address nftAddress, bytes memory signature, uint256 tokenId, string memory code, address recipient } for (uint i = 0; i < members.length; i++) { for (uint j = i + 1; j < members.length; j++) { require(members[i].memberAddress != members[j].memberAddress, "Duplicate member addresses found"); } totalPercentage += members[i].percentage; } require(totalPercentage == 10000, "Total percentage is not 10000"); function setOrgFeesPercentage( address nftAddress, uint16 primaryPercentage, uint16 secondaryPercentage } function setPrimaryFeePercentage( address nftAddress, uint16 percentage } } function startCodeSale( address nftAddress, address code_signerAddress } function verifyData( address nftAddress, bytes memory signature, uint256 tokenId, string memory code } function codeListingMint( address nftAddress, bytes memory signature, uint256 tokenId, string memory code, address recipient } for (uint i = 0; i < members.length; i++) { for (uint j = i + 1; j < members.length; j++) { require(members[i].memberAddress != members[j].memberAddress, "Duplicate member addresses found"); } totalPercentage += members[i].percentage; } require(totalPercentage == 10000, "Total percentage is not 10000"); if (scenario == PayoutScenario.Primary) { for (uint256 i = 0; i < members.length; i++) { primaryPayoutGroups[nftAddress].push(members[i]); } for (uint256 i = 0; i < members.length; i++) { secondaryPayoutGroups[nftAddress].push(members[i]); } } emit PayoutGroupSet(nftAddress, scenario, members); if (scenario == PayoutScenario.Primary) { for (uint256 i = 0; i < members.length; i++) { primaryPayoutGroups[nftAddress].push(members[i]); } for (uint256 i = 0; i < members.length; i++) { secondaryPayoutGroups[nftAddress].push(members[i]); } } emit PayoutGroupSet(nftAddress, scenario, members); } else if (scenario == PayoutScenario.Secondary) { if (scenario == PayoutScenario.Primary) { for (uint256 i = 0; i < members.length; i++) { primaryPayoutGroups[nftAddress].push(members[i]); } for (uint256 i = 0; i < members.length; i++) { secondaryPayoutGroups[nftAddress].push(members[i]); } } emit PayoutGroupSet(nftAddress, scenario, members); }
9,510,683
[ 1, 4625, 348, 7953, 560, 30, 225, 2073, 364, 11211, 471, 4604, 2078, 11622, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3875, 52, 2012, 1114, 12, 2867, 290, 1222, 1887, 16, 453, 2012, 21390, 10766, 16, 453, 2012, 4419, 8526, 3778, 4833, 13, 2713, 288, 203, 3639, 2254, 5034, 2078, 16397, 273, 374, 31, 203, 203, 203, 565, 445, 444, 6001, 2954, 281, 16397, 12, 203, 3639, 1758, 290, 1222, 1887, 16, 203, 3639, 2254, 2313, 3354, 16397, 16, 203, 3639, 2254, 2313, 9946, 16397, 203, 565, 289, 203, 203, 203, 565, 445, 444, 6793, 14667, 16397, 12, 203, 3639, 1758, 290, 1222, 1887, 16, 203, 3639, 2254, 2313, 11622, 203, 565, 289, 203, 203, 565, 289, 203, 203, 203, 565, 445, 787, 1085, 30746, 12, 203, 3639, 1758, 290, 1222, 1887, 16, 203, 3639, 1758, 981, 67, 2977, 264, 1887, 203, 565, 289, 203, 203, 565, 445, 3929, 751, 12, 203, 3639, 1758, 290, 1222, 1887, 16, 203, 3639, 1731, 3778, 3372, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 533, 3778, 981, 203, 565, 289, 203, 203, 565, 445, 981, 19081, 49, 474, 12, 203, 3639, 1758, 290, 1222, 1887, 16, 203, 3639, 1731, 3778, 3372, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 533, 3778, 981, 16, 203, 3639, 1758, 8027, 203, 565, 289, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 4833, 18, 2469, 31, 277, 27245, 288, 203, 5411, 364, 261, 11890, 525, 273, 277, 397, 404, 31, 525, 411, 4833, 18, 2469, 31, 525, 27245, 288, 203, 7734, 2583, 12, 7640, 63, 77, 8009, 5990, 1887, 480, 4833, 63, 78, 8009, 5990, 1887, 16, 315, 11826, 3140, 6138, 1392, 8863, 203, 5411, 289, 203, 5411, 2078, 16397, 1011, 4833, 63, 77, 8009, 18687, 31, 203, 3639, 289, 203, 203, 3639, 2583, 12, 4963, 16397, 422, 12619, 16, 315, 5269, 11622, 353, 486, 12619, 8863, 203, 203, 565, 445, 444, 6001, 2954, 281, 16397, 12, 203, 3639, 1758, 290, 1222, 1887, 16, 203, 3639, 2254, 2313, 3354, 16397, 16, 203, 3639, 2254, 2313, 9946, 16397, 203, 565, 289, 203, 203, 203, 565, 445, 444, 6793, 14667, 16397, 12, 203, 3639, 1758, 290, 1222, 1887, 16, 203, 3639, 2254, 2313, 11622, 203, 565, 289, 203, 203, 565, 289, 203, 203, 203, 565, 445, 787, 1085, 30746, 12, 203, 3639, 1758, 290, 1222, 1887, 16, 203, 3639, 1758, 981, 67, 2977, 264, 1887, 203, 565, 289, 203, 203, 565, 445, 3929, 751, 12, 203, 3639, 1758, 290, 1222, 1887, 16, 203, 3639, 1731, 3778, 3372, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 533, 3778, 981, 203, 565, 289, 203, 203, 565, 445, 981, 19081, 49, 474, 12, 203, 3639, 1758, 290, 1222, 1887, 16, 203, 3639, 1731, 3778, 3372, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 533, 3778, 981, 16, 203, 3639, 1758, 8027, 203, 565, 289, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 4833, 18, 2469, 31, 277, 27245, 288, 203, 5411, 364, 261, 11890, 525, 273, 277, 397, 404, 31, 525, 411, 4833, 18, 2469, 31, 525, 27245, 288, 203, 7734, 2583, 12, 7640, 63, 77, 8009, 5990, 1887, 480, 4833, 63, 78, 8009, 5990, 1887, 16, 315, 11826, 3140, 6138, 1392, 8863, 203, 5411, 289, 203, 5411, 2078, 16397, 1011, 4833, 63, 77, 8009, 18687, 31, 203, 3639, 289, 203, 203, 3639, 2583, 12, 4963, 16397, 422, 12619, 16, 315, 5269, 11622, 353, 486, 12619, 8863, 203, 203, 3639, 309, 261, 26405, 422, 453, 2012, 21390, 18, 6793, 13, 288, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4833, 18, 2469, 31, 277, 27245, 288, 203, 7734, 3354, 52, 2012, 3621, 63, 82, 1222, 1887, 8009, 6206, 12, 7640, 63, 77, 19226, 203, 5411, 289, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4833, 18, 2469, 31, 277, 27245, 288, 203, 7734, 9946, 52, 2012, 3621, 63, 82, 1222, 1887, 8009, 6206, 12, 7640, 63, 77, 19226, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 3626, 453, 2012, 1114, 694, 12, 82, 1222, 1887, 16, 10766, 16, 4833, 1769, 203, 3639, 309, 261, 26405, 422, 453, 2012, 21390, 18, 6793, 13, 288, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4833, 18, 2469, 31, 277, 27245, 288, 203, 7734, 3354, 52, 2012, 3621, 63, 82, 1222, 1887, 8009, 6206, 12, 7640, 63, 77, 19226, 203, 5411, 289, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4833, 18, 2469, 31, 277, 27245, 288, 203, 7734, 9946, 52, 2012, 3621, 63, 82, 1222, 1887, 8009, 6206, 12, 7640, 63, 77, 19226, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 3626, 453, 2012, 1114, 694, 12, 82, 1222, 1887, 16, 10766, 16, 4833, 1769, 203, 3639, 289, 469, 309, 261, 26405, 422, 453, 2012, 21390, 18, 14893, 13, 288, 203, 3639, 309, 261, 26405, 422, 453, 2012, 21390, 18, 6793, 13, 288, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4833, 18, 2469, 31, 277, 27245, 288, 203, 7734, 3354, 52, 2012, 3621, 63, 82, 1222, 1887, 8009, 6206, 12, 7640, 63, 77, 19226, 203, 5411, 289, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4833, 18, 2469, 31, 277, 27245, 288, 203, 7734, 9946, 52, 2012, 3621, 63, 82, 1222, 1887, 8009, 6206, 12, 7640, 63, 77, 19226, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 3626, 453, 2012, 1114, 694, 12, 82, 1222, 1887, 16, 10766, 16, 4833, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/137/0x5dE8baA77325EC8B6f0682cC1DC0f799596d8Cbc/sources/Pool/AdvancePool.sol
* @dev update Harvest Fee amount @param _harvestFee harvest fee in BUSD/
function updateHarvestFeeAmount( uint256 _harvestFee ) external onlyOwner { HARVEST_FEE = _harvestFee; }
4,765,476
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 1089, 670, 297, 26923, 30174, 3844, 632, 891, 389, 30250, 26923, 14667, 17895, 26923, 14036, 316, 605, 3378, 40, 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,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, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 2018 ZeroEx Intl. 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.5.5; import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol"; import "./libs/LibConstants.sol"; import "./mixins/MWeth.sol"; contract MixinWeth is LibMath, LibConstants, MWeth { /// @dev Default payabale function, this allows us to withdraw WETH function () external payable { require( msg.sender == address(ETHER_TOKEN), "DEFAULT_FUNCTION_WETH_CONTRACT_ONLY" ); } /// @dev Converts message call's ETH value into WETH. function convertEthToWeth() internal { require( msg.value > 0, "INVALID_MSG_VALUE" ); ETHER_TOKEN.deposit.value(msg.value)(); } /// @dev Transfers feePercentage of WETH spent on primary orders to feeRecipient. /// Refunds any excess ETH to msg.sender. /// @param wethSoldExcludingFeeOrders Amount of WETH sold when filling primary orders. /// @param wethSoldForZrx Amount of WETH sold when purchasing ZRX required for primary order fees. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. function transferEthFeeAndRefund( uint256 wethSoldExcludingFeeOrders, uint256 wethSoldForZrx, uint256 feePercentage, address payable feeRecipient ) internal { // Ensure feePercentage is less than 5%. require( feePercentage <= MAX_FEE_PERCENTAGE, "FEE_PERCENTAGE_TOO_LARGE" ); // Ensure that no extra WETH owned by this contract has been sold. uint256 wethSold = safeAdd(wethSoldExcludingFeeOrders, wethSoldForZrx); require( wethSold <= msg.value, "OVERSOLD_WETH" ); // Calculate amount of WETH that hasn't been sold. uint256 wethRemaining = safeSub(msg.value, wethSold); // Calculate ETH fee to pay to feeRecipient. uint256 ethFee = getPartialAmountFloor( feePercentage, PERCENTAGE_DENOMINATOR, wethSoldExcludingFeeOrders ); // Ensure fee is less than amount of WETH remaining. require( ethFee <= wethRemaining, "INSUFFICIENT_ETH_REMAINING" ); // Do nothing if no WETH remaining if (wethRemaining > 0) { // Convert remaining WETH to ETH ETHER_TOKEN.withdraw(wethRemaining); // Pay ETH to feeRecipient if (ethFee > 0) { feeRecipient.transfer(ethFee); } // Refund remaining ETH to msg.sender. uint256 ethRefund = safeSub(wethRemaining, ethFee); if (ethRefund > 0) { msg.sender.transfer(ethRefund); } } } }
@dev Transfers feePercentage of WETH spent on primary orders to feeRecipient. Refunds any excess ETH to msg.sender. @param wethSoldExcludingFeeOrders Amount of WETH sold when filling primary orders. @param wethSoldForZrx Amount of WETH sold when purchasing ZRX required for primary order fees. @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. @param feeRecipient Address that will receive ETH when orders are filled. Ensure feePercentage is less than 5%. Ensure that no extra WETH owned by this contract has been sold. Calculate amount of WETH that hasn't been sold. Calculate ETH fee to pay to feeRecipient. Ensure fee is less than amount of WETH remaining. Do nothing if no WETH remaining Convert remaining WETH to ETH Pay ETH to feeRecipient
function transferEthFeeAndRefund( uint256 wethSoldExcludingFeeOrders, uint256 wethSoldForZrx, uint256 feePercentage, address payable feeRecipient ) internal { require( feePercentage <= MAX_FEE_PERCENTAGE, "FEE_PERCENTAGE_TOO_LARGE" ); uint256 wethSold = safeAdd(wethSoldExcludingFeeOrders, wethSoldForZrx); require( wethSold <= msg.value, "OVERSOLD_WETH" ); uint256 wethRemaining = safeSub(msg.value, wethSold); uint256 ethFee = getPartialAmountFloor( feePercentage, PERCENTAGE_DENOMINATOR, wethSoldExcludingFeeOrders ); require( ethFee <= wethRemaining, "INSUFFICIENT_ETH_REMAINING" ); if (wethRemaining > 0) { ETHER_TOKEN.withdraw(wethRemaining); if (ethFee > 0) { feeRecipient.transfer(ethFee); } if (ethRefund > 0) { msg.sender.transfer(ethRefund); } } }
6,428,719
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 2604, 18881, 14036, 16397, 434, 678, 1584, 44, 26515, 603, 3354, 11077, 358, 14036, 18241, 18, 1377, 3941, 19156, 1281, 23183, 512, 2455, 358, 1234, 18, 15330, 18, 632, 891, 341, 546, 55, 1673, 424, 18596, 14667, 16528, 16811, 434, 678, 1584, 44, 272, 1673, 1347, 25740, 3354, 11077, 18, 632, 891, 341, 546, 55, 1673, 1290, 62, 20122, 16811, 434, 678, 1584, 44, 272, 1673, 1347, 5405, 343, 11730, 2285, 54, 60, 1931, 364, 3354, 1353, 1656, 281, 18, 632, 891, 14036, 16397, 21198, 410, 434, 678, 1584, 44, 272, 1673, 716, 903, 8843, 329, 487, 14036, 358, 20635, 6835, 14036, 18241, 18, 632, 891, 14036, 18241, 5267, 716, 903, 6798, 512, 2455, 1347, 11077, 854, 6300, 18, 7693, 14036, 16397, 353, 5242, 2353, 1381, 9, 18, 7693, 716, 1158, 2870, 678, 1584, 44, 16199, 635, 333, 6835, 711, 2118, 272, 1673, 18, 9029, 3844, 434, 678, 1584, 44, 716, 13342, 1404, 2118, 272, 1673, 18, 9029, 512, 2455, 14036, 358, 8843, 358, 14036, 18241, 18, 7693, 14036, 353, 5242, 2353, 3844, 434, 678, 1584, 44, 4463, 18, 2256, 5083, 309, 1158, 678, 1584, 44, 4463, 4037, 4463, 678, 1584, 44, 358, 512, 2455, 13838, 512, 2455, 358, 14036, 18241, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14667, 16528, 16, 203, 3639, 2254, 5034, 341, 546, 55, 1673, 1290, 62, 20122, 16, 203, 3639, 2254, 5034, 14036, 16397, 16, 203, 3639, 1758, 8843, 429, 14036, 18241, 203, 565, 262, 203, 3639, 2713, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 14036, 16397, 1648, 4552, 67, 8090, 41, 67, 3194, 19666, 2833, 16, 203, 5411, 315, 8090, 41, 67, 3194, 19666, 2833, 67, 4296, 51, 67, 48, 28847, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 341, 546, 55, 1673, 273, 4183, 986, 12, 91, 546, 55, 1673, 424, 18596, 14667, 16528, 16, 341, 546, 55, 1673, 1290, 62, 20122, 1769, 203, 3639, 2583, 12, 203, 5411, 341, 546, 55, 1673, 1648, 1234, 18, 1132, 16, 203, 5411, 315, 12959, 55, 11846, 67, 59, 1584, 44, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 341, 546, 11429, 273, 4183, 1676, 12, 3576, 18, 1132, 16, 341, 546, 55, 1673, 1769, 203, 203, 3639, 2254, 5034, 13750, 14667, 273, 13657, 649, 6275, 42, 5807, 12, 203, 5411, 14036, 16397, 16, 203, 5411, 10950, 19666, 2833, 67, 13296, 1872, 706, 3575, 16, 203, 5411, 341, 546, 55, 1673, 424, 18596, 14667, 16528, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 13750, 14667, 1648, 341, 546, 11429, 16, 203, 5411, 315, 706, 6639, 42, 1653, 7266, 2222, 67, 1584, 44, 67, 862, 19803, 1360, 6, 203, 3639, 11272, 203, 203, 3639, 309, 261, 91, 546, 11429, 405, 374, 13, 288, 203, 5411, 512, 19905, 67, 8412, 18, 1918, 9446, 12, 91, 546, 11429, 1769, 203, 203, 5411, 309, 261, 546, 14667, 405, 374, 13, 288, 203, 7734, 14036, 18241, 18, 13866, 12, 546, 14667, 1769, 203, 5411, 289, 203, 203, 5411, 309, 261, 546, 21537, 405, 374, 13, 288, 203, 7734, 1234, 18, 15330, 18, 13866, 12, 546, 21537, 1769, 203, 5411, 289, 203, 3639, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6f9140097Ab6278B41Cf9597a597030207b8D75d/sources/lib/seaport-core/src/lib/ConsiderationDecoder.sol
Check that returndatasize is at least four words: offerOffset, considerationOffset, offerLength, & considerationLength Proceed if enough returndata is present to continue evaluation. Copy first two words of returndata (the offsets to offer and consideration array lengths) to scratch space. If valid length, check that offsets are within returndata. Only proceed if length (and thus encoding) is valid so far. Copy length of offer array to scratch space. Copy length of consideration array to scratch space. Calculate total size of offer & consideration arrays. Add 4 words to total size to cover the offset and length fields of the two arrays. Don't continue if returndatasize exceeds 65535 bytes or is greater than the calculated size. Set first word of scratch space to 0 so length of offer/consideration are set to 0 on invalid encoding. Retrieve the current free memory pointer. Allocate memory for the array. Write the length of the array to the start of free memory. Use offset from length to minimize stack depth. Iterate over each element. Write the memory pointer to the accompanying head offset. Copy itemType, token, identifier and amount. Copy amount to endAmount. Update read pointer, next tail pointer, and head offset.
function _decodeOrderComponentsAsOrderParameters(CalldataPointer cdPtr) internal pure returns (MemoryPointer mPtr) } function _decodeGenerateOrderReturndata() internal pure returns (uint256 invalidEncoding, MemoryPointer offer, MemoryPointer consideration) assembly { invalidEncoding := lt(returndatasize(), FourWords) let offsetOffer let offsetConsideration let offerLength let considerationLength if iszero(invalidEncoding) { returndatacopy(0, 0, TwoWords) offsetOffer := mload(0) offsetConsideration := mload(OneWord) let invalidOfferOffset := gt(offsetOffer, returndatasize()) let invalidConsiderationOffset := gt(offsetConsideration, returndatasize()) invalidEncoding := or(invalidOfferOffset, invalidConsiderationOffset) if iszero(invalidEncoding) { returndatacopy(0, offsetOffer, OneWord) offerLength := mload(0) returndatacopy(OneWord, offsetConsideration, OneWord) considerationLength := mload(OneWord) { let totalOfferSize := shl(SpentItem_size_shift, offerLength) let totalConsiderationSize := mul(ReceivedItem_size, considerationLength) let totalSize := add(FourWords, add(totalOfferSize, totalConsiderationSize)) invalidEncoding := or( gt(or(offerLength, considerationLength), generateOrder_maximum_returndatasize), gt(totalSize, returndatasize()) ) mstore(0, 0) } } } if iszero(invalidEncoding) { offer := copySpentItemsAsOfferItems(add(offsetOffer, OneWord), offerLength) consideration := copyReceivedItemsAsConsiderationItems(add(offsetConsideration, OneWord), considerationLength) } function copySpentItemsAsOfferItems(rdPtrHead, length) -> mPtrLength { mPtrLength := mload(FreeMemoryPointerSlot) mstore(FreeMemoryPointerSlot, add(mPtrLength, add(OneWord, mul(length, OfferItem_size_with_length)))) mstore(mPtrLength, length) let headOffsetFromLength := OneWord let headSizeWithLength := shl(OneWordShift, add(1, length)) let mPtrTailNext := add(mPtrLength, headSizeWithLength) mstore(add(mPtrLength, headOffsetFromLength), mPtrTailNext) returndatacopy(mPtrTailNext, rdPtrHead, SpentItem_size) mstore(add(mPtrTailNext, Common_endAmount_offset), mload(add(mPtrTailNext, Common_amount_offset))) rdPtrHead := add(rdPtrHead, SpentItem_size) mPtrTailNext := add(mPtrTailNext, OfferItem_size) headOffsetFromLength := add(headOffsetFromLength, OneWord) } }
9,676,142
[ 1, 4625, 348, 7953, 560, 30, 225, 2073, 716, 327, 13178, 554, 353, 622, 4520, 12792, 4511, 30, 10067, 2335, 16, 5260, 367, 2335, 16, 10067, 1782, 16, 473, 5260, 367, 1782, 1186, 5288, 309, 7304, 327, 892, 353, 3430, 358, 1324, 9873, 18, 5631, 1122, 2795, 4511, 434, 327, 892, 261, 5787, 8738, 358, 10067, 471, 5260, 367, 526, 10917, 13, 358, 15289, 3476, 18, 971, 923, 769, 16, 866, 716, 8738, 854, 3470, 327, 892, 18, 5098, 11247, 309, 769, 261, 464, 12493, 2688, 13, 353, 923, 1427, 10247, 18, 5631, 769, 434, 10067, 526, 358, 15289, 3476, 18, 5631, 769, 434, 5260, 367, 526, 358, 15289, 3476, 18, 9029, 2078, 963, 434, 10067, 473, 5260, 367, 5352, 18, 1436, 1059, 4511, 358, 2078, 963, 358, 5590, 326, 1384, 471, 769, 1466, 434, 326, 2795, 5352, 18, 7615, 1404, 1324, 309, 327, 13178, 554, 14399, 10147, 1731, 578, 353, 6802, 2353, 326, 8894, 963, 18, 1000, 1122, 2076, 434, 15289, 3476, 358, 374, 1427, 769, 434, 10067, 19, 8559, 3585, 367, 854, 444, 358, 374, 603, 2057, 2688, 18, 10708, 326, 783, 4843, 3778, 4407, 18, 22222, 3778, 364, 326, 526, 18, 2598, 326, 769, 434, 326, 526, 358, 326, 787, 434, 4843, 3778, 18, 2672, 1384, 628, 769, 358, 18935, 2110, 3598, 18, 11436, 1879, 1517, 930, 18, 2598, 326, 3778, 4407, 358, 326, 1721, 16840, 310, 910, 1384, 18, 5631, 23080, 16, 1147, 16, 2756, 471, 3844, 18, 5631, 3844, 358, 679, 6275, 18, 2315, 855, 4407, 16, 1024, 5798, 4407, 16, 471, 910, 1384, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3922, 2448, 7171, 1463, 2448, 2402, 12, 1477, 892, 4926, 7976, 5263, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 6031, 4926, 312, 5263, 13, 203, 565, 289, 203, 203, 565, 445, 389, 3922, 4625, 2448, 990, 892, 1435, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 5034, 2057, 4705, 16, 9251, 4926, 10067, 16, 9251, 4926, 5260, 367, 13, 203, 3639, 19931, 288, 203, 5411, 2057, 4705, 519, 13489, 12, 2463, 13178, 554, 9334, 478, 477, 7363, 13, 203, 203, 5411, 2231, 1384, 10513, 203, 5411, 2231, 1384, 9054, 3585, 367, 203, 5411, 2231, 10067, 1782, 203, 5411, 2231, 5260, 367, 1782, 203, 203, 5411, 309, 353, 7124, 12, 5387, 4705, 13, 288, 203, 7734, 327, 892, 3530, 12, 20, 16, 374, 16, 16896, 7363, 13, 203, 7734, 1384, 10513, 519, 312, 945, 12, 20, 13, 203, 7734, 1384, 9054, 3585, 367, 519, 312, 945, 12, 3335, 3944, 13, 203, 203, 7734, 2231, 2057, 10513, 2335, 519, 9879, 12, 3348, 10513, 16, 327, 13178, 554, 10756, 203, 7734, 2231, 2057, 9054, 3585, 367, 2335, 519, 9879, 12, 3348, 9054, 3585, 367, 16, 327, 13178, 554, 10756, 203, 203, 7734, 2057, 4705, 519, 578, 12, 5387, 10513, 2335, 16, 2057, 9054, 3585, 367, 2335, 13, 203, 7734, 309, 353, 7124, 12, 5387, 4705, 13, 288, 203, 10792, 327, 892, 3530, 12, 20, 16, 1384, 10513, 16, 6942, 3944, 13, 203, 10792, 10067, 1782, 519, 312, 945, 12, 20, 13, 203, 203, 10792, 327, 892, 3530, 12, 3335, 3944, 16, 1384, 9054, 3585, 367, 16, 6942, 3944, 13, 203, 10792, 5260, 367, 1782, 519, 312, 945, 12, 3335, 3944, 13, 203, 203, 10792, 288, 203, 13491, 2231, 2078, 10513, 1225, 519, 699, 80, 12, 3389, 319, 1180, 67, 1467, 67, 4012, 16, 10067, 1782, 13, 203, 13491, 2231, 2078, 9054, 3585, 367, 1225, 519, 14064, 12, 8872, 1180, 67, 1467, 16, 5260, 367, 1782, 13, 203, 203, 13491, 2231, 24611, 519, 527, 12, 42, 477, 7363, 16, 527, 12, 4963, 10513, 1225, 16, 2078, 9054, 3585, 367, 1225, 3719, 203, 13491, 2057, 4705, 519, 203, 18701, 578, 12, 203, 27573, 9879, 12, 280, 12, 23322, 1782, 16, 5260, 367, 1782, 3631, 2103, 2448, 67, 15724, 67, 2463, 13178, 554, 3631, 203, 27573, 9879, 12, 4963, 1225, 16, 327, 13178, 554, 10756, 203, 18701, 262, 203, 203, 13491, 312, 2233, 12, 20, 16, 374, 13, 203, 10792, 289, 203, 7734, 289, 203, 5411, 289, 203, 203, 5411, 309, 353, 7124, 12, 5387, 4705, 13, 288, 203, 7734, 10067, 519, 1610, 3389, 319, 3126, 1463, 10513, 3126, 12, 1289, 12, 3348, 10513, 16, 6942, 3944, 3631, 10067, 1782, 13, 203, 203, 7734, 5260, 367, 519, 203, 10792, 1610, 8872, 3126, 1463, 9054, 3585, 367, 3126, 12, 1289, 12, 3348, 9054, 3585, 367, 16, 6942, 3944, 3631, 5260, 367, 1782, 13, 203, 5411, 289, 203, 203, 5411, 445, 1610, 3389, 319, 3126, 1463, 10513, 3126, 12, 13623, 5263, 1414, 16, 769, 13, 317, 312, 5263, 1782, 288, 203, 7734, 312, 5263, 1782, 519, 312, 945, 12, 9194, 6031, 4926, 8764, 13, 203, 203, 7734, 312, 2233, 12, 9194, 6031, 4926, 8764, 16, 527, 12, 81, 5263, 1782, 16, 527, 12, 3335, 3944, 16, 14064, 12, 2469, 16, 25753, 1180, 67, 1467, 67, 1918, 67, 2469, 3719, 3719, 203, 203, 7734, 312, 2233, 12, 81, 5263, 1782, 16, 769, 13, 203, 203, 7734, 2231, 910, 2335, 1265, 1782, 519, 6942, 3944, 203, 7734, 2231, 910, 1225, 1190, 1782, 519, 699, 80, 12, 3335, 3944, 10544, 16, 527, 12, 21, 16, 769, 3719, 203, 7734, 2231, 312, 5263, 12363, 2134, 519, 527, 12, 81, 5263, 1782, 16, 910, 1225, 1190, 1782, 13, 203, 203, 10792, 312, 2233, 12, 1289, 12, 81, 5263, 1782, 16, 910, 2335, 1265, 1782, 3631, 312, 5263, 12363, 2134, 13, 203, 203, 10792, 327, 892, 3530, 12, 81, 5263, 12363, 2134, 16, 9437, 5263, 1414, 16, 5878, 319, 1180, 67, 1467, 13, 203, 203, 10792, 312, 2233, 12, 1289, 12, 81, 5263, 12363, 2134, 16, 5658, 67, 409, 6275, 67, 3348, 3631, 312, 945, 12, 1289, 12, 81, 5263, 12363, 2134, 16, 5658, 67, 8949, 67, 3348, 20349, 203, 203, 10792, 9437, 5263, 1414, 519, 527, 12, 13623, 5263, 1414, 16, 5878, 319, 1180, 67, 1467, 13, 203, 10792, 312, 5263, 12363, 2134, 519, 527, 12, 81, 5263, 12363, 2134, 16, 25753, 1180, 67, 1467, 13, 203, 10792, 910, 2335, 1265, 1782, 519, 527, 12, 1978, 2335, 1265, 1782, 16, 6942, 3944, 13, 203, 7734, 289, 203, 5411, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x595f279DE4b5DF1e47Ca55b65175D8a9A935A0fA/sources/ERC721Metadata.sol
Token name Token symbol Optional mapping for token URIs Optional mapping for token URL
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { string private _name; string private _symbol; mapping(uint256 => string) private _tokenURIs; mapping(uint256 => string) private _tokenURLSomnium; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _registerInterface(_INTERFACE_ID_ERC721_METADATA); } function name() external view returns (string memory) { return _name; } function symbol() external view returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } function tokenURL(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URL query for nonexistent token"); return _tokenURLSomnium[tokenId]; } function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } function _setTokenURLSomnium(uint256 tokenId, string memory url) internal { require(_exists(tokenId), "ERC721Metadata: URL set of nonexistent token"); _tokenURLSomnium[tokenId] = url; } function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } }
15,893,769
[ 1, 4625, 348, 7953, 560, 30, 225, 3155, 508, 3155, 3273, 4055, 2874, 364, 1147, 24565, 4055, 2874, 364, 1147, 1976, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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7175, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 3238, 389, 2316, 1099, 2520, 31, 203, 377, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 3238, 389, 2316, 1785, 55, 362, 82, 5077, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 18865, 67, 734, 67, 654, 39, 27, 5340, 67, 22746, 273, 374, 92, 25, 70, 25, 73, 24347, 74, 31, 203, 203, 565, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 203, 3639, 389, 4861, 1358, 24899, 18865, 67, 734, 67, 654, 39, 27, 5340, 67, 22746, 1769, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 3903, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 2277, 30, 3699, 843, 364, 1661, 19041, 1147, 8863, 203, 3639, 327, 389, 2316, 1099, 2520, 63, 2316, 548, 15533, 203, 565, 289, 203, 377, 203, 565, 445, 1147, 1785, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 2277, 30, 1976, 843, 364, 1661, 19041, 1147, 8863, 203, 3639, 327, 389, 2316, 1785, 55, 362, 82, 5077, 63, 2316, 548, 15533, 203, 565, 289, 203, 203, 565, 445, 389, 542, 1345, 3098, 12, 11890, 5034, 1147, 548, 16, 533, 3778, 2003, 13, 2713, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 2277, 30, 3699, 444, 434, 1661, 19041, 1147, 8863, 203, 3639, 389, 2316, 1099, 2520, 63, 2316, 548, 65, 273, 2003, 31, 203, 565, 289, 203, 377, 203, 565, 445, 389, 542, 1345, 1785, 55, 362, 82, 5077, 12, 11890, 5034, 1147, 548, 16, 533, 3778, 880, 13, 2713, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 2277, 30, 1976, 444, 434, 1661, 19041, 1147, 8863, 203, 3639, 389, 2316, 1785, 55, 362, 82, 5077, 63, 2316, 548, 65, 273, 880, 31, 203, 565, 289, 203, 203, 565, 445, 389, 70, 321, 12, 2867, 3410, 16, 2254, 5034, 1147, 548, 13, 2713, 288, 203, 3639, 2240, 6315, 70, 321, 12, 8443, 16, 1147, 548, 1769, 203, 203, 3639, 309, 261, 3890, 24899, 2316, 1099, 2520, 63, 2316, 548, 65, 2934, 2469, 480, 374, 13, 288, 203, 5411, 1430, 389, 2316, 1099, 2520, 63, 2316, 548, 15533, 203, 3639, 289, 203, 565, 289, 203, 565, 445, 389, 70, 321, 12, 2867, 3410, 16, 2254, 5034, 1147, 548, 13, 2713, 288, 203, 3639, 2240, 6315, 70, 321, 12, 8443, 16, 1147, 548, 1769, 203, 203, 3639, 309, 261, 3890, 24899, 2316, 1099, 2520, 63, 2316, 548, 65, 2934, 2469, 480, 374, 13, 288, 203, 5411, 1430, 389, 2316, 1099, 2520, 63, 2316, 548, 15533, 203, 3639, 289, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.12; interface ib { function acceptGov() external; function balanceOf(address) external view returns (uint); function burn(uint amount) external; function deposit() external; function mint(uint amount) external; function profit() external; function setGov(address gov) external; function transfer(address dst, uint amount) external returns (bool); function withdraw(uint amount) external; } contract ib_controller { address public burner; // contract to normalize profit into ibEUR and distribute to ve_dist address public msig; address public next_msig; uint public commit_msig; uint public constant delay = 1 days; address[] public tokens; // list of tokens (simplifies profit calls) modifier is_msig() { require(msg.sender == msig); _; } constructor(address _msig, address _burner) { msig = _msig; burner = _burner; } // set the burner contract that normalizes tokens function set_burner(address _burner) is_msig external { burner = _burner; } // set the new msig with 1 day delay function set_msig(address _msig) is_msig external { next_msig = _msig; commit_msig = block.timestamp + delay; } // accept msig for the new controller function accept_msig() external { require(msg.sender == next_msig && commit_msig < block.timestamp); msig = next_msig; } // used to accept gov on underlying ib tokens for this contract function accept_gov(address token) is_msig external { ib(token).acceptGov(); tokens.push(token); } // set the governance for a token to a new governance function set_gov(address token, address nextgov) is_msig external { ib(token).setGov(nextgov); } // mint new ib tokens and deposit into the Iron Bank function mint_and_deposit(address token, uint amount) is_msig external { ib(token).mint(amount); ib(token).deposit(); } // withdraw ib tokens from Iron Bank and burn function withdraw_and_burn(address token, uint amount) is_msig external { ib(token).withdraw(amount); } // claim profits and distribute to ve_dist function profit() external { profit(tokens); } // fallback incase tokens are changed to a new governance function profit(address[] memory _tokens) public { for (uint i = 0; i < _tokens.length; i++) { ib _token = ib(_tokens[i]); _token.profit(); _token.transfer(burner, _token.balanceOf(address(this))); } } }
used to accept gov on underlying ib tokens for this contract
function accept_gov(address token) is_msig external { ib(token).acceptGov(); tokens.push(token); }
12,120,550
[ 1, 4625, 348, 7953, 560, 30, 225, 1399, 358, 2791, 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 75, 1527, 12, 2867, 1147, 13, 353, 67, 959, 360, 3903, 288, 203, 3639, 9834, 12, 2316, 2934, 9436, 43, 1527, 5621, 203, 3639, 2430, 18, 6206, 12, 2316, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/28/0xf94BF3984A8E0cd3abcd7C3A5CD352AA97424694/sources/project_/contracts/Dating.sol
Initial owners of the contract to make this easier Some default users
constructor() { owner = msg.sender; users.push(alice); users.push(bob); users.push(charlie); people[address(1)] = alice; people[address(2)] = bob; people[address(3)] = charlie; numberOfUsers = 3; }
16,365,784
[ 1, 4625, 348, 7953, 560, 30, 225, 10188, 25937, 434, 326, 6835, 358, 1221, 333, 15857, 10548, 805, 3677, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 3677, 18, 6206, 12, 287, 1812, 1769, 203, 3639, 3677, 18, 6206, 12, 70, 947, 1769, 203, 3639, 3677, 18, 6206, 12, 3001, 549, 73, 1769, 203, 3639, 16951, 63, 2867, 12, 21, 25887, 273, 524, 1812, 31, 203, 3639, 16951, 63, 2867, 12, 22, 25887, 273, 800, 70, 31, 203, 3639, 16951, 63, 2867, 12, 23, 25887, 273, 1149, 549, 73, 31, 203, 203, 3639, 7922, 6588, 273, 890, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.8.0; // SPDX-License-Identifier: MIT import "OpenZeppelin/openzeppelin-contracts@4.1.0/contracts/access/Ownable.sol"; import "../interfaces/IERC2981.sol"; import "./Token.sol"; /** * @title NFT Marketplace with ERC-2981 support * @notice Defines a marketplace to bid on and sell NFTs. * Sends royalties to rightsholder on each sale if applicable. */ contract Marketplace { struct SellOffer { address seller; uint256 minPrice; } struct BuyOffer { address buyer; uint256 price; uint256 createTime; } bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; // Store the address of the contract of the NFT to trade. Can be changed in // constructor or with a call to setTokenContractAddress. address public _tokenContractAddress = address(0); // Store all active sell offers and maps them to their respective token ids mapping(uint256 => SellOffer) public activeSellOffers; // Store all active buy offers and maps them to their respective token ids mapping(uint256 => BuyOffer) public activeBuyOffers; // Token contract Token token; // Escrow for buy offers mapping(address => mapping(uint256 => uint256)) public buyOffersEscrow; // Events event NewSellOffer(uint256 tokenId, address seller, uint256 value); event NewBuyOffer(uint256 tokenId, address buyer, uint256 value); event SellOfferWithdrawn(uint256 tokenId, address seller); event BuyOfferWithdrawn(uint256 tokenId, address buyer); event RoyaltiesPaid(uint256 tokenId, uint value); event Sale(uint256 tokenId, address seller, address buyer, uint256 value); constructor(address tokenContractAddress) { _tokenContractAddress = tokenContractAddress; token = Token(_tokenContractAddress); } /// @notice Checks if NFT contract implements the ERC-2981 interface /// @param _contract - the address of the NFT contract to query /// @return true if ERC-2981 interface is supported, false otherwise function _checkRoyalties(address _contract) internal returns (bool) { (bool success) = IERC2981(_contract). supportsInterface(_INTERFACE_ID_ERC2981); return success; } /// @notice Puts a token on sale at a given price /// @param tokenId - id of the token to sell /// @param minPrice - minimum price at which the token can be sold function makeSellOffer(uint256 tokenId, uint256 minPrice) external isMarketable(tokenId) tokenOwnerOnly(tokenId) { // Create sell offer activeSellOffers[tokenId] = SellOffer({seller : msg.sender, minPrice : minPrice}); // Broadcast sell offer emit NewSellOffer(tokenId, msg.sender, minPrice); } /// @notice Withdraw a sell offer /// @param tokenId - id of the token whose sell order needs to be cancelled function withdrawSellOffer(uint256 tokenId) external isMarketable(tokenId) { require(activeSellOffers[tokenId].seller != address(0), "No sale offer"); require(activeSellOffers[tokenId].seller == msg.sender, "Not seller"); // Removes the current sell offer delete (activeSellOffers[tokenId]); // Broadcast offer withdrawal emit SellOfferWithdrawn(tokenId, msg.sender); } /// @notice Transfers royalties to the rightsowner if applicable /// @param tokenId - the NFT assed queried for royalties /// @param grossSaleValue - the price at which the asset will be sold /// @return netSaleAmount - the value that will go to the seller after /// deducting royalties function _deduceRoyalties(uint256 tokenId, uint256 grossSaleValue) internal returns (uint256 netSaleAmount) { // Get amount of royalties to pays and recipient (address royaltiesReceiver, uint256 royaltiesAmount) = token .royaltyInfo(tokenId, grossSaleValue); // Deduce royalties from sale value uint256 netSaleValue = grossSaleValue - royaltiesAmount; // Transfer royalties to rightholder if not zero if (royaltiesAmount > 0) { royaltiesReceiver.call{value: royaltiesAmount}(''); } // Broadcast royalties payment emit RoyaltiesPaid(tokenId, royaltiesAmount); return netSaleValue; } /// @notice Purchases a token and transfers royalties if applicable /// @param tokenId - id of the token to sell function purchase(uint256 tokenId) external tokenOwnerForbidden(tokenId) payable { address seller = activeSellOffers[tokenId].seller; require(seller != address(0), "No active sell offer"); // If, for some reason, the token is not approved anymore (transfer or // sale on another market place for instance), we remove the sell order // and throw if (token.getApproved(tokenId) != address(this)) { delete (activeSellOffers[tokenId]); // Broadcast offer withdrawal emit SellOfferWithdrawn(tokenId, seller); // Revert revert("Invalid sell offer"); } require(msg.value >= activeSellOffers[tokenId].minPrice, "Amount sent too low"); uint256 saleValue = msg.value; // Pay royalties if applicable if (_checkRoyalties(_tokenContractAddress)) { saleValue = _deduceRoyalties(tokenId, saleValue); } // Transfer funds to the seller activeSellOffers[tokenId].seller.call{value: saleValue}(''); // And token to the buyer token.safeTransferFrom( seller, msg.sender, tokenId ); // Remove all sell and buy offers delete (activeSellOffers[tokenId]); delete (activeBuyOffers[tokenId]); // Broadcast the sale emit Sale(tokenId, seller, msg.sender, msg.value); } /// @notice Makes a buy offer for a token. The token does not need to have /// been put up for sale. A buy offer can not be withdrawn or /// replaced for 24 hours. Amount of the offer is put in escrow /// until the offer is withdrawn or superceded /// @param tokenId - id of the token to buy function makeBuyOffer(uint256 tokenId) external tokenOwnerForbidden(tokenId) payable { // Reject the offer if item is already available for purchase at a // lower or identical price if (activeSellOffers[tokenId].minPrice != 0) { require((msg.value > activeSellOffers[tokenId].minPrice), "Sell order at this price or lower exists"); } // Only process the offer if it is higher than the previous one or the // previous one has expired require(activeBuyOffers[tokenId].createTime < (block.timestamp - 1 days) || msg.value > activeBuyOffers[tokenId].price, "Previous buy offer higher or not expired"); address previousBuyOfferOwner = activeBuyOffers[tokenId].buyer; uint256 refundBuyOfferAmount = buyOffersEscrow[previousBuyOfferOwner] [tokenId]; // Refund the owner of the previous buy offer buyOffersEscrow[previousBuyOfferOwner][tokenId] = 0; if (refundBuyOfferAmount > 0) { payable(previousBuyOfferOwner).call{value: refundBuyOfferAmount}(''); } // Create a new buy offer activeBuyOffers[tokenId] = BuyOffer({buyer : msg.sender, price : msg.value, createTime : block.timestamp}); // Create record of funds deposited for this offer buyOffersEscrow[msg.sender][tokenId] = msg.value; // Broadcast the buy offer emit NewBuyOffer(tokenId, msg.sender, msg.value); } /// @notice Withdraws a buy offer. Can only be withdrawn a day after being /// posted /// @param tokenId - id of the token whose buy order to remove function withdrawBuyOffer(uint256 tokenId) external lastBuyOfferExpired(tokenId) { require(activeBuyOffers[tokenId].buyer == msg.sender, "Not buyer"); uint256 refundBuyOfferAmount = buyOffersEscrow[msg.sender][tokenId]; // Set the buyer balance to 0 before refund buyOffersEscrow[msg.sender][tokenId] = 0; // Remove the current buy offer delete(activeBuyOffers[tokenId]); // Refund the current buy offer if it is non-zero if (refundBuyOfferAmount > 0) { msg.sender.call{value: refundBuyOfferAmount}(''); } // Broadcast offer withdrawal emit BuyOfferWithdrawn(tokenId, msg.sender); } /// @notice Lets a token owner accept the current buy offer /// (even without a sell offer) /// @param tokenId - id of the token whose buy order to accept function acceptBuyOffer(uint256 tokenId) external isMarketable(tokenId) tokenOwnerOnly(tokenId) { address currentBuyer = activeBuyOffers[tokenId].buyer; require(currentBuyer != address(0), "No buy offer"); uint256 saleValue = activeBuyOffers[tokenId].price; uint256 netSaleValue = saleValue; // Pay royalties if applicable if (_checkRoyalties(_tokenContractAddress)) { netSaleValue = _deduceRoyalties(tokenId, saleValue); } // Delete the current sell offer whether it exists or not delete (activeSellOffers[tokenId]); // Delete the buy offer that was accepted delete (activeBuyOffers[tokenId]); // Withdraw buyer's balance buyOffersEscrow[currentBuyer][tokenId] = 0; // Transfer funds to the seller msg.sender.call{value: netSaleValue}(''); // And token to the buyer token.safeTransferFrom( msg.sender, currentBuyer, tokenId ); // Broadcast the sale emit Sale(tokenId, msg.sender, currentBuyer, saleValue); } modifier isMarketable(uint256 tokenId) { require(token.getApproved(tokenId) == address(this), "Not approved"); _; } modifier tokenOwnerForbidden(uint256 tokenId) { require(token.ownerOf(tokenId) != msg.sender, "Token owner not allowed"); _; } modifier tokenOwnerOnly(uint256 tokenId) { require(token.ownerOf(tokenId) == msg.sender, "Not token owner"); _; } modifier lastBuyOfferExpired(uint256 tokenId) { require( activeBuyOffers[tokenId].createTime < (block.timestamp - 1 days), "Buy offer not expired"); _; } }
Broadcast the buy offer
emit NewBuyOffer(tokenId, msg.sender, msg.value);
13,042,327
[ 1, 4625, 348, 7953, 560, 30, 225, 19687, 326, 30143, 10067, 2, 0, 0, 0, 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 16, 1234, 18, 15330, 16, 1234, 18, 1132, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.21; // File: contracts/ISimpleCrowdsale.sol interface ISimpleCrowdsale { function getSoftCap() external view returns(uint256); function isContributorInLists(address contributorAddress) external view returns(bool); function processReservationFundContribution( address contributor, uint256 tokenAmount, uint256 tokenBonusAmount ) external payable; } // File: contracts/fund/ICrowdsaleReservationFund.sol /** * @title ICrowdsaleReservationFund * @dev ReservationFund methods used by crowdsale contract */ interface ICrowdsaleReservationFund { /** * @dev Check if contributor has transactions */ function canCompleteContribution(address contributor) external returns(bool); /** * @dev Complete contribution * @param contributor Contributor`s address */ function completeContribution(address contributor) external; /** * @dev Function accepts user`s contributed ether and amount of tokens to issue * @param contributor Contributor wallet address. * @param _tokensToIssue Token amount to issue * @param _bonusTokensToIssue Bonus token amount to issue */ function processContribution(address contributor, uint256 _tokensToIssue, uint256 _bonusTokensToIssue) external payable; /** * @dev Function returns current user`s contributed ether amount */ function contributionsOf(address contributor) external returns(uint256); /** * @dev Function is called on the end of successful crowdsale */ function onCrowdsaleEnd() external; } // File: contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ contract SafeMath { /** * @dev constructor */ function SafeMath() public { } function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(a >= b); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: 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; address public newOwner; event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract. */ function Ownable(address _owner) public { owner = _owner == address(0) ? msg.sender : _owner; } /** * @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 != owner); newOwner = _newOwner; } /** * @dev confirm ownership by a new owner */ function confirmOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = 0x0; } } // File: contracts/ReservationFund.sol contract ReservationFund is ICrowdsaleReservationFund, Ownable, SafeMath { bool public crowdsaleFinished = false; mapping(address => uint256) contributions; mapping(address => uint256) tokensToIssue; mapping(address => uint256) bonusTokensToIssue; ISimpleCrowdsale public crowdsale; event RefundPayment(address contributor, uint256 etherAmount); event TransferToFund(address contributor, uint256 etherAmount); event FinishCrowdsale(); function ReservationFund(address _owner) public Ownable(_owner) { } modifier onlyCrowdsale() { require(msg.sender == address(crowdsale)); _; } function setCrowdsaleAddress(address crowdsaleAddress) public onlyOwner { require(crowdsale == address(0)); crowdsale = ISimpleCrowdsale(crowdsaleAddress); } function onCrowdsaleEnd() external onlyCrowdsale { crowdsaleFinished = true; FinishCrowdsale(); } function canCompleteContribution(address contributor) external returns(bool) { if(crowdsaleFinished) { return false; } if(!crowdsale.isContributorInLists(contributor)) { return false; } if(contributions[contributor] == 0) { return false; } return true; } /** * @dev Function to check contributions by address */ function contributionsOf(address contributor) external returns(uint256) { return contributions[contributor]; } /** * @dev Process crowdsale contribution without whitelist */ function processContribution( address contributor, uint256 _tokensToIssue, uint256 _bonusTokensToIssue ) external payable onlyCrowdsale { contributions[contributor] = safeAdd(contributions[contributor], msg.value); tokensToIssue[contributor] = safeAdd(tokensToIssue[contributor], _tokensToIssue); bonusTokensToIssue[contributor] = safeAdd(bonusTokensToIssue[contributor], _bonusTokensToIssue); } /** * @dev Complete contribution after if user is whitelisted */ function completeContribution(address contributor) external { require(!crowdsaleFinished); require(crowdsale.isContributorInLists(contributor)); require(contributions[contributor] > 0); uint256 etherAmount = contributions[contributor]; uint256 tokenAmount = tokensToIssue[contributor]; uint256 tokenBonusAmount = bonusTokensToIssue[contributor]; contributions[contributor] = 0; tokensToIssue[contributor] = 0; bonusTokensToIssue[contributor] = 0; crowdsale.processReservationFundContribution.value(etherAmount)(contributor, tokenAmount, tokenBonusAmount); TransferToFund(contributor, etherAmount); } /** * @dev Refund payments if crowdsale is finalized */ function refundPayment(address contributor) public { require(crowdsaleFinished); require(contributions[contributor] > 0 || tokensToIssue[contributor] > 0); uint256 amountToRefund = contributions[contributor]; contributions[contributor] = 0; tokensToIssue[contributor] = 0; bonusTokensToIssue[contributor] = 0; contributor.transfer(amountToRefund); RefundPayment(contributor, amountToRefund); } }
* @dev Complete contribution after if user is whitelisted/
function completeContribution(address contributor) external { require(!crowdsaleFinished); require(crowdsale.isContributorInLists(contributor)); require(contributions[contributor] > 0); uint256 etherAmount = contributions[contributor]; uint256 tokenAmount = tokensToIssue[contributor]; uint256 tokenBonusAmount = bonusTokensToIssue[contributor]; contributions[contributor] = 0; tokensToIssue[contributor] = 0; bonusTokensToIssue[contributor] = 0; crowdsale.processReservationFundContribution.value(etherAmount)(contributor, tokenAmount, tokenBonusAmount); TransferToFund(contributor, etherAmount); }
7,678,838
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 14575, 24880, 1839, 309, 729, 353, 26944, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3912, 442, 4027, 12, 2867, 31123, 13, 3903, 288, 203, 3639, 2583, 12, 5, 71, 492, 2377, 5349, 10577, 1769, 203, 3639, 2583, 12, 71, 492, 2377, 5349, 18, 291, 442, 19293, 382, 7432, 12, 591, 19293, 10019, 203, 3639, 2583, 12, 591, 15326, 63, 591, 19293, 65, 405, 374, 1769, 203, 203, 3639, 2254, 5034, 225, 2437, 6275, 273, 13608, 6170, 63, 591, 19293, 15533, 203, 3639, 2254, 5034, 1147, 6275, 273, 2430, 774, 12956, 63, 591, 19293, 15533, 203, 3639, 2254, 5034, 1147, 38, 22889, 6275, 273, 324, 22889, 5157, 774, 12956, 63, 591, 19293, 15533, 203, 203, 3639, 13608, 6170, 63, 591, 19293, 65, 273, 374, 31, 203, 3639, 2430, 774, 12956, 63, 591, 19293, 65, 273, 374, 31, 203, 3639, 324, 22889, 5157, 774, 12956, 63, 591, 19293, 65, 273, 374, 31, 203, 203, 3639, 276, 492, 2377, 5349, 18, 2567, 18074, 42, 1074, 442, 4027, 18, 1132, 12, 2437, 6275, 21433, 591, 19293, 16, 1147, 6275, 16, 1147, 38, 22889, 6275, 1769, 203, 3639, 12279, 774, 42, 1074, 12, 591, 19293, 16, 225, 2437, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; //////////////////// // good morning ☀️ // //////////////////// contract GenerativeMorning is ERC721, Ownable { using Strings for uint; uint public sunrise; // epoch time in seconds for first sunrise bool public revealedOnOS; string public realDescription; string public twitterGMReceiver; string public sayItBackMessage; uint private dayLength = 43200; // in seconds event SayItBack(address sayer, string message, string receiver); constructor(uint inputSunrise, string memory receiver, string memory sayItBackMessageInput, string memory realDescriptionInput) ERC721("Generative Morning", "gm") { revealedOnOS = false; twitterGMReceiver = receiver; sayItBackMessage = sayItBackMessageInput; realDescription = realDescriptionInput; sunrise = inputSunrise; _safeMint(msg.sender, 1); } function tokenURI(uint tokenId) public view override returns (string memory) { if (revealedOnOS) { return realTokenURI(); } return hiddenTokenURI(); } function hiddenTokenURI() private pure returns (string memory) { return string(abi.encodePacked( 'data:application/json;utf8,', '{"name":"Generative Morning",', '"description":"gm at generativemorning.eth.link",', '"image":"', _generateHiddenImage(), '", "attributes":[', _generateHiddenMetadata(), ']', '}')); } function realTokenURI() public view returns (string memory) { return string(abi.encodePacked( 'data:application/json;utf8,', '{"name":"Generative Morning",', '"description":"', realDescription, '",', '"image":"', _generateRealImage(), '", "attributes":[', _generateRealMetadata(), ']', '}')); } function _generateHiddenImage() private pure returns (string memory) { return "data:image/svg+xml;utf8,<svg viewBox='0 0 400 400' width='400' height='400' xmlns='http://www.w3.org/2000/svg'><text x='50%' y='50%' style='font:700 30px sans-serif' text-anchor='middle' dominant-baseline='middle'>gm</text></svg>"; } function _generateHiddenMetadata() private pure returns (string memory) { return _wrapTrait("good", "morning"); } function _wrapTrait(string memory trait, string memory value) internal pure returns(string memory) { return string(abi.encodePacked( '{"trait_type":"', trait, '","value":"', value, '"}' )); } function isCurrentOwner(address account) private view returns (bool) { return balanceOf(account) == 1; } function isDayTime() public view returns (bool) { uint time = block.timestamp; uint timeSinceSunrise = time - sunrise; uint percentOfTwelve = (100 * timeSinceSunrise / dayLength); bool isDay = (percentOfTwelve / 100) % 2 == 0; return isDay; } function _generateRealImage() private view returns (string memory) { uint time = block.timestamp; uint timeSinceSunrise = time - sunrise; uint percentOfTwelve = (100 * timeSinceSunrise / dayLength); if (!isDayTime()) { return "data:image/svg+xml;utf8,<svg viewBox='0 0 400 400' width='400' height='400' fill='none' xmlns='http://www.w3.org/2000/svg'><path style='fill:#040348' d='M0 0h400v280H0z'/><path style='fill:#1b1e23' d='M0 280h400v120H0z'/><path d='M300 20a30 30 1 0 1 0 60 40 40 1 0 0 0-60z' fill='#fff' style='transform:rotate(-30deg);transform-origin:350px 40px'/></svg>"; } if (percentOfTwelve > 100) { percentOfTwelve = percentOfTwelve % 100; } uint xBase = 400; uint yBase = 280; uint xMov = (xBase * percentOfTwelve) / 100; uint yMov = (120 * yBase * percentOfTwelve) / 10000; if (percentOfTwelve > 50) { yMov = (120 * yBase * (100 - percentOfTwelve)) / 10000; } uint finalX = xMov; uint finalY = yBase - yMov; return string(abi.encodePacked( "data:image/svg+xml;utf8,<svg viewBox='0 0 400 400' width='400' height='400' fill='none' xmlns='http://www.w3.org/2000/svg'><path style='fill:#87cefa' d='M0 0h400v280H0z'/>", "<circle cx='", finalX.toString(), "' cy='", finalY.toString(), "' r='20' style='fill:#e29f05'/>", _getSunLine(finalX, finalY, 0), _getSunLine(finalX, finalY, 45), _getSunLine(finalX, finalY, 90), _getSunLine(finalX, finalY, 135), _getSunLine(finalX, finalY, 180), _getSunLine(finalX, finalY, 225), _getSunLine(finalX, finalY, 270), _getSunLine(finalX, finalY, 315), "<path style='fill:#a82f01' d='M0 280h400v120H0z'/></svg>" )); } function _getSunLine(uint x, uint y, uint rotate) private pure returns (string memory) { return string(abi.encodePacked( "<path stroke='#e29f05' style='transform:rotate(", rotate.toString(), "deg);transform-origin:", x.toString(), "px ", y.toString(), "px' d='M", x.toString(), " ", (y-25).toString(), "V", (y-35).toString(), "' stroke-width='5'/>" )); } function _generateRealMetadata() private view returns (string memory) { return string(abi.encodePacked( _wrapTrait("good", "morning"), ',', _wrapTrait("owner", string(abi.encodePacked("@", twitterGMReceiver))) )); } function setRealDescription(string memory description) public { require(isCurrentOwner(msg.sender), 'Only owner can change description.'); realDescription = description; } function setSunrise(uint sunriseTime) public { require(isCurrentOwner(msg.sender), 'Only owner can change sunrise.'); sunrise = sunriseTime; } function setDayLength(uint dayLengthInput) public { require(isCurrentOwner(msg.sender), 'Only owner can change day length.'); dayLength = dayLengthInput; } function setSayItBackMessage(string memory message) public { require(isCurrentOwner(msg.sender), 'Only owner can change say it back message.'); sayItBackMessage = message; } function sayItBack() public { require(!isCurrentOwner(msg.sender), "You can't say it back to yourself"); emit SayItBack(msg.sender, sayItBackMessage, twitterGMReceiver); } function revealOnOS() public { require(isCurrentOwner(msg.sender), 'Only owner can reveal on OS.'); revealedOnOS = true; } function hideOnOS() public { require(isCurrentOwner(msg.sender), 'Only owner can hide on OS.'); revealedOnOS = false; } } // 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 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 "./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; /** * @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; 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 "../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; 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); }
www.w3.org/2000/svg'><path style='fill:#040348' d='M0 0h400v280H0z'/><path style='fill:#1b1e23' d='M0 280h400v120H0z'/><path d='M300 20a30 30 1 0 1 0 60 40 40 1 0 0 0-60z' fill='#fff' style='transform:rotate(-30deg);transform-origin:350px 40px'/></svg>";
return "data:image/svg+xml;utf8,<svg viewBox='0 0 400 400' width='400' height='400' fill='none' xmlns='http:
10,124,949
[ 1, 4625, 348, 7953, 560, 30, 8765, 18, 91, 23, 18, 3341, 19, 17172, 19, 11451, 11, 4438, 803, 2154, 2218, 5935, 27363, 3028, 4630, 8875, 11, 302, 2218, 49, 20, 374, 76, 16010, 90, 22, 3672, 44, 20, 94, 11, 19, 4438, 803, 2154, 2218, 5935, 27363, 21, 70, 21, 73, 4366, 11, 302, 2218, 49, 20, 576, 3672, 76, 16010, 90, 22343, 44, 20, 94, 11, 19, 4438, 803, 302, 2218, 49, 19249, 4200, 69, 5082, 5196, 404, 374, 404, 374, 4752, 8063, 8063, 404, 374, 374, 374, 17, 4848, 94, 11, 3636, 2218, 7, 25449, 11, 2154, 2218, 6547, 30, 20342, 19236, 5082, 9923, 1769, 6547, 17, 10012, 30, 23, 3361, 4430, 8063, 4430, 11, 19, 4695, 11451, 2984, 31, 203, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 327, 315, 892, 30, 2730, 19, 11451, 15, 2902, 31, 3158, 28, 16, 32, 11451, 1476, 3514, 2218, 20, 374, 7409, 7409, 11, 1835, 2218, 16010, 11, 2072, 2218, 16010, 11, 3636, 2218, 6102, 11, 12302, 2218, 2505, 30, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// contracts/mocks/Rewards.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IMMintableERC20.sol"; contract MasterChef is Ownable { using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CAKEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCakePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCakePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CAKEs to distribute per block. uint256 lastRewardBlock; // Last block number that CAKEs distribution occurs. uint256 accCakePerShare; // Accumulated CAKEs per share, times 1e12. See below. } // The CAKE TOKEN! address public cake; // CAKE tokens created per block. uint256 public cakePerBlock; // Bonus muliplier for early cake makers. uint256 public bonusMultiplier = 1; // 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 CAKE mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor(address _cake) { cake = _cake; cakePerBlock = 400000000000000000; startBlock = block.number; // staking pool poolInfo.push( PoolInfo({lpToken: IERC20(_cake), allocPoint: 1000, lastRewardBlock: startBlock, accCakePerShare: 0}) ); totalAllocPoint = 1000; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { bonusMultiplier = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCakePerShare: 0}) ); updateStakingPool(); } // Update the given pool's CAKE allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; totalAllocPoint = totalAllocPoint - prevAllocPoint + _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 + poolInfo[pid].allocPoint; } if (points != 0) { points = points / 3; totalAllocPoint = totalAllocPoint - poolInfo[0].allocPoint + points; poolInfo[0].allocPoint = points; } } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return (_to - _from) * bonusMultiplier; } // View function to see pending CAKEs on frontend. function pendingCake(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCakePerShare = pool.accCakePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cakeReward = (multiplier * cakePerBlock * pool.allocPoint) / totalAllocPoint; accCakePerShare = accCakePerShare + ((cakeReward * 1e12) / lpSupply); } return (user.amount * accCakePerShare) / 1e12 - user.rewardDebt; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cakeReward = (multiplier * cakePerBlock * pool.allocPoint) / totalAllocPoint; pool.accCakePerShare = pool.accCakePerShare + ((cakeReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for CAKE allocation. function deposit(uint256 _pid, uint256 _amount) public { require(_pid != 0, "deposit CAKE by staking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accCakePerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeCakeTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount + _amount; } user.rewardDebt = (user.amount * pool.accCakePerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { require(_pid != 0, "withdraw CAKE by unstaking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accCakePerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeCakeTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount - _amount; pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = (user.amount * pool.accCakePerShare) / 1e12; emit Withdraw(msg.sender, _pid, _amount); } // Stake CAKE tokens to MasterChef function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accCakePerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeCakeTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount + _amount; } user.rewardDebt = (user.amount * pool.accCakePerShare) / 1e12; emit Deposit(msg.sender, 0, _amount); } // Withdraw CAKE tokens from STAKING. function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = ((user.amount * pool.accCakePerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeCakeTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount - _amount; pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = (user.amount * pool.accCakePerShare) / 1e12; emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // allow admin update, no risk of rug pull function updateCakePerBlock(uint256 _cakePerBlock) public onlyOwner { require(msg.sender == owner(), "Owner-Only Function"); cakePerBlock = _cakePerBlock; } // Safe cake transfer function, just in case if rounding error causes pool to not have enough CAKEs. // MODIFIED TO MINT HERE function safeCakeTransfer(address _to, uint256 _amount) internal { IMMintableERC20(cake).mint(_to, _amount); } }
Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public { require(_pid != 0, "withdraw CAKE by unstaking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accCakePerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeCakeTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount - _amount; pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = (user.amount * pool.accCakePerShare) / 1e12; emit Withdraw(msg.sender, _pid, _amount); }
12,683,992
[ 1, 4625, 348, 7953, 560, 30, 225, 3423, 9446, 511, 52, 2430, 628, 13453, 39, 580, 74, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2583, 24899, 6610, 480, 374, 16, 315, 1918, 9446, 6425, 6859, 635, 640, 334, 6159, 8863, 203, 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, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 2254, 5034, 4634, 273, 14015, 1355, 18, 8949, 380, 2845, 18, 8981, 31089, 2173, 9535, 13, 342, 404, 73, 2138, 13, 300, 729, 18, 266, 2913, 758, 23602, 31, 203, 3639, 309, 261, 9561, 405, 374, 13, 288, 203, 5411, 4183, 31089, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 3639, 289, 203, 3639, 309, 261, 67, 8949, 405, 374, 13, 288, 203, 5411, 729, 18, 8949, 273, 729, 18, 8949, 300, 389, 8949, 31, 203, 5411, 2845, 18, 9953, 1345, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 3639, 289, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 261, 1355, 18, 8949, 380, 2845, 18, 8981, 31089, 2173, 9535, 13, 342, 404, 73, 2138, 31, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 389, 6610, 16, 389, 8949, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract BearIsland is ERC721, ERC721Enumerable, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; string public baseURI; constructor(string memory baseURI_) ERC721("Bear Island", "BEAR") { baseURI = baseURI_; } /// Return the base URI for a token. function _baseURI() internal view override returns (string memory) { return baseURI; } /// Update the base URI for tokens. /// @param baseURI_ the new base URI function setURI(string memory baseURI_) external onlyOwner { baseURI = baseURI_; } /// Mint a token. /// @param to address to mint the token to function safeMint(address to) public onlyOwner { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); } // The following functions are overrides required by Solidity. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
Update the base URI for tokens. @param baseURI_ the new base URI
function setURI(string memory baseURI_) external onlyOwner { baseURI = baseURI_; }
12,634,574
[ 1, 4625, 348, 7953, 560, 30, 225, 2315, 326, 1026, 3699, 364, 2430, 18, 632, 891, 1026, 3098, 67, 326, 394, 1026, 3699, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 3098, 12, 1080, 3778, 1026, 3098, 67, 13, 3903, 1338, 5541, 288, 203, 3639, 1026, 3098, 273, 1026, 3098, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xF88038430085726183702b36a7D163a81528F7f1/sources/SwanStake.sol
@dev emitted whenever user's staked tokens are successfully unstaked and trasnferred back to the user
event ClaimedInterestTokens(address indexed _user,uint256 _amount);
5,069,533
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 17826, 17334, 729, 1807, 384, 9477, 2430, 854, 4985, 640, 334, 9477, 471, 433, 31432, 4193, 1473, 358, 326, 729, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 871, 18381, 329, 29281, 5157, 12, 2867, 8808, 389, 1355, 16, 11890, 5034, 389, 8949, 1769, 21281, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x99e0439920A80006d2b5A258e30Df66e22467C6D/sources/BOMBHEAD.sol
any tokens sent here ?modifiers
contract BOMBHEAD is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "BOMBHEAD token"; string constant tokenSymbol = "BOMBHEAD"; uint8 constant tokenDecimals = 18; uint256 constant eighteen = 1000000000000000000; uint256 _totalSupply = 9000 * eighteen; IERC20 currentToken ; address payable public _owner; modifier onlyOwner() { require(msg.sender == _owner); _; } constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _owner = msg.sender; require(_totalSupply != 0); _balances[_owner] = _balances[_owner].add(_totalSupply); emit Transfer(address(0), _owner, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } function _executeTransfer(address _from, address _to, uint256 _value) private { if (_value <= 0) revert(); } function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**uint256(tokenDecimals); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**uint256(tokenDecimals); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function withdrawUnclaimedTokens(address contractUnclaimed) external onlyOwner { currentToken = IERC20(contractUnclaimed); uint256 amount = currentToken.balanceOf(address(this)); currentToken.transfer(_owner, amount); } }
3,591,994
[ 1, 4625, 348, 7953, 560, 30, 1281, 2430, 3271, 2674, 692, 15432, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 25408, 38, 12458, 353, 4232, 39, 3462, 40, 6372, 288, 203, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 377, 203, 203, 21281, 225, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 8151, 31, 203, 225, 533, 5381, 1147, 461, 273, 315, 38, 1872, 38, 12458, 1147, 14432, 203, 225, 533, 5381, 1147, 5335, 273, 315, 38, 1872, 38, 12458, 14432, 203, 225, 2254, 28, 225, 5381, 1147, 31809, 273, 6549, 31, 203, 225, 2254, 5034, 5381, 425, 750, 73, 275, 273, 2130, 12648, 12648, 31, 203, 225, 2254, 5034, 389, 4963, 3088, 1283, 273, 2468, 3784, 380, 425, 750, 73, 275, 31, 203, 21281, 225, 467, 654, 39, 3462, 23719, 274, 203, 565, 1758, 8843, 429, 1071, 389, 8443, 31, 203, 377, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 1377, 2583, 12, 3576, 18, 15330, 422, 389, 8443, 1769, 203, 1377, 389, 31, 203, 225, 289, 203, 21281, 21281, 377, 203, 21281, 203, 225, 3885, 1435, 1071, 8843, 429, 4232, 39, 3462, 40, 6372, 12, 2316, 461, 16, 1147, 5335, 16, 1147, 31809, 13, 288, 203, 4202, 203, 565, 389, 8443, 273, 1234, 18, 15330, 31, 203, 565, 2583, 24899, 4963, 3088, 1283, 480, 374, 1769, 203, 565, 389, 70, 26488, 63, 67, 8443, 65, 273, 389, 70, 26488, 63, 67, 8443, 8009, 1289, 24899, 4963, 3088, 1283, 1769, 203, 565, 3626, 12279, 12, 2867, 12, 20, 3631, 389, 8443, 16, 389, 4963, 3088, 1283, 1769, 203, 377, 203, 225, 289, 203, 203, 225, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 4963, 3088, 1283, 31, 203, 225, 289, 203, 203, 225, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 70, 26488, 63, 8443, 15533, 203, 225, 289, 203, 203, 225, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 8151, 63, 8443, 6362, 87, 1302, 264, 15533, 203, 225, 289, 203, 203, 203, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 13, 7010, 565, 288, 203, 3639, 389, 8837, 5912, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 565, 445, 3309, 5912, 12, 2867, 8526, 3778, 22686, 16, 2254, 5034, 8526, 3778, 924, 13, 1071, 203, 565, 288, 203, 3639, 2583, 12, 8606, 6760, 18, 2469, 422, 924, 18, 2469, 1769, 203, 3639, 364, 12, 11890, 5034, 277, 273, 374, 31, 277, 411, 22686, 18, 2469, 31, 277, 27245, 203, 5411, 389, 8837, 5912, 12, 3576, 18, 15330, 16, 22686, 63, 77, 6487, 924, 63, 77, 19226, 203, 565, 289, 203, 377, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 13, 7010, 565, 288, 203, 3639, 2583, 12, 1132, 1648, 389, 8151, 63, 2080, 6362, 3576, 18, 15330, 19226, 203, 3639, 389, 8151, 63, 2080, 6362, 3576, 18, 15330, 65, 273, 389, 8151, 63, 2080, 6362, 3576, 18, 15330, 8009, 1717, 12, 1132, 1769, 203, 3639, 389, 8837, 5912, 12, 2080, 16, 358, 16, 460, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 27699, 203, 203, 203, 203, 565, 445, 389, 8837, 5912, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 3238, 203, 565, 288, 203, 3639, 309, 261, 67, 1132, 1648, 374, 13, 15226, 5621, 7010, 540, 203, 540, 203, 203, 565, 289, 21281, 203, 203, 203, 203, 203, 203, 21281, 21281, 21281, 225, 445, 3309, 5912, 5812, 6275, 12, 2867, 8526, 3778, 22686, 16, 2254, 5034, 3844, 13, 1071, 288, 203, 565, 2254, 5034, 3844, 1190, 31809, 273, 3844, 380, 1728, 636, 11890, 5034, 12, 2316, 31809, 1769, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 22686, 18, 2469, 31, 277, 27245, 288, 203, 1377, 7412, 12, 8606, 6760, 63, 77, 6487, 3844, 1190, 31809, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 203, 225, 445, 3309, 5912, 5812, 6275, 12, 2867, 8526, 3778, 22686, 16, 2254, 5034, 3844, 13, 1071, 288, 203, 565, 2254, 5034, 3844, 1190, 31809, 273, 3844, 380, 1728, 636, 11890, 5034, 12, 2316, 31809, 1769, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 22686, 18, 2469, 31, 277, 27245, 288, 203, 1377, 7412, 12, 8606, 6760, 63, 77, 6487, 3844, 1190, 31809, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 203, 225, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2583, 12, 87, 1302, 264, 480, 1758, 12, 20, 10019, 203, 565, 389, 8151, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 460, 31, 203, 565, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 460, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 21281, 21281, 225, 445, 10929, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 3096, 620, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2583, 12, 87, 1302, 264, 480, 1758, 12, 20, 10019, 203, 565, 389, 8151, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 261, 67, 8151, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 8009, 1289, 12, 9665, 620, 10019, 203, 565, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 389, 8151, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 19226, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 225, 445, 20467, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2583, 12, 87, 1302, 264, 480, 1758, 12, 20, 10019, 203, 565, 389, 8151, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 261, 67, 8151, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 8009, 1717, 12, 1717, 1575, 329, 620, 10019, 203, 565, 3626, 1716, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-01-01 */ // SPDX-License-Identifier: MIT // GO TO LINE 1904 TO SEE WHERE THE ALPHA CONTRACT STARTS // 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/introspection/IERC165.sol 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); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @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; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @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); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @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); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <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); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol 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; } } // File: @openzeppelin/contracts/utils/Address.sol 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); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <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; // 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]; } // 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); } // 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)))); } // 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)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 _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)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @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 || ERC721.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 _tokenOwners.contains(tokenId); } /** * @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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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"); // internal 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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, 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), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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 { } } // 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; } } // ************************************************ // ************************************************ // ************************************************ // ************************************************ pragma solidity ^0.7.0; pragma abicoder v2; contract Alphas is ERC721, Ownable { using SafeMath for uint256; string public ALPHA_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN ALPHA ARE ALL SOLD OUT string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE uint256 public constant alphaPrice = 30000000000000000; // 0.03 ETH uint public constant maxAlphaPurchase = 10; uint256 public constant MAX_ALPHA = 2500; bool public saleIsActive = true; mapping(uint => string) public alphaNames; // Reserve 1 alpha for team - Giveaways/Prizes etc uint public alphaReserve = 1; event alphaNameChange(address _by, uint _tokenId, string _name); event licenseisLocked(string _licenseText); constructor() ERC721("Alphas", "Alpha") { } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function reserveAlpha(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= alphaReserve, "Not enough reserve left for team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } alphaReserve = alphaReserve.sub(_reserveAmount); } function setProvenanceHash(string memory provenanceHash) public onlyOwner { ALPHA_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } // Returns the license for tokens function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "CHOOSE A ALPHA WITHIN RANGE"); return LICENSE_TEXT; } // Locks the license to prevent further changes function lockLicense() public onlyOwner { licenseLocked = true; emit licenseisLocked(LICENSE_TEXT); } // Change the license function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "License already locked"); LICENSE_TEXT = _license; } function mintAlphas(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Alpha"); require(numberOfTokens > 0 && numberOfTokens <= maxAlphaPurchase, "Can only mint 10 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_ALPHA, "Purchase would exceed max supply of Alpha"); require(msg.value >= alphaPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_ALPHA) { _safeMint(msg.sender, mintIndex); } } } function changeAlphaName(uint _tokenId, string memory _name) public { require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this alpha!"); require(sha256(bytes(_name)) != sha256(bytes(alphaNames[_tokenId])), "New name is same as the current one"); alphaNames[_tokenId] = _name; emit alphaNameChange(msg.sender, _tokenId, _name); } function viewAlphaName(uint _tokenId) public view returns( string memory ){ require( _tokenId < totalSupply(), "Choose a alpha within range" ); return alphaNames[_tokenId]; } // GET ALL ALPHA OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH function alphaNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new string[](0); } else { string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = alphaNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } } }
Reserve 1 alpha for team - Giveaways/Prizes etc
contract Alphas is ERC721, Ownable { using SafeMath for uint256; uint public constant maxAlphaPurchase = 10; uint256 public constant MAX_ALPHA = 2500; bool public saleIsActive = true; mapping(uint => string) public alphaNames; uint public alphaReserve = 1; event alphaNameChange(address _by, uint _tokenId, string _name); event licenseisLocked(string _licenseText); pragma solidity ^0.7.0; constructor() ERC721("Alphas", "Alpha") { } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function reserveAlpha(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= alphaReserve, "Not enough reserve left for team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } alphaReserve = alphaReserve.sub(_reserveAmount); } function reserveAlpha(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= alphaReserve, "Not enough reserve left for team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } alphaReserve = alphaReserve.sub(_reserveAmount); } function setProvenanceHash(string memory provenanceHash) public onlyOwner { ALPHA_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } } else { function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "CHOOSE A ALPHA WITHIN RANGE"); return LICENSE_TEXT; } function lockLicense() public onlyOwner { licenseLocked = true; emit licenseisLocked(LICENSE_TEXT); } function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "License already locked"); LICENSE_TEXT = _license; } function mintAlphas(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Alpha"); require(numberOfTokens > 0 && numberOfTokens <= maxAlphaPurchase, "Can only mint 10 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_ALPHA, "Purchase would exceed max supply of Alpha"); require(msg.value >= alphaPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_ALPHA) { _safeMint(msg.sender, mintIndex); } } } function mintAlphas(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Alpha"); require(numberOfTokens > 0 && numberOfTokens <= maxAlphaPurchase, "Can only mint 10 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_ALPHA, "Purchase would exceed max supply of Alpha"); require(msg.value >= alphaPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_ALPHA) { _safeMint(msg.sender, mintIndex); } } } function mintAlphas(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Alpha"); require(numberOfTokens > 0 && numberOfTokens <= maxAlphaPurchase, "Can only mint 10 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_ALPHA, "Purchase would exceed max supply of Alpha"); require(msg.value >= alphaPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_ALPHA) { _safeMint(msg.sender, mintIndex); } } } function changeAlphaName(uint _tokenId, string memory _name) public { require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this alpha!"); require(sha256(bytes(_name)) != sha256(bytes(alphaNames[_tokenId])), "New name is same as the current one"); alphaNames[_tokenId] = _name; emit alphaNameChange(msg.sender, _tokenId, _name); } function viewAlphaName(uint _tokenId) public view returns( string memory ){ require( _tokenId < totalSupply(), "Choose a alpha within range" ); return alphaNames[_tokenId]; } function alphaNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = alphaNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } } function alphaNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = alphaNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } } } else { function alphaNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = alphaNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } } }
14,609,268
[ 1, 4625, 348, 7953, 560, 30, 225, 1124, 6527, 404, 4190, 364, 5927, 300, 22374, 69, 3052, 19, 2050, 3128, 5527, 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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728, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 26313, 273, 6969, 713, 31, 203, 203, 565, 1426, 1071, 272, 5349, 2520, 3896, 273, 638, 31, 203, 377, 203, 565, 2874, 12, 11890, 516, 533, 13, 1071, 4190, 1557, 31, 203, 377, 203, 565, 2254, 1071, 4190, 607, 6527, 273, 404, 31, 203, 377, 203, 565, 871, 4190, 461, 3043, 12, 2867, 389, 1637, 16, 2254, 389, 2316, 548, 16, 533, 389, 529, 1769, 203, 377, 203, 565, 871, 8630, 291, 8966, 12, 1080, 389, 12687, 1528, 1769, 203, 203, 377, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 31, 203, 565, 3885, 1435, 4232, 39, 27, 5340, 2932, 1067, 26377, 3113, 315, 9690, 7923, 288, 289, 203, 565, 445, 598, 9446, 1435, 1071, 1338, 5541, 288, 203, 3639, 2254, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 12296, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 20501, 9690, 12, 2867, 389, 869, 16, 2254, 5034, 389, 455, 6527, 6275, 13, 1071, 1338, 5541, 288, 540, 203, 3639, 2254, 14467, 273, 2078, 3088, 1283, 5621, 203, 3639, 2583, 24899, 455, 6527, 6275, 405, 374, 597, 389, 455, 6527, 6275, 1648, 4190, 607, 6527, 16, 315, 1248, 7304, 20501, 2002, 364, 5927, 8863, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 455, 6527, 6275, 31, 277, 27245, 288, 203, 5411, 389, 4626, 49, 474, 24899, 869, 16, 14467, 397, 277, 1769, 203, 3639, 289, 203, 3639, 4190, 607, 6527, 273, 4190, 607, 6527, 18, 1717, 24899, 455, 6527, 6275, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 20501, 9690, 12, 2867, 389, 869, 16, 2254, 5034, 389, 455, 6527, 6275, 13, 1071, 1338, 5541, 288, 540, 203, 3639, 2254, 14467, 273, 2078, 3088, 1283, 5621, 203, 3639, 2583, 24899, 455, 6527, 6275, 405, 374, 597, 389, 455, 6527, 6275, 1648, 4190, 607, 6527, 16, 315, 1248, 7304, 20501, 2002, 364, 5927, 8863, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 455, 6527, 6275, 31, 277, 27245, 288, 203, 5411, 389, 4626, 49, 474, 24899, 869, 16, 14467, 397, 277, 1769, 203, 3639, 289, 203, 3639, 4190, 607, 6527, 273, 4190, 607, 6527, 18, 1717, 24899, 455, 6527, 6275, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 444, 626, 15856, 2310, 12, 1080, 3778, 24185, 2310, 13, 1071, 1338, 5541, 288, 203, 3639, 29432, 37, 67, 3373, 58, 1157, 4722, 273, 24185, 2310, 31, 203, 565, 289, 203, 203, 565, 445, 26435, 3098, 12, 1080, 3778, 1026, 3098, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 542, 2171, 3098, 12, 1969, 3098, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 9668, 30746, 1119, 1435, 1071, 1338, 5541, 288, 203, 3639, 272, 5349, 2520, 3896, 273, 401, 87, 5349, 2520, 3896, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 445, 2430, 951, 5541, 12, 2867, 389, 8443, 13, 3903, 1476, 1135, 12, 11890, 5034, 8526, 3778, 262, 288, 203, 3639, 2254, 5034, 1147, 1380, 273, 11013, 951, 24899, 8443, 1769, 203, 3639, 309, 261, 2316, 1380, 422, 374, 13, 288, 203, 5411, 327, 394, 2254, 5034, 8526, 12, 20, 1769, 203, 5411, 2254, 5034, 8526, 3778, 563, 273, 394, 2254, 5034, 8526, 12, 2316, 1380, 1769, 203, 5411, 2254, 5034, 770, 31, 203, 5411, 364, 261, 1615, 273, 374, 31, 770, 411, 1147, 1380, 31, 770, 27245, 288, 203, 7734, 563, 63, 1615, 65, 273, 1147, 951, 5541, 21268, 24899, 8443, 16, 770, 1769, 203, 5411, 289, 203, 5411, 327, 563, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 565, 445, 2430, 951, 5541, 12, 2867, 389, 8443, 13, 3903, 1476, 1135, 12, 11890, 5034, 8526, 3778, 262, 288, 203, 3639, 2254, 5034, 1147, 1380, 273, 11013, 951, 24899, 8443, 1769, 203, 3639, 309, 261, 2316, 1380, 422, 374, 13, 288, 203, 5411, 327, 394, 2254, 5034, 8526, 12, 20, 1769, 203, 5411, 2254, 5034, 8526, 3778, 563, 273, 394, 2254, 5034, 8526, 12, 2316, 1380, 1769, 203, 5411, 2254, 5034, 770, 31, 203, 5411, 364, 261, 1615, 273, 374, 31, 770, 411, 1147, 1380, 31, 770, 27245, 288, 203, 7734, 563, 63, 1615, 65, 273, 1147, 951, 5541, 21268, 24899, 8443, 16, 770, 1769, 203, 5411, 289, 203, 5411, 327, 563, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 3639, 289, 469, 288, 203, 565, 445, 2430, 951, 5541, 12, 2867, 389, 8443, 13, 3903, 1476, 1135, 12, 11890, 5034, 8526, 3778, 262, 288, 203, 3639, 2254, 5034, 1147, 1380, 273, 11013, 951, 24899, 8443, 1769, 203, 3639, 309, 261, 2316, 1380, 422, 374, 13, 288, 203, 5411, 327, 394, 2254, 5034, 8526, 12, 20, 1769, 203, 5411, 2254, 5034, 8526, 3778, 563, 273, 394, 2254, 5034, 8526, 12, 2316, 1380, 1769, 203, 5411, 2254, 5034, 770, 31, 203, 5411, 364, 261, 1615, 273, 374, 31, 770, 411, 1147, 1380, 31, 770, 27245, 288, 203, 7734, 563, 63, 1615, 65, 273, 1147, 951, 5541, 21268, 24899, 8443, 16, 770, 1769, 203, 5411, 289, 203, 5411, 327, 563, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 565, 445, 1147, 13211, 12, 11890, 389, 350, 13, 1071, 1476, 1135, 12, 1080, 3778, 13, 288, 203, 3639, 2583, 24899, 350, 411, 2078, 3088, 1283, 9334, 315, 22213, 51, 1090, 432, 29432, 37, 13601, 706, 534, 8357, 8863, 203, 3639, 327, 511, 2871, 23396, 67, 5151, 31, 203, 565, 289, 203, 377, 203, 565, 445, 2176, 13211, 1435, 1071, 1338, 5541, 288, 203, 3639, 8630, 8966, 273, 225, 638, 31, 203, 3639, 3626, 8630, 291, 8966, 12, 6065, 23396, 67, 5151, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 2549, 13211, 12, 1080, 3778, 389, 12687, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 12687, 8966, 422, 629, 16, 315, 13211, 1818, 8586, 8863, 203, 3639, 511, 2871, 23396, 67, 5151, 273, 389, 12687, 2 ]
./full_match/80001/0x7a8a4df3279720526275Dc27f027f228966C7B49/sources/contracts/LensRoles.sol
@dev Grant a role to a user as per the total followers receiver by Phat Contract @param caller The address of the user being granted the role @param totalFollowers Total followers of a Lens Profile returned by the Phat Contract
function grantRole(address caller, uint256 totalFollowers) internal { for (uint i = 0; i < totalRoles; i++) { if ( Roles[i].thresholdLower >= totalFollowers && Roles[i - 1].thresholdUpper < totalFollowers ) { _grantRole(Roles[i].Role, caller); break; } } }
9,442,630
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 19689, 279, 2478, 358, 279, 729, 487, 1534, 326, 2078, 2805, 414, 5971, 635, 4360, 270, 13456, 632, 891, 4894, 1021, 1758, 434, 326, 729, 3832, 17578, 326, 2478, 632, 891, 2078, 8328, 414, 10710, 2805, 414, 434, 279, 511, 773, 11357, 2106, 635, 326, 4360, 270, 13456, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7936, 2996, 12, 2867, 4894, 16, 2254, 5034, 2078, 8328, 414, 13, 2713, 288, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 2078, 6898, 31, 277, 27245, 288, 203, 5411, 309, 261, 203, 7734, 19576, 63, 77, 8009, 8699, 4070, 1545, 2078, 8328, 414, 597, 203, 7734, 19576, 63, 77, 300, 404, 8009, 8699, 5988, 411, 2078, 8328, 414, 203, 5411, 262, 288, 203, 7734, 389, 16243, 2996, 12, 6898, 63, 77, 8009, 2996, 16, 4894, 1769, 203, 7734, 898, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * 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 TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param rateP Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param walletP Address where collected funds will be forwarded to * @param tokenP Address of the token being sold */ constructor (uint256 rateP, address payable walletP, IERC20 tokenP) { require(rateP > 0, "Crowdsale: rate is 0"); require(walletP != address(0), "Crowdsale: wallet is the zero address"); require(address(tokenP) != address(0), "Crowdsale: token is the zero address"); _rate = rateP; _wallet = walletP; _token = tokenP; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ receive () external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal virtual { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal virtual { _wallet.transfer(msg.value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "./Crowdsale.sol"; contract SuckTokenSale is Crowdsale { constructor( uint256 rate, // rate in TKNbits address payable wallet, IERC20 token ) Crowdsale(rate, wallet, token) { } function getCrowdSaleBalance() public view returns (uint256) { require(msg.sender == wallet(), "Only owner can see the balance"); return token().balanceOf(address(this)); } } // SPDX-License-Identifier: MIT 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 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; } } // 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' // 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) + 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 // 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.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.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) { 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.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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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; } } }
* @title Crowdsale @dev Crowdsale is a base contract for managing a token crowdsale, allowing investors to purchase tokens with ether. This contract implements such functionality in its most fundamental form and can be extended to provide additional functionality and/or custom behavior. The external interface represents the basic interface for purchasing tokens, and conforms the base architecture for crowdsales. It is not intended to be modified / overridden. The internal interface conforms the extensible and modifiable surface of crowdsales. Override the methods to add functionality. Consider using 'super' where appropriate to concatenate behavior./ The token being sold Address where funds are collected How many token units a buyer gets per wei. The rate is the conversion between wei and the smallest and indivisible token unit. So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK 1 wei will give you 1 unit, or 0.001 TOK. Amount of wei raised
contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 private _token; address payable private _wallet; uint256 private _rate; uint256 private _weiRaised; event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); constructor (uint256 rateP, address payable walletP, IERC20 tokenP) { require(rateP > 0, "Crowdsale: rate is 0"); require(walletP != address(0), "Crowdsale: wallet is the zero address"); require(address(tokenP) != address(0), "Crowdsale: token is the zero address"); _rate = rateP; _wallet = walletP; _token = tokenP; } receive () external payable { buyTokens(_msgSender()); } function token() public view returns (IERC20) { return _token; } function wallet() public view returns (address payable) { return _wallet; } function rate() public view returns (uint256) { return _rate; } function weiRaised() public view returns (uint256) { return _weiRaised; } function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); } function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual { } function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual { _token.safeTransfer(beneficiary, tokenAmount); } function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual { _deliverTokens(beneficiary, tokenAmount); } function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal virtual { } function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } function _forwardFunds() internal virtual { _wallet.transfer(msg.value); } }
12,071,414
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2649, 385, 492, 2377, 5349, 632, 5206, 385, 492, 2377, 5349, 353, 279, 1026, 6835, 364, 30632, 279, 1147, 276, 492, 2377, 5349, 16, 15632, 2198, 395, 1383, 358, 23701, 2430, 598, 225, 2437, 18, 1220, 6835, 4792, 4123, 14176, 316, 2097, 4486, 284, 1074, 14773, 287, 646, 471, 848, 506, 7021, 358, 5615, 3312, 14176, 471, 19, 280, 1679, 6885, 18, 1021, 3903, 1560, 8686, 326, 5337, 1560, 364, 5405, 343, 11730, 2430, 16, 471, 356, 9741, 326, 1026, 27418, 364, 276, 492, 2377, 5408, 18, 2597, 353, 486, 12613, 358, 506, 4358, 342, 11000, 18, 1021, 2713, 1560, 356, 9741, 326, 1110, 773, 1523, 471, 681, 8424, 9034, 434, 276, 492, 2377, 5408, 18, 1439, 326, 2590, 358, 527, 14176, 18, 23047, 1450, 296, 9565, 11, 1625, 5505, 358, 11361, 6885, 18, 19, 1021, 1147, 3832, 272, 1673, 5267, 1625, 284, 19156, 854, 12230, 9017, 4906, 1147, 4971, 279, 27037, 5571, 1534, 732, 77, 18, 1021, 4993, 353, 326, 4105, 3086, 732, 77, 471, 326, 13541, 471, 6335, 18932, 1147, 2836, 18, 6155, 16, 309, 1846, 854, 1450, 279, 4993, 434, 404, 598, 279, 4232, 39, 3462, 40, 6372, 1147, 598, 890, 15105, 2566, 399, 3141, 404, 732, 77, 903, 8492, 1846, 404, 2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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 492, 2377, 5349, 353, 1772, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 654, 39, 3462, 3238, 389, 2316, 31, 203, 203, 565, 1758, 8843, 429, 3238, 389, 19177, 31, 203, 203, 565, 2254, 5034, 3238, 389, 5141, 31, 203, 203, 565, 2254, 5034, 3238, 389, 1814, 77, 12649, 5918, 31, 203, 203, 565, 871, 13899, 10262, 343, 8905, 12, 2867, 8808, 5405, 343, 14558, 16, 1758, 8808, 27641, 74, 14463, 814, 16, 2254, 5034, 460, 16, 2254, 5034, 3844, 1769, 203, 203, 203, 565, 3885, 261, 11890, 5034, 4993, 52, 16, 1758, 8843, 429, 9230, 52, 16, 467, 654, 39, 3462, 1147, 52, 13, 288, 203, 3639, 2583, 12, 5141, 52, 405, 374, 16, 315, 39, 492, 2377, 5349, 30, 4993, 353, 374, 8863, 203, 3639, 2583, 12, 19177, 52, 480, 1758, 12, 20, 3631, 315, 39, 492, 2377, 5349, 30, 9230, 353, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 2867, 12, 2316, 52, 13, 480, 1758, 12, 20, 3631, 315, 39, 492, 2377, 5349, 30, 1147, 353, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 5141, 273, 4993, 52, 31, 203, 3639, 389, 19177, 273, 9230, 52, 31, 203, 3639, 389, 2316, 273, 1147, 52, 31, 203, 565, 289, 203, 203, 565, 6798, 1832, 3903, 8843, 429, 288, 203, 3639, 30143, 5157, 24899, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 445, 1147, 1435, 1071, 1476, 1135, 261, 45, 654, 39, 3462, 13, 288, 203, 3639, 327, 389, 2316, 31, 203, 565, 289, 203, 203, 565, 445, 9230, 1435, 1071, 1476, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 389, 19177, 31, 203, 565, 289, 203, 203, 565, 445, 4993, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 5141, 31, 203, 565, 289, 203, 203, 565, 445, 732, 77, 12649, 5918, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 1814, 77, 12649, 5918, 31, 203, 565, 289, 203, 203, 565, 445, 30143, 5157, 12, 2867, 27641, 74, 14463, 814, 13, 1071, 1661, 426, 8230, 970, 8843, 429, 288, 203, 3639, 2254, 5034, 732, 77, 6275, 273, 1234, 18, 1132, 31, 203, 3639, 389, 1484, 4270, 23164, 12, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 1769, 203, 203, 3639, 2254, 5034, 2430, 273, 389, 588, 1345, 6275, 12, 1814, 77, 6275, 1769, 203, 203, 3639, 389, 1814, 77, 12649, 5918, 273, 389, 1814, 77, 12649, 5918, 18, 1289, 12, 1814, 77, 6275, 1769, 203, 203, 3639, 389, 2567, 23164, 12, 70, 4009, 74, 14463, 814, 16, 2430, 1769, 203, 3639, 3626, 13899, 10262, 343, 8905, 24899, 3576, 12021, 9334, 27641, 74, 14463, 814, 16, 732, 77, 6275, 16, 2430, 1769, 203, 203, 3639, 389, 2725, 10262, 343, 11730, 1119, 12, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 1769, 203, 203, 3639, 389, 11565, 42, 19156, 5621, 203, 3639, 389, 2767, 4270, 23164, 12, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 1484, 4270, 23164, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 732, 77, 6275, 13, 2713, 1476, 5024, 288, 203, 3639, 2583, 12, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 3631, 315, 39, 492, 2377, 5349, 30, 27641, 74, 14463, 814, 353, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 1814, 77, 6275, 480, 374, 16, 315, 39, 492, 2377, 5349, 30, 732, 77, 6275, 353, 374, 8863, 203, 565, 289, 203, 203, 565, 445, 389, 2767, 4270, 23164, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 732, 77, 6275, 13, 2713, 1476, 5024, 288, 203, 565, 289, 203, 203, 565, 445, 389, 26672, 5157, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 1147, 6275, 13, 2713, 5024, 288, 203, 3639, 389, 2316, 18, 4626, 5912, 12, 70, 4009, 74, 14463, 814, 16, 1147, 6275, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 2567, 23164, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 1147, 6275, 13, 2713, 5024, 288, 203, 3639, 389, 26672, 5157, 12, 70, 4009, 74, 14463, 814, 16, 1147, 6275, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 2725, 10262, 343, 11730, 1119, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 732, 77, 6275, 13, 2713, 5024, 288, 203, 565, 289, 203, 203, 565, 445, 389, 588, 1345, 6275, 12, 11890, 5034, 732, 77, 6275, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 732, 77, 6275, 18, 16411, 24899, 5141, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 11565, 42, 19156, 1435, 2713, 5024, 288, 203, 3639, 389, 19177, 18, 13866, 12, 3576, 18, 1132, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 {SafeMath} from "./SafeMath.sol"; import {ERC20Token} from "./Token.sol"; import {Project} from "./Project.sol"; contract Intermediary { using SafeMath for uint; // List of projects Project[] projects; // Currency token ERC20Token currency_; // Intermediary's address address intermediary_; // Intermediary's name string name_; // Modificators modifier onlyBy(address _account) { require( msg.sender == _account, "Sender not authorized. Intermediary." ); // Do not forget the "_;"! It will // be replaced by the actual function // body when the modifier is used. _; } // Methods constructor(string memory name) public { name_ = name; intermediary_ = msg.sender; } // Public functions // Set currency function setCurrency(ERC20Token currency) public onlyBy(intermediary_) returns(bool success) { currency_ = currency; return true; } // Set project price function setProjectPrice(string memory projectName, uint projectPrice) public onlyBy(intermediary_) returns(bool success) { (uint id, bool err) = findProjectIdByName(projectName); if(err) return false; setProjectPrice(projects[id], projectPrice); return true; } // Register new Project function registerNewProject(Project project) public onlyBy(intermediary_) returns(bool success) { (uint id, bool err) = findProjectIdByName(project.getName()); if(!err) return false; projects.push(project); return true; } // By project token - avaliable only for intermediary function buyProjectTokenInter(string memory projectName, uint amount) public onlyBy(intermediary_) returns(bool success) { (uint id, bool err) = findProjectIdByName(projectName); if(err) return false; Project project = projects[id]; if(project.buyToken(amount)) { return true; } return false; } // Sell project token - avaliable only for intermediary function sellProjectTokenInter(string memory projectName, uint amount) public onlyBy(intermediary_) returns(bool success) { (uint id, bool err) = findProjectIdByName(projectName); if(err) return false; Project project = projects[id]; require(project.balanceOf(intermediary_) < amount, "You have not enogh project token."); if(project.sellToken(amount)) { return true; } return false; } // Buy project token function buyProjectToken(string memory projectName, uint amount) public onlyBy(intermediary_) returns(bool success) { return false; } // Sell project token function sellProjectToken(string memory projectName, uint amount) public onlyBy(intermediary_) returns(bool success) { return false; } // Set a new price for project function setProjectPrice(Project project, uint projectPrice) public onlyBy(intermediary_) returns(bool success) { project.setPrice(projectPrice); return true; } // Get intermediary address function getIntermediary() public view returns(address) { return intermediary_; } // Get name of the intermediary function getName() public view returns(string memory){ return name_; } // Get balance for project function getBalanceForProject(string memory projectName) public onlyBy(intermediary_) view returns(uint balance) { (uint id, bool err) = findProjectIdByName(projectName); if(err) return 0; Project project = projects[id]; return project.balanceOf(intermediary_); } // Get balance for currency function getBalanceForCurrency() public view onlyBy(intermediary_) returns(uint balance) { return currency_.balanceOf(intermediary_); } // Internal functions // Checking String for equation function equalStrings(string memory firstStr, string memory secondStr) internal pure returns(bool success) { bytes memory first = bytes(firstStr); bytes memory second = bytes(secondStr); if(first.length != second.length) return false; for(uint i = 0; i < first.length; i++) { if(first[i] != second[i]) return false; } return true; } // Find project position in a list by its name function findProjectIdByName(string memory projectName) internal view returns(uint, bool success) { for(uint i = 0; i < projects.length; i++) { if(equalStrings(projects[i].getName(), projectName)) { return (i, false); } } return (projects.length, true); } }
Do not forget the "_;"! It will be replaced by the actual function body when the modifier is used.
{ require( msg.sender == _account, "Sender not authorized. Intermediary." ); _; }
5,541,387
[ 1, 4625, 348, 7953, 560, 30, 225, 2256, 486, 13776, 326, 4192, 4868, 5, 2597, 903, 506, 8089, 635, 326, 3214, 445, 1417, 1347, 326, 9606, 353, 1399, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 389, 4631, 16, 203, 5411, 315, 12021, 486, 10799, 18, 5294, 5660, 814, 1199, 203, 3639, 11272, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 /** ░░░░░░░░▒░░░░░░░░░░░░░░░░▒▒▒▒▒░░░░░░░░░░▒░░░░░░░░░ ░░░░░░▒▓███░░░░░░░░▒▒▒▒▒░░▒▒███░░░░░░░▓▒██░░░░░░░░ ░░░░▓█░░░▓█▒░░░░▒▓▒░░░░░░░░░░██░░░░░░██▒░██░░░░░░░ ░░░░▒██░░▒▒░░░░▓█░░░░░░░░░░░░██▓░░░░░▓█▓░▒█▒░░░░░░ ░░░░░▒██░░░░░░██░░░░░░░░░░░░▒░██▒░░░░▓█▓▒▒░░░░░░░░ ░░░░░░▓██░░░░▓█▒░░░░░░░░░░░░▒░▒██░░░░▓██▓▓░░░░░░░░ ░░░░░░░▓██░░░██░░░░░░░░░░░░▓░░░██▒░░░▓█▓▒██░░░░░░░ ░░░░░░░░██▓░░██▒░░░░░░░░░░▒░░░░▒██░░░▓█▓░▓██░░░░░░ ░░░░░░░░░██▓░▓██░░░░░░░░░▒▒░░░░░██▒░░▓█▓░░▓██░░░░░ ░░░░░░░░░░██▒░██▓░░░░▓███████▒░░▒██░░▓█▓░░░█▓░░░░░ ░░░░▒█▒░░░░█▓░░▓█▓░░░░░░░░░░░░░░░▓█▒░▓█▓░░▒░░░░░░░ ░░░░▓██░░░▒░░░░░▒██▒░░░░░░░░░░░▓░░░░░▓██▒░░░░░░░░░ ░░░░░▓██▓░░░░░░░░░░▒▓▓▓▒▒░░▒▒▓▓▒░░░░░▓▓░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ CTHDRL x Scott Campbell Contract: Scab Shop Auction Forked From: https://github.com/ourzora/auction-house Original Creators: Zora **/ pragma solidity ^0.8.6; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { IERC721, IERC165 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {Counters} from "@openzeppelin/contracts/utils/Counters.sol"; import { IMarket, Decimal } from "./ScabShopAuction/IMarket.sol"; import { IMedia } from "./ScabShopAuction/IMedia.sol"; import { IAuctionHouse } from "./ScabShopAuction/IAuctionHouse.sol"; interface IWETH { function deposit() external payable; function withdraw(uint wad) external; function transfer(address to, uint256 value) external returns (bool); } interface IMediaExtended is IMedia { function marketContract() external returns(address); } /** * @title An open auction house, enabling collectors and curators to run their own auctions */ contract ScabShopAuction is IAuctionHouse, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; using Counters for Counters.Counter; // The minimum amount of time left in an auction after a new bid is created uint256 public timeBuffer; // The minimum percentage difference between the last bid amount and the current bid. uint8 public minBidIncrementPercentage; // The address of the zora protocol to use via this contract address public zora; // / The address of the WETH contract, so that any ETH transferred can be handled as an ERC-20 address public wethAddress; // The address of the Shop Pass contract, to gete bids address public shopPassAddress; // A mapping of all of the auctions currently running. mapping(uint256 => IAuctionHouse.Auction) public auctions; bytes4 constant interfaceId = 0x80ac58cd; // 721 interface id Counters.Counter private _auctionIdTracker; /** * @notice Require that the specified auction exists */ modifier auctionExists(uint256 auctionId) { require(_exists(auctionId), "Auction doesn't exist"); _; } /* * Constructor */ constructor(address _shopPass, address _zora, address _weth) { shopPassAddress = _shopPass; zora = _zora; wethAddress = _weth; timeBuffer = 15 * 60; // extend 15 minutes after every bid made in last 15 minutes minBidIncrementPercentage = 5; // 5% } /** * @notice Create an auction. * @dev Store the auction details in the auctions mapping and emit an AuctionCreated event. * If there is no curator, or if the curator is the auction creator, automatically approve the auction. */ function createAuction( uint256 tokenId, address tokenContract, uint256 duration, uint256 reservePrice, address payable curator, uint8 curatorFeePercentage, address auctionCurrency ) public override nonReentrant returns (uint256) { require( IERC165(tokenContract).supportsInterface(interfaceId), "tokenContract does not support ERC721 interface" ); require(curatorFeePercentage < 100, "curatorFeePercentage must be less than 100"); address tokenOwner = IERC721(tokenContract).ownerOf(tokenId); require(msg.sender == IERC721(tokenContract).getApproved(tokenId) || msg.sender == tokenOwner, "Caller must be approved or owner for token id"); uint256 auctionId = _auctionIdTracker.current(); auctions[auctionId] = Auction({ tokenId: tokenId, tokenContract: tokenContract, approved: false, amount: 0, duration: duration, firstBidTime: 0, reservePrice: reservePrice, curatorFeePercentage: curatorFeePercentage, tokenOwner: tokenOwner, bidder: payable(address(0)), curator: curator, auctionCurrency: auctionCurrency }); IERC721(tokenContract).transferFrom(tokenOwner, address(this), tokenId); _auctionIdTracker.increment(); emit AuctionCreated(auctionId, tokenId, tokenContract, duration, reservePrice, tokenOwner, curator, curatorFeePercentage, auctionCurrency); if(auctions[auctionId].curator == address(0) || curator == tokenOwner) { _approveAuction(auctionId, true); } return auctionId; } /** * @notice Approve an auction, opening up the auction for bids. * @dev Only callable by the curator. Cannot be called if the auction has already started. */ function setAuctionApproval(uint256 auctionId, bool approved) external override auctionExists(auctionId) { require(msg.sender == auctions[auctionId].curator, "Must be auction curator"); require(auctions[auctionId].firstBidTime == 0, "Auction has already started"); _approveAuction(auctionId, approved); } function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice) external override auctionExists(auctionId) { require(msg.sender == auctions[auctionId].curator || msg.sender == auctions[auctionId].tokenOwner, "Must be auction curator or token owner"); require(auctions[auctionId].firstBidTime == 0, "Auction has already started"); auctions[auctionId].reservePrice = reservePrice; emit AuctionReservePriceUpdated(auctionId, auctions[auctionId].tokenId, auctions[auctionId].tokenContract, reservePrice); } /** * @notice Create a bid on a token, with a given amount. * @dev If provided a valid bid, transfers the provided amount to this contract. * If the auction is run in native ETH, the ETH is wrapped so it can be identically to other * auction currencies in this contract. */ function createBid(uint256 auctionId, uint256 amount) external override payable auctionExists(auctionId) nonReentrant { address payable lastBidder = auctions[auctionId].bidder; require(auctions[auctionId].approved, "Auction must be approved by curator"); require( auctions[auctionId].firstBidTime == 0 || block.timestamp < auctions[auctionId].firstBidTime.add(auctions[auctionId].duration), "Auction expired" ); require( amount >= auctions[auctionId].reservePrice, "Must send at least reservePrice" ); require( amount >= auctions[auctionId].amount.add( auctions[auctionId].amount.mul(minBidIncrementPercentage).div(100) ), "Must send more than last bid by minBidIncrementPercentage amount" ); require(IERC721(shopPassAddress).balanceOf(msg.sender) >= 1, "Must own a Shop Pass to bid"); // For Zora Protocol, ensure that the bid is valid for the current bidShare configuration if(auctions[auctionId].tokenContract == zora) { require( IMarket(IMediaExtended(zora).marketContract()).isValidBid( auctions[auctionId].tokenId, amount ), "Bid invalid for share splitting" ); } // If this is the first valid bid, we should set the starting time now. // If it's not, then we should refund the last bidder if(auctions[auctionId].firstBidTime == 0) { auctions[auctionId].firstBidTime = block.timestamp; } else if(lastBidder != address(0)) { _handleOutgoingBid(lastBidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency); } _handleIncomingBid(amount, auctions[auctionId].auctionCurrency); auctions[auctionId].amount = amount; auctions[auctionId].bidder = payable(msg.sender); bool extended = false; // at this point we know that the timestamp is less than start + duration (since the auction would be over, otherwise) // we want to know by how much the timestamp is less than start + duration // if the difference is less than the timeBuffer, increase the duration by the timeBuffer if ( auctions[auctionId].firstBidTime.add(auctions[auctionId].duration).sub( block.timestamp ) < timeBuffer ) { // Playing code golf for gas optimization: // uint256 expectedEnd = auctions[auctionId].firstBidTime.add(auctions[auctionId].duration); // uint256 timeRemaining = expectedEnd.sub(block.timestamp); // uint256 timeToAdd = timeBuffer.sub(timeRemaining); // uint256 newDuration = auctions[auctionId].duration.add(timeToAdd); uint256 oldDuration = auctions[auctionId].duration; auctions[auctionId].duration = oldDuration.add(timeBuffer.sub(auctions[auctionId].firstBidTime.add(oldDuration).sub(block.timestamp))); extended = true; } emit AuctionBid( auctionId, auctions[auctionId].tokenId, auctions[auctionId].tokenContract, msg.sender, amount, lastBidder == address(0), // firstBid boolean extended ); if (extended) { emit AuctionDurationExtended( auctionId, auctions[auctionId].tokenId, auctions[auctionId].tokenContract, auctions[auctionId].duration ); } } /** * @notice End an auction, finalizing the bid on Zora if applicable and paying out the respective parties. * @dev If for some reason the auction cannot be finalized (invalid token recipient, for example), * The auction is reset and the NFT is transferred back to the auction creator. */ function endAuction(uint256 auctionId) external override auctionExists(auctionId) nonReentrant { require( uint256(auctions[auctionId].firstBidTime) != 0, "Auction hasn't begun" ); require( block.timestamp >= auctions[auctionId].firstBidTime.add(auctions[auctionId].duration), "Auction hasn't completed" ); address currency = auctions[auctionId].auctionCurrency == address(0) ? wethAddress : auctions[auctionId].auctionCurrency; uint256 curatorFee = 0; uint256 tokenOwnerProfit = auctions[auctionId].amount; if(auctions[auctionId].tokenContract == zora) { // If the auction is running on zora, settle it on the protocol (bool success, uint256 remainingProfit) = _handleZoraAuctionSettlement(auctionId); tokenOwnerProfit = remainingProfit; if(success != true) { _handleOutgoingBid(auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency); _cancelAuction(auctionId); return; } } else { // Otherwise, transfer the token to the winner and pay out the participants below try IERC721(auctions[auctionId].tokenContract).safeTransferFrom(address(this), auctions[auctionId].bidder, auctions[auctionId].tokenId) {} catch { _handleOutgoingBid(auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency); _cancelAuction(auctionId); return; } } if(auctions[auctionId].curator != address(0)) { curatorFee = tokenOwnerProfit.mul(auctions[auctionId].curatorFeePercentage).div(100); tokenOwnerProfit = tokenOwnerProfit.sub(curatorFee); _handleOutgoingBid(auctions[auctionId].curator, curatorFee, auctions[auctionId].auctionCurrency); } _handleOutgoingBid(auctions[auctionId].tokenOwner, tokenOwnerProfit, auctions[auctionId].auctionCurrency); emit AuctionEnded( auctionId, auctions[auctionId].tokenId, auctions[auctionId].tokenContract, auctions[auctionId].tokenOwner, auctions[auctionId].curator, auctions[auctionId].bidder, tokenOwnerProfit, curatorFee, currency ); delete auctions[auctionId]; } /** * @notice Cancel an auction. * @dev Transfers the NFT back to the auction creator and emits an AuctionCanceled event */ function cancelAuction(uint256 auctionId) external override nonReentrant auctionExists(auctionId) { require( auctions[auctionId].tokenOwner == msg.sender || auctions[auctionId].curator == msg.sender, "Can only be called by auction creator or curator" ); require( uint256(auctions[auctionId].firstBidTime) == 0, "Can't cancel an auction once it's begun" ); _cancelAuction(auctionId); } /** * @dev Given an amount and a currency, transfer the currency to this contract. * If the currency is ETH (0x0), attempt to wrap the amount as WETH */ function _handleIncomingBid(uint256 amount, address currency) internal { // If this is an ETH bid, ensure they sent enough and convert it to WETH under the hood if(currency == address(0)) { require(msg.value == amount, "Sent ETH Value does not match specified bid amount"); IWETH(wethAddress).deposit{value: amount}(); } else { // We must check the balance that was actually transferred to the auction, // as some tokens impose a transfer fee and would not actually transfer the // full amount to the market, resulting in potentally locked funds IERC20 token = IERC20(currency); uint256 beforeBalance = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), amount); uint256 afterBalance = token.balanceOf(address(this)); require(beforeBalance.add(amount) == afterBalance, "Token transfer call did not transfer expected amount"); } } function _handleOutgoingBid(address to, uint256 amount, address currency) internal { // If the auction is in ETH, unwrap it from its underlying WETH and try to send it to the recipient. if(currency == address(0)) { IWETH(wethAddress).withdraw(amount); // If the ETH transfer fails (sigh), rewrap the ETH and try send it as WETH. if(!_safeTransferETH(to, amount)) { IWETH(wethAddress).deposit{value: amount}(); IERC20(wethAddress).safeTransfer(to, amount); } } else { IERC20(currency).safeTransfer(to, amount); } } function _safeTransferETH(address to, uint256 value) internal returns (bool) { (bool success, ) = to.call{value: value}(new bytes(0)); return success; } function _cancelAuction(uint256 auctionId) internal { address tokenOwner = auctions[auctionId].tokenOwner; IERC721(auctions[auctionId].tokenContract).safeTransferFrom(address(this), tokenOwner, auctions[auctionId].tokenId); emit AuctionCanceled(auctionId, auctions[auctionId].tokenId, auctions[auctionId].tokenContract, tokenOwner); delete auctions[auctionId]; } function _approveAuction(uint256 auctionId, bool approved) internal { auctions[auctionId].approved = approved; emit AuctionApprovalUpdated(auctionId, auctions[auctionId].tokenId, auctions[auctionId].tokenContract, approved); } function _exists(uint256 auctionId) internal view returns(bool) { return auctions[auctionId].tokenOwner != address(0); } function _handleZoraAuctionSettlement(uint256 auctionId) internal returns (bool, uint256) { address currency = auctions[auctionId].auctionCurrency == address(0) ? wethAddress : auctions[auctionId].auctionCurrency; IMarket.Bid memory bid = IMarket.Bid({ amount: auctions[auctionId].amount, currency: currency, bidder: address(this), recipient: auctions[auctionId].bidder, sellOnShare: Decimal.D256(0) }); IERC20(currency).approve(IMediaExtended(zora).marketContract(), bid.amount); IMedia(zora).setBid(auctions[auctionId].tokenId, bid); uint256 beforeBalance = IERC20(currency).balanceOf(address(this)); try IMedia(zora).acceptBid(auctions[auctionId].tokenId, bid) {} catch { // If the underlying NFT transfer here fails, we should cancel the auction and refund the winner IMediaExtended(zora).removeBid(auctions[auctionId].tokenId); return (false, 0); } uint256 afterBalance = IERC20(currency).balanceOf(address(this)); // We have to calculate the amount to send to the token owner here in case there was a // sell-on share on the token return (true, afterBalance.sub(beforeBalance)); } // TODO: consider reverting if the message sender is not WETH receive() external payable {} fallback() external payable {} } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.6; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Math * * Library for non-standard Math functions * NOTE: This file is a clone of the dydx protocol's Decimal.sol contract. * It was forked from https://github.com/dydxprotocol/solo at commit * 2d8454e02702fe5bc455b848556660629c3cad36. It has not been modified other than to use a * newer solidity in the pragma to match the rest of the contract suite of this project. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128(uint256 number) internal pure returns (uint128) { uint128 result = uint128(number); require(result == number, "Math: Unsafe cast to uint128"); return result; } function to96(uint256 number) internal pure returns (uint96) { uint96 result = uint96(number); require(result == number, "Math: Unsafe cast to uint96"); return result; } function to32(uint256 number) internal pure returns (uint32) { uint32 result = uint32(number); require(result == number, "Math: Unsafe cast to uint32"); return result; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.6; pragma experimental ABIEncoderV2; import {IMarket} from "./IMarket.sol"; /** * @title Interface for Zora Protocol's Media */ interface IMedia { struct EIP712Signature { uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct MediaData { // A valid URI of the content represented by this token string tokenURI; // A valid URI of the metadata associated with this token string metadataURI; // A SHA256 hash of the content pointed to by tokenURI bytes32 contentHash; // A SHA256 hash of the content pointed to by metadataURI bytes32 metadataHash; } event TokenURIUpdated(uint256 indexed _tokenId, address owner, string _uri); event TokenMetadataURIUpdated( uint256 indexed _tokenId, address owner, string _uri ); /** * @notice Return the metadata URI for a piece of media given the token URI */ function tokenMetadataURI(uint256 tokenId) external view returns (string memory); /** * @notice Mint new media for msg.sender. */ function mint(MediaData calldata data, IMarket.BidShares calldata bidShares) external; /** * @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature. */ function mintWithSig( address creator, MediaData calldata data, IMarket.BidShares calldata bidShares, EIP712Signature calldata sig ) external; /** * @notice Transfer the token with the given ID to a given address. * Save the previous owner before the transfer, in case there is a sell-on fee. * @dev This can only be called by the auction contract specified at deployment */ function auctionTransfer(uint256 tokenId, address recipient) external; /** * @notice Set the ask on a piece of media */ function setAsk(uint256 tokenId, IMarket.Ask calldata ask) external; /** * @notice Remove the ask on a piece of media */ function removeAsk(uint256 tokenId) external; /** * @notice Set the bid on a piece of media */ function setBid(uint256 tokenId, IMarket.Bid calldata bid) external; /** * @notice Remove the bid on a piece of media */ function removeBid(uint256 tokenId) external; function acceptBid(uint256 tokenId, IMarket.Bid calldata bid) external; /** * @notice Revoke approval for a piece of media */ function revokeApproval(uint256 tokenId) external; /** * @notice Update the token URI */ function updateTokenURI(uint256 tokenId, string calldata tokenURI) external; /** * @notice Update the token metadata uri */ function updateTokenMetadataURI( uint256 tokenId, string calldata metadataURI ) external; /** * @notice EIP-712 permit method. Sets an approved spender given a valid signature. */ function permit( address spender, uint256 tokenId, EIP712Signature calldata sig ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.6; pragma experimental ABIEncoderV2; import {Decimal} from "./Decimal.sol"; /** * @title Interface for Zora Protocol's Market */ interface IMarket { struct Bid { // Amount of the currency being bid uint256 amount; // Address to the ERC20 token being used to bid address currency; // Address of the bidder address bidder; // Address of the recipient address recipient; // % of the next sale to award the current owner Decimal.D256 sellOnShare; } struct Ask { // Amount of the currency being asked uint256 amount; // Address to the ERC20 token being asked address currency; } struct BidShares { // % of sale value that goes to the _previous_ owner of the nft Decimal.D256 prevOwner; // % of sale value that goes to the original creator of the nft Decimal.D256 creator; // % of sale value that goes to the seller (current owner) of the nft Decimal.D256 owner; } event BidCreated(uint256 indexed tokenId, Bid bid); event BidRemoved(uint256 indexed tokenId, Bid bid); event BidFinalized(uint256 indexed tokenId, Bid bid); event AskCreated(uint256 indexed tokenId, Ask ask); event AskRemoved(uint256 indexed tokenId, Ask ask); event BidShareUpdated(uint256 indexed tokenId, BidShares bidShares); function bidForTokenBidder(uint256 tokenId, address bidder) external view returns (Bid memory); function currentAskForToken(uint256 tokenId) external view returns (Ask memory); function bidSharesForToken(uint256 tokenId) external view returns (BidShares memory); function isValidBid(uint256 tokenId, uint256 bidAmount) external view returns (bool); function isValidBidShares(BidShares calldata bidShares) external pure returns (bool); function splitShare(Decimal.D256 calldata sharePercentage, uint256 amount) external pure returns (uint256); function configure(address mediaContractAddress) external; function setBidShares(uint256 tokenId, BidShares calldata bidShares) external; function setAsk(uint256 tokenId, Ask calldata ask) external; function removeAsk(uint256 tokenId) external; function setBid( uint256 tokenId, Bid calldata bid, address spender ) external; function removeBid(uint256 tokenId, address bidder) external; function acceptBid(uint256 tokenId, Bid calldata expectedBid) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.6; pragma experimental ABIEncoderV2; /** * @title Interface for Auction Houses */ interface IAuctionHouse { struct Auction { // ID for the ERC721 token uint256 tokenId; // Address for the ERC721 contract address tokenContract; // Whether or not the auction curator has approved the auction to start bool approved; // The current highest bid amount uint256 amount; // The length of time to run the auction for, after the first bid was made uint256 duration; // The time of the first bid uint256 firstBidTime; // The minimum price of the first bid uint256 reservePrice; // The sale percentage to send to the curator uint8 curatorFeePercentage; // The address that should receive the funds once the NFT is sold. address tokenOwner; // The address of the current highest bid address payable bidder; // The address of the auction's curator. // The curator can reject or approve an auction address payable curator; // The address of the ERC-20 currency to run the auction with. // If set to 0x0, the auction will be run in ETH address auctionCurrency; } event AuctionCreated( uint256 indexed auctionId, uint256 indexed tokenId, address indexed tokenContract, uint256 duration, uint256 reservePrice, address tokenOwner, address curator, uint8 curatorFeePercentage, address auctionCurrency ); event AuctionApprovalUpdated( uint256 indexed auctionId, uint256 indexed tokenId, address indexed tokenContract, bool approved ); event AuctionReservePriceUpdated( uint256 indexed auctionId, uint256 indexed tokenId, address indexed tokenContract, uint256 reservePrice ); event AuctionBid( uint256 indexed auctionId, uint256 indexed tokenId, address indexed tokenContract, address sender, uint256 value, bool firstBid, bool extended ); event AuctionDurationExtended( uint256 indexed auctionId, uint256 indexed tokenId, address indexed tokenContract, uint256 duration ); event AuctionEnded( uint256 indexed auctionId, uint256 indexed tokenId, address indexed tokenContract, address tokenOwner, address curator, address winner, uint256 amount, uint256 curatorFee, address auctionCurrency ); event AuctionCanceled( uint256 indexed auctionId, uint256 indexed tokenId, address indexed tokenContract, address tokenOwner ); function createAuction( uint256 tokenId, address tokenContract, uint256 duration, uint256 reservePrice, address payable curator, uint8 curatorFeePercentages, address auctionCurrency ) external returns (uint256); function setAuctionApproval(uint256 auctionId, bool approved) external; function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice) external; function createBid(uint256 auctionId, uint256 amount) external payable; function endAuction(uint256 auctionId) external; function cancelAuction(uint256 auctionId) external; } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2019 dYdX Trading Inc. 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.8.6; pragma experimental ABIEncoderV2; /** * NOTE: This file is a clone of the dydx protocol's Decimal.sol contract. It was forked from https://github.com/dydxprotocol/solo * at commit 2d8454e02702fe5bc455b848556660629c3cad36 * * It has not been modified other than to use a newer solidity in the pragma to match the rest of the contract suite of this project */ import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { Math } from "./Math.sol"; /** * @title Decimal * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE_POW = 18; uint256 constant BASE = 10**BASE_POW; // ============ Structs ============ struct D256 { uint256 value; } // ============ Functions ============ function one() internal pure returns (D256 memory) { return D256({value: BASE}); } function onePlus(D256 memory d) internal pure returns (D256 memory) { return D256({value: d.value.add(BASE)}); } function mul(uint256 target, D256 memory d) internal pure returns (uint256) { return Math.getPartial(target, d.value, BASE); } function div(uint256 target, D256 memory d) internal pure returns (uint256) { return Math.getPartial(target, BASE, d.value); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) 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 generally not needed starting with Solidity 0.8, since 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 // 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 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.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; } } // 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 (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.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 (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 (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; } }
* @notice Approve an auction, opening up the auction for bids. @dev Only callable by the curator. Cannot be called if the auction has already started./
function setAuctionApproval(uint256 auctionId, bool approved) external override auctionExists(auctionId) { require(msg.sender == auctions[auctionId].curator, "Must be auction curator"); require(auctions[auctionId].firstBidTime == 0, "Auction has already started"); _approveAuction(auctionId, approved); }
1,157,518
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 1716, 685, 537, 392, 279, 4062, 16, 10890, 731, 326, 279, 4062, 364, 30534, 18, 632, 5206, 5098, 4140, 635, 326, 662, 639, 18, 14143, 506, 2566, 309, 326, 279, 4062, 711, 1818, 5746, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 37, 4062, 23461, 12, 11890, 5034, 279, 4062, 548, 16, 1426, 20412, 13, 3903, 3849, 279, 4062, 4002, 12, 69, 4062, 548, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 279, 4062, 87, 63, 69, 4062, 548, 8009, 1397, 639, 16, 315, 10136, 506, 279, 4062, 662, 639, 8863, 203, 3639, 2583, 12, 69, 4062, 87, 63, 69, 4062, 548, 8009, 3645, 17763, 950, 422, 374, 16, 315, 37, 4062, 711, 1818, 5746, 8863, 203, 3639, 389, 12908, 537, 37, 4062, 12, 69, 4062, 548, 16, 20412, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /* Contract Imports */ import { L2StandardERC721 } from "../../standards/L2StandardERC721.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import { IL2StandardERC721Factory } from './IL2StandardERC721Factory.sol'; /** * @title L2StandardERC721Factory * @dev Factory contract for creating standard L2 ERC721 representations of L1 ERC721s * compatible with and working on the NFT bridge. */ contract L2StandardERC721Factory is IL2StandardERC721Factory { mapping(address => bool) public isStandardERC721; mapping(address => address) public standardERC721Mapping; /** * @inheritdoc IL2StandardERC721Factory */ function createStandardL2ERC721( address _l1Token, string memory _name, string memory _symbol ) external { require(_l1Token != address(0), "Must provide L1 token address"); require( standardERC721Mapping[_l1Token] == address(0), "L2 Standard Token already exists for this L1 Token" ); L2StandardERC721 l2Token = new L2StandardERC721( Lib_PredeployAddresses.L2_ERC721_BRIDGE, _l1Token, _name, _symbol ); isStandardERC721[address(l2Token)] = true; standardERC721Mapping[_l1Token] = address(l2Token); emit StandardL2ERC721Created(_l1Token, address(l2Token)); } }
* @title L2StandardERC721Factory @dev Factory contract for creating standard L2 ERC721 representations of L1 ERC721s compatible with and working on the NFT bridge./
contract L2StandardERC721Factory is IL2StandardERC721Factory { mapping(address => bool) public isStandardERC721; mapping(address => address) public standardERC721Mapping; function createStandardL2ERC721( address _l1Token, string memory _name, string memory _symbol pragma solidity ^0.8.9; import { L2StandardERC721 } from "../../standards/L2StandardERC721.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import { IL2StandardERC721Factory } from './IL2StandardERC721Factory.sol'; ) external { require(_l1Token != address(0), "Must provide L1 token address"); require( standardERC721Mapping[_l1Token] == address(0), "L2 Standard Token already exists for this L1 Token" ); L2StandardERC721 l2Token = new L2StandardERC721( Lib_PredeployAddresses.L2_ERC721_BRIDGE, _l1Token, _name, _symbol ); isStandardERC721[address(l2Token)] = true; standardERC721Mapping[_l1Token] = address(l2Token); emit StandardL2ERC721Created(_l1Token, address(l2Token)); } }
2,488,671
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2649, 511, 22, 8336, 654, 39, 27, 5340, 1733, 632, 5206, 7822, 6835, 364, 4979, 4529, 511, 22, 4232, 39, 27, 5340, 27851, 434, 511, 21, 4232, 39, 27, 5340, 87, 7318, 598, 471, 5960, 603, 326, 423, 4464, 10105, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 511, 22, 8336, 654, 39, 27, 5340, 1733, 353, 467, 48, 22, 8336, 654, 39, 27, 5340, 1733, 288, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 353, 8336, 654, 39, 27, 5340, 31, 203, 565, 2874, 12, 2867, 516, 1758, 13, 1071, 4529, 654, 39, 27, 5340, 3233, 31, 203, 203, 565, 445, 752, 8336, 48, 22, 654, 39, 27, 5340, 12, 203, 3639, 1758, 389, 80, 21, 1345, 16, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 29, 31, 203, 5666, 288, 511, 22, 8336, 654, 39, 27, 5340, 289, 628, 315, 16644, 10005, 87, 19, 48, 22, 8336, 654, 39, 27, 5340, 18, 18281, 14432, 203, 5666, 288, 10560, 67, 1386, 12411, 7148, 289, 628, 315, 16644, 31417, 19, 13358, 19, 5664, 67, 1386, 12411, 7148, 18, 18281, 14432, 203, 5666, 288, 467, 48, 22, 8336, 654, 39, 27, 5340, 1733, 289, 628, 12871, 2627, 22, 8336, 654, 39, 27, 5340, 1733, 18, 18281, 13506, 203, 565, 262, 3903, 288, 203, 3639, 2583, 24899, 80, 21, 1345, 480, 1758, 12, 20, 3631, 315, 10136, 5615, 511, 21, 1147, 1758, 8863, 203, 203, 3639, 2583, 12, 203, 5411, 4529, 654, 39, 27, 5340, 3233, 63, 67, 80, 21, 1345, 65, 422, 1758, 12, 20, 3631, 203, 5411, 315, 48, 22, 8263, 3155, 1818, 1704, 364, 333, 511, 21, 3155, 6, 203, 3639, 11272, 203, 203, 3639, 511, 22, 8336, 654, 39, 27, 5340, 328, 22, 1345, 273, 394, 511, 22, 8336, 654, 39, 27, 5340, 12, 203, 5411, 10560, 67, 1386, 12411, 7148, 18, 48, 22, 67, 654, 39, 27, 5340, 67, 7192, 734, 7113, 16, 203, 5411, 389, 80, 21, 1345, 16, 203, 5411, 389, 529, 16, 203, 5411, 389, 7175, 203, 3639, 11272, 203, 203, 3639, 353, 8336, 654, 39, 27, 5340, 63, 2867, 12, 80, 22, 1345, 25887, 273, 638, 31, 203, 3639, 4529, 654, 39, 27, 5340, 3233, 63, 67, 80, 21, 1345, 65, 273, 1758, 12, 80, 22, 1345, 1769, 203, 3639, 3626, 8263, 48, 22, 654, 39, 27, 5340, 6119, 24899, 80, 21, 1345, 16, 1758, 12, 80, 22, 1345, 10019, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/137/0x6ceb95626A59a2F8B1d0B6DB970F4190B89354C7/sources/_koyofinance/exchange-vault-solidity-utils/contracts/helpers/WordCodec.sol
We never accept 256 bit values (which would make the codec pointless), and the larger the offset the smaller the maximum bit length. Testing unsigned values for size is straightforward: their upper bits must be cleared.
function _validateEncodingParams( uint256 value, uint256 offset, uint256 bitLength ) private pure { _require(offset < 256, Errors.OUT_OF_BOUNDS); _require(bitLength >= 1 && bitLength <= Math.min(255, 256 - offset), Errors.OUT_OF_BOUNDS); _require(value >> bitLength == 0, Errors.CODEC_OVERFLOW); }
3,751,645
[ 1, 4625, 348, 7953, 560, 30, 225, 1660, 5903, 2791, 8303, 2831, 924, 261, 12784, 4102, 1221, 326, 9196, 1634, 2656, 3631, 471, 326, 10974, 326, 1384, 326, 10648, 326, 4207, 2831, 769, 18, 7766, 310, 9088, 924, 364, 963, 353, 21251, 11565, 30, 3675, 3854, 4125, 1297, 506, 16054, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5662, 4705, 1370, 12, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 2254, 5034, 1384, 16, 203, 3639, 2254, 5034, 2831, 1782, 203, 565, 262, 3238, 16618, 288, 203, 3639, 389, 6528, 12, 3348, 411, 8303, 16, 9372, 18, 5069, 67, 3932, 67, 5315, 2124, 3948, 1769, 203, 3639, 389, 6528, 12, 3682, 1782, 1545, 404, 597, 2831, 1782, 1648, 2361, 18, 1154, 12, 10395, 16, 8303, 300, 1384, 3631, 9372, 18, 5069, 67, 3932, 67, 5315, 2124, 3948, 1769, 203, 203, 3639, 389, 6528, 12, 1132, 1671, 2831, 1782, 422, 374, 16, 9372, 18, 5572, 39, 67, 12959, 17430, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.6; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import "@openzeppelin/contracts/access/Ownable.sol"; contract TeamTimeLock is Ownable{ using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public token; uint256 public blockReward; // Monthly rewards are fixed uint256 public startBlock; uint256 public endBlock; uint256 public rewardDept; // Rewards already withdrawn //address public beneficiary; string public introduce; uint256 public maxReward; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. } mapping(address => UserInfo) userInfos; uint256 public totalShare; bool public paused; event WithDraw(address indexed operator, address indexed to, uint256 amount); constructor( address _token, uint256 _maxReward, uint256 _startBlock, uint256 _endBlock, string memory _introduce ) public { require(_maxReward > 0, "TimeLock: _maxReward is zero"); token = IERC20(_token); maxReward = _maxReward.mul(1e18); blockReward = maxReward.div(_endBlock.sub(_startBlock)); startBlock = _startBlock; endBlock = _endBlock; rewardDept = 0; introduce = _introduce; paused = true; } function initParams(uint256 _maxReward, uint256 _startBlock, uint256 _endBlock) public onlyOwner { require(paused == true, "Benifit has been started"); maxReward = _maxReward.mul(1e18); blockReward = maxReward.div(_endBlock.sub(_startBlock)); startBlock = _startBlock; endBlock = _endBlock; rewardDept = 0; } modifier notPause() { require(paused == false, "Benifit has been suspended"); _; } function setPause() public onlyOwner { paused = !paused; } function addUser(address addr,uint256 amount) public onlyOwner{ require(paused,"benefit is running"); UserInfo storage user = userInfos[addr]; user.amount = user.amount.add(amount); totalShare = totalShare.add(amount); } function removeUser(address addr,uint256 amount) public onlyOwner{ require(paused,"benefit is running"); UserInfo storage user = userInfos[addr]; require(user.amount > 0 , "user not beneficiary"); totalShare = totalShare.sub(amount); user.amount = user.amount.sub(amount); } function getBalance() public view returns (uint256) { return token.balanceOf(address(this)); } function getCurrentUserReward(address addr) public notPause view returns (uint256) { uint256 reward = getReward(addr,block.number); if(reward <= token.balanceOf(address(this))){ return reward; } return token.balanceOf(address(this)); } function getTotalReward(uint256 blocknumber) public notPause view returns (uint256) { if (blocknumber <= startBlock) { return 0; } uint256 totalReward= blocknumber.sub(startBlock).mul(blockReward); if(totalReward >= maxReward ){ return maxReward; } return totalReward; } function getReward(address addr,uint256 blocknumber) public notPause view returns (uint256) { UserInfo storage user = userInfos[addr]; if(user.amount==0){ return 0; } uint256 totalReward=getTotalReward(blocknumber); uint256 reward = totalReward.mul(user.amount).div(totalShare).sub(user.rewardDebt); return reward; } function withDraw(address beneficiary) notPause external { UserInfo storage user = userInfos[beneficiary]; require(user.amount>0,"user amount zero"); uint256 reward = getCurrentUserReward(beneficiary); require(reward > 0, "TimeLock: no reward"); user.rewardDebt = user.rewardDebt.add(reward); token.safeTransfer(beneficiary, reward); emit WithDraw(msg.sender, beneficiary, reward); } }
address public beneficiary; Info of each user.
contract TeamTimeLock is Ownable{ using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public token; uint256 public startBlock; uint256 public endBlock; string public introduce; uint256 public maxReward; struct UserInfo { } mapping(address => UserInfo) userInfos; uint256 public totalShare; bool public paused; event WithDraw(address indexed operator, address indexed to, uint256 amount); constructor( address _token, uint256 _maxReward, uint256 _startBlock, uint256 _endBlock, string memory _introduce ) public { require(_maxReward > 0, "TimeLock: _maxReward is zero"); token = IERC20(_token); maxReward = _maxReward.mul(1e18); blockReward = maxReward.div(_endBlock.sub(_startBlock)); startBlock = _startBlock; endBlock = _endBlock; rewardDept = 0; introduce = _introduce; paused = true; } function initParams(uint256 _maxReward, uint256 _startBlock, uint256 _endBlock) public onlyOwner { require(paused == true, "Benifit has been started"); maxReward = _maxReward.mul(1e18); blockReward = maxReward.div(_endBlock.sub(_startBlock)); startBlock = _startBlock; endBlock = _endBlock; rewardDept = 0; } modifier notPause() { require(paused == false, "Benifit has been suspended"); _; } function setPause() public onlyOwner { paused = !paused; } function addUser(address addr,uint256 amount) public onlyOwner{ require(paused,"benefit is running"); UserInfo storage user = userInfos[addr]; user.amount = user.amount.add(amount); totalShare = totalShare.add(amount); } function removeUser(address addr,uint256 amount) public onlyOwner{ require(paused,"benefit is running"); UserInfo storage user = userInfos[addr]; require(user.amount > 0 , "user not beneficiary"); totalShare = totalShare.sub(amount); user.amount = user.amount.sub(amount); } function getBalance() public view returns (uint256) { return token.balanceOf(address(this)); } function getCurrentUserReward(address addr) public notPause view returns (uint256) { uint256 reward = getReward(addr,block.number); if(reward <= token.balanceOf(address(this))){ return reward; } return token.balanceOf(address(this)); } function getCurrentUserReward(address addr) public notPause view returns (uint256) { uint256 reward = getReward(addr,block.number); if(reward <= token.balanceOf(address(this))){ return reward; } return token.balanceOf(address(this)); } function getTotalReward(uint256 blocknumber) public notPause view returns (uint256) { if (blocknumber <= startBlock) { return 0; } uint256 totalReward= blocknumber.sub(startBlock).mul(blockReward); if(totalReward >= maxReward ){ return maxReward; } return totalReward; } function getTotalReward(uint256 blocknumber) public notPause view returns (uint256) { if (blocknumber <= startBlock) { return 0; } uint256 totalReward= blocknumber.sub(startBlock).mul(blockReward); if(totalReward >= maxReward ){ return maxReward; } return totalReward; } function getTotalReward(uint256 blocknumber) public notPause view returns (uint256) { if (blocknumber <= startBlock) { return 0; } uint256 totalReward= blocknumber.sub(startBlock).mul(blockReward); if(totalReward >= maxReward ){ return maxReward; } return totalReward; } function getReward(address addr,uint256 blocknumber) public notPause view returns (uint256) { UserInfo storage user = userInfos[addr]; if(user.amount==0){ return 0; } uint256 totalReward=getTotalReward(blocknumber); uint256 reward = totalReward.mul(user.amount).div(totalShare).sub(user.rewardDebt); return reward; } function getReward(address addr,uint256 blocknumber) public notPause view returns (uint256) { UserInfo storage user = userInfos[addr]; if(user.amount==0){ return 0; } uint256 totalReward=getTotalReward(blocknumber); uint256 reward = totalReward.mul(user.amount).div(totalShare).sub(user.rewardDebt); return reward; } function withDraw(address beneficiary) notPause external { UserInfo storage user = userInfos[beneficiary]; require(user.amount>0,"user amount zero"); uint256 reward = getCurrentUserReward(beneficiary); require(reward > 0, "TimeLock: no reward"); user.rewardDebt = user.rewardDebt.add(reward); token.safeTransfer(beneficiary, reward); emit WithDraw(msg.sender, beneficiary, reward); } }
1,065,368
[ 1, 4625, 348, 7953, 560, 30, 1758, 1071, 27641, 74, 14463, 814, 31, 3807, 434, 1517, 729, 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, 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, 5034, 1071, 679, 1768, 31, 203, 565, 533, 1071, 16658, 311, 31, 203, 565, 2254, 5034, 1071, 943, 17631, 1060, 31, 203, 203, 203, 565, 1958, 25003, 288, 203, 565, 289, 203, 203, 565, 2874, 12, 2867, 516, 25003, 13, 729, 7655, 31, 203, 565, 2254, 5034, 1071, 2078, 9535, 31, 203, 565, 1426, 1071, 17781, 31, 203, 203, 565, 871, 3423, 6493, 12, 2867, 8808, 3726, 16, 1758, 8808, 358, 16, 2254, 5034, 3844, 1769, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 2254, 5034, 389, 1896, 17631, 1060, 16, 203, 3639, 2254, 5034, 389, 1937, 1768, 16, 203, 3639, 2254, 5034, 389, 409, 1768, 16, 203, 3639, 533, 3778, 389, 23342, 2544, 311, 203, 565, 262, 1071, 288, 203, 3639, 2583, 24899, 1896, 17631, 1060, 405, 374, 16, 315, 950, 2531, 30, 389, 1896, 17631, 1060, 353, 3634, 8863, 203, 3639, 1147, 273, 467, 654, 39, 3462, 24899, 2316, 1769, 203, 3639, 943, 17631, 1060, 273, 389, 1896, 17631, 1060, 18, 16411, 12, 21, 73, 2643, 1769, 203, 3639, 1203, 17631, 1060, 273, 943, 17631, 1060, 18, 2892, 24899, 409, 1768, 18, 1717, 24899, 1937, 1768, 10019, 203, 3639, 787, 1768, 273, 389, 1937, 1768, 31, 203, 3639, 679, 1768, 273, 389, 409, 1768, 31, 203, 3639, 19890, 758, 337, 273, 374, 31, 203, 3639, 16658, 311, 273, 389, 23342, 2544, 311, 31, 203, 3639, 17781, 273, 638, 31, 203, 565, 289, 203, 203, 565, 445, 1208, 1370, 12, 11890, 5034, 389, 1896, 17631, 1060, 16, 203, 3639, 2254, 5034, 389, 1937, 1768, 16, 203, 3639, 2254, 5034, 389, 409, 1768, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 8774, 3668, 422, 638, 16, 315, 38, 275, 430, 305, 711, 2118, 5746, 8863, 203, 203, 3639, 943, 17631, 1060, 273, 389, 1896, 17631, 1060, 18, 16411, 12, 21, 73, 2643, 1769, 203, 3639, 1203, 17631, 1060, 273, 943, 17631, 1060, 18, 2892, 24899, 409, 1768, 18, 1717, 24899, 1937, 1768, 10019, 203, 3639, 787, 1768, 273, 389, 1937, 1768, 31, 203, 3639, 679, 1768, 273, 389, 409, 1768, 31, 203, 3639, 19890, 758, 337, 273, 374, 31, 203, 203, 565, 289, 203, 203, 203, 565, 9606, 486, 19205, 1435, 288, 203, 3639, 2583, 12, 8774, 3668, 422, 629, 16, 315, 38, 275, 430, 305, 711, 2118, 21850, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 565, 445, 17004, 1579, 1435, 1071, 1338, 5541, 288, 203, 3639, 17781, 273, 401, 8774, 3668, 31, 203, 565, 289, 203, 203, 565, 445, 527, 1299, 12, 2867, 3091, 16, 11890, 5034, 3844, 13, 1071, 1338, 5541, 95, 203, 3639, 2583, 12, 8774, 3668, 10837, 70, 4009, 7216, 353, 3549, 8863, 203, 203, 3639, 25003, 2502, 729, 273, 729, 7655, 63, 4793, 15533, 203, 3639, 729, 18, 8949, 273, 729, 18, 8949, 18, 1289, 12, 8949, 1769, 203, 3639, 2078, 9535, 273, 2078, 9535, 18, 1289, 12, 8949, 1769, 203, 203, 565, 289, 203, 203, 565, 445, 1206, 1299, 12, 2867, 3091, 16, 11890, 5034, 3844, 13, 1071, 1338, 5541, 95, 203, 3639, 2583, 12, 8774, 3668, 10837, 70, 4009, 7216, 353, 3549, 8863, 203, 3639, 25003, 2502, 729, 273, 729, 7655, 63, 4793, 15533, 203, 3639, 2583, 12, 1355, 18, 8949, 405, 374, 269, 315, 1355, 486, 27641, 74, 14463, 814, 8863, 203, 3639, 2078, 9535, 273, 2078, 9535, 18, 1717, 12, 8949, 1769, 203, 3639, 729, 18, 8949, 273, 729, 18, 8949, 18, 1717, 12, 8949, 1769, 203, 565, 289, 203, 203, 565, 445, 2882, 6112, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 565, 289, 203, 203, 203, 565, 445, 21995, 17631, 1060, 12, 2867, 3091, 13, 1071, 486, 19205, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 19890, 273, 4170, 359, 1060, 12, 4793, 16, 2629, 18, 2696, 1769, 203, 540, 203, 3639, 309, 12, 266, 2913, 1648, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 15329, 203, 5411, 327, 19890, 31, 203, 3639, 289, 203, 203, 3639, 327, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 203, 565, 289, 203, 203, 377, 203, 203, 565, 445, 21995, 17631, 1060, 12, 2867, 3091, 13, 1071, 486, 19205, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 19890, 273, 4170, 359, 1060, 12, 4793, 16, 2629, 18, 2696, 1769, 203, 540, 203, 3639, 309, 12, 266, 2913, 1648, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 15329, 203, 5411, 327, 19890, 31, 203, 3639, 289, 203, 203, 3639, 327, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 203, 565, 289, 203, 203, 377, 203, 203, 565, 445, 12831, 17631, 1060, 12, 11890, 5034, 1203, 2696, 13, 1071, 486, 19205, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 2629, 2696, 1648, 787, 1768, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 540, 203, 3639, 2254, 5034, 2078, 17631, 1060, 33, 1203, 2696, 18, 1717, 12, 1937, 1768, 2934, 16411, 12, 2629, 17631, 1060, 1769, 203, 3639, 309, 12, 4963, 17631, 1060, 1545, 943, 17631, 1060, 262, 95, 203, 5411, 327, 943, 17631, 1060, 31, 203, 3639, 289, 203, 3639, 327, 2078, 17631, 1060, 31, 203, 565, 289, 203, 203, 203, 565, 445, 12831, 17631, 1060, 12, 11890, 5034, 1203, 2696, 13, 1071, 486, 19205, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 2629, 2696, 1648, 787, 1768, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 540, 203, 3639, 2254, 5034, 2078, 17631, 1060, 33, 1203, 2696, 18, 1717, 12, 1937, 1768, 2934, 16411, 12, 2629, 17631, 1060, 1769, 203, 3639, 309, 12, 4963, 17631, 1060, 1545, 943, 17631, 1060, 262, 95, 203, 5411, 327, 943, 17631, 1060, 31, 203, 3639, 289, 203, 3639, 327, 2078, 17631, 2 ]
./full_match/4/0xe440b9cBaF7b31513F8414abd1D6c7a63dd01DD8/sources/contracts/Loka.sol
Ideally, you would pass in some sort of unique identifier to reference your token for this demo we're just repurposing the token URI
contract Loka is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; uint256 public cost = 0.001 ether; uint256 private itemCounter; address [] public holderIndex; mapping(uint256 => string) public tokenAttribute; mapping(address => uint256) public claimableYield; function name() public view virtual override returns (string memory) mapping(string => uint256) public _uriId; mapping(address => uint256) public _tokenOwned; mapping(address => bool) public _holderExists; uint256 currentYield = 0; address payable thisContract; bool internal disbursed=false; pragma solidity ^0.8.0; {return("LoKa - Renewable Energy Blockchain Miner_V2");} constructor() ERC721("Loka", "LOKA") { thisContract=payable(address(this)); currentYield = 0.005 ether; } function getHolderIndex(uint256 id) public view returns(address){ return holderIndex[id]; } function getCurrentYield() public view onlyOwner returns(uint256){ return currentYield/1 ether; } function setCurrentYield(uint256 yield) public onlyOwner{ currentYield=yield*1 gwei; disbursed=false; } function disburseYield() public onlyOwner{ require(!disbursed,"this yield has been disbursed"); for(uint256 i=0;i<holderIndex.length;i++){ claimableYield[holderIndex[i]]+=(tokenQuantity(holderIndex[i])*currentYield)/totalSupply(); } disbursed=true; } function disburseYield() public onlyOwner{ require(!disbursed,"this yield has been disbursed"); for(uint256 i=0;i<holderIndex.length;i++){ claimableYield[holderIndex[i]]+=(tokenQuantity(holderIndex[i])*currentYield)/totalSupply(); } disbursed=true; } function test_yield() public view returns(uint256){ return (tokenQuantity(msg.sender)*currentYield)/totalSupply(); } function getYield() public view returns(uint256) { return claimableYield[msg.sender]/1 gwei; } function claimYield() public payable { payable(msg.sender).transfer(claimableYield[msg.sender]); claimableYield[msg.sender]=0; } function receiveEth() public payable { } function mintNFT(string memory _tokenURI) public payable returns (uint256) { require(_uriId[_tokenURI] == 0, "This key is already minted"); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(msg.sender, newItemId); setTokenUri(newItemId, _tokenURI); _setTokenURI(newItemId, _tokenURI); _tokenOwned[msg.sender]+=1; itemCounter = _tokenIds.current(); if(!_holderExists[msg.sender]){ _holderExists[msg.sender]=true; holderIndex.push(msg.sender); claimableYield[msg.sender]=0 ether; } return newItemId; } function mintNFT(string memory _tokenURI) public payable returns (uint256) { require(_uriId[_tokenURI] == 0, "This key is already minted"); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(msg.sender, newItemId); setTokenUri(newItemId, _tokenURI); _setTokenURI(newItemId, _tokenURI); _tokenOwned[msg.sender]+=1; itemCounter = _tokenIds.current(); if(!_holderExists[msg.sender]){ _holderExists[msg.sender]=true; holderIndex.push(msg.sender); claimableYield[msg.sender]=0 ether; } return newItemId; } function _baseURI() internal pure override returns (string memory) { } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 id) public override(ERC721, ERC721URIStorage) view returns (string memory){ string memory encodedUri = Base64.encode( bytes(string( abi.encodePacked(tokenAttribute[id]) )) ); return string(abi.encodePacked('data:application/json;base64,', encodedUri)); } function setTokenUri(uint256 id, string memory attributeUri) internal{ tokenAttribute[id]=attributeUri; } function tokenByUri(string memory _uri) external view returns(uint256) { return _uriId[_uri]; } function tokenQuantity(address addr) public view returns(uint256) { return _tokenOwned[addr]; } function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalKeys = totalSupply(); uint256 resultIndex = 0; uint256 tokenId; for (tokenId = 1; tokenId <= totalKeys; tokenId++) { if (ownerOf(tokenId) == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalKeys = totalSupply(); uint256 resultIndex = 0; uint256 tokenId; for (tokenId = 1; tokenId <= totalKeys; tokenId++) { if (ownerOf(tokenId) == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } } else { function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalKeys = totalSupply(); uint256 resultIndex = 0; uint256 tokenId; for (tokenId = 1; tokenId <= totalKeys; tokenId++) { if (ownerOf(tokenId) == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalKeys = totalSupply(); uint256 resultIndex = 0; uint256 tokenId; for (tokenId = 1; tokenId <= totalKeys; tokenId++) { if (ownerOf(tokenId) == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } }
12,374,800
[ 1, 4625, 348, 7953, 560, 30, 225, 23062, 1230, 16, 1846, 4102, 1342, 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 353, 4232, 39, 27, 5340, 16, 4232, 39, 27, 5340, 3572, 25121, 16, 4232, 39, 27, 5340, 3098, 3245, 16, 14223, 6914, 288, 203, 202, 9940, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 202, 18037, 18, 4789, 3238, 389, 2316, 2673, 31, 203, 202, 11890, 5034, 1071, 6991, 273, 374, 18, 11664, 225, 2437, 31, 203, 202, 11890, 5034, 3238, 761, 4789, 31, 203, 202, 2867, 5378, 1071, 10438, 1016, 31, 203, 202, 6770, 12, 11890, 5034, 516, 533, 13, 1071, 1147, 1499, 31, 203, 202, 6770, 12, 2867, 516, 2254, 5034, 13, 1071, 7516, 429, 16348, 31, 203, 202, 915, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 203, 202, 6770, 12, 1080, 516, 2254, 5034, 13, 1071, 389, 1650, 548, 31, 203, 202, 6770, 12, 2867, 516, 2254, 5034, 13, 1071, 389, 2316, 5460, 329, 31, 203, 202, 6770, 12, 2867, 516, 1426, 13, 1071, 389, 4505, 4002, 31, 203, 202, 11890, 5034, 783, 16348, 273, 374, 31, 203, 202, 2867, 8843, 429, 333, 8924, 31, 203, 202, 6430, 2713, 1015, 70, 295, 730, 33, 5743, 31, 203, 202, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 202, 95, 2463, 2932, 1504, 47, 69, 300, 25921, 359, 429, 512, 1224, 7797, 3914, 5639, 5444, 264, 67, 58, 22, 8863, 97, 203, 202, 12316, 1435, 4232, 39, 27, 5340, 2932, 48, 601, 69, 3113, 315, 1502, 47, 37, 7923, 288, 203, 202, 202, 2211, 8924, 33, 10239, 429, 12, 2867, 12, 2211, 10019, 203, 202, 202, 2972, 16348, 273, 374, 18, 28564, 225, 2437, 31, 203, 202, 97, 203, 202, 203, 202, 915, 336, 6064, 1016, 12, 11890, 5034, 612, 13, 1071, 1476, 1135, 12, 2867, 15329, 203, 202, 202, 2463, 10438, 1016, 63, 350, 15533, 203, 202, 97, 203, 202, 915, 5175, 16348, 1435, 1071, 1476, 1338, 5541, 1135, 12, 11890, 5034, 15329, 203, 3639, 327, 783, 16348, 19, 21, 225, 2437, 31, 203, 565, 289, 203, 203, 202, 915, 12589, 16348, 12, 11890, 5034, 2824, 13, 1071, 1338, 5541, 95, 203, 3639, 783, 16348, 33, 23604, 14, 21, 314, 1814, 77, 31, 203, 202, 202, 2251, 70, 295, 730, 33, 5743, 31, 203, 565, 289, 203, 203, 202, 915, 1015, 70, 295, 307, 16348, 1435, 1071, 1338, 5541, 95, 203, 202, 202, 6528, 12, 5, 2251, 70, 295, 730, 10837, 2211, 2824, 711, 2118, 1015, 70, 295, 730, 8863, 203, 202, 202, 1884, 12, 11890, 5034, 277, 33, 20, 31, 77, 32, 4505, 1016, 18, 2469, 31, 77, 27245, 95, 203, 1082, 202, 14784, 429, 16348, 63, 4505, 1016, 63, 77, 65, 3737, 28657, 2316, 12035, 12, 4505, 1016, 63, 77, 5717, 14, 2972, 16348, 13176, 4963, 3088, 1283, 5621, 203, 202, 202, 97, 203, 202, 202, 2251, 70, 295, 730, 33, 3767, 31, 203, 202, 97, 203, 203, 202, 915, 1015, 70, 295, 307, 16348, 1435, 1071, 1338, 5541, 95, 203, 202, 202, 6528, 12, 5, 2251, 70, 295, 730, 10837, 2211, 2824, 711, 2118, 1015, 70, 295, 730, 8863, 203, 202, 202, 1884, 12, 11890, 5034, 277, 33, 20, 31, 77, 32, 4505, 1016, 18, 2469, 31, 77, 27245, 95, 203, 1082, 202, 14784, 429, 16348, 63, 4505, 1016, 63, 77, 65, 3737, 28657, 2316, 12035, 12, 4505, 1016, 63, 77, 5717, 14, 2972, 16348, 13176, 4963, 3088, 1283, 5621, 203, 202, 202, 97, 203, 202, 202, 2251, 70, 295, 730, 33, 3767, 31, 203, 202, 97, 203, 203, 202, 915, 1842, 67, 23604, 1435, 1071, 1476, 1135, 12, 11890, 5034, 15329, 203, 202, 202, 2463, 261, 2316, 12035, 12, 3576, 18, 15330, 17653, 2972, 16348, 13176, 4963, 3088, 1283, 5621, 203, 1082, 203, 202, 97, 203, 203, 202, 915, 10448, 491, 1435, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 202, 202, 2463, 7516, 429, 16348, 63, 3576, 18, 15330, 18537, 21, 314, 1814, 77, 31, 203, 202, 97, 203, 202, 915, 7516, 16348, 1435, 1071, 8843, 429, 288, 203, 3639, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 14784, 429, 16348, 63, 3576, 18, 15330, 19226, 203, 202, 202, 14784, 429, 16348, 63, 3576, 18, 15330, 65, 33, 20, 31, 203, 565, 289, 203, 203, 202, 915, 6798, 41, 451, 1435, 1071, 8843, 429, 288, 203, 540, 203, 565, 289, 203, 202, 203, 203, 202, 915, 312, 474, 50, 4464, 12, 1080, 3778, 389, 2316, 3098, 13, 203, 3639, 1071, 8843, 429, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 202, 202, 6528, 24899, 1650, 548, 63, 67, 2316, 3098, 65, 422, 374, 16, 315, 2503, 498, 353, 1818, 312, 474, 329, 8863, 203, 1082, 203, 3639, 389, 2316, 2673, 18, 15016, 5621, 203, 203, 3639, 2254, 5034, 394, 17673, 273, 389, 2316, 2673, 18, 2972, 5621, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 394, 17673, 1769, 203, 3639, 22629, 3006, 12, 2704, 17673, 16, 389, 2316, 3098, 1769, 203, 3639, 389, 542, 1345, 3098, 12, 2704, 17673, 16, 389, 2316, 3098, 1769, 203, 202, 202, 67, 2316, 5460, 329, 63, 3576, 18, 15330, 3737, 33, 21, 31, 203, 3639, 761, 4789, 273, 389, 2316, 2673, 18, 2972, 5621, 203, 202, 202, 430, 12, 5, 67, 4505, 4002, 63, 3576, 18, 15330, 5717, 95, 203, 1082, 202, 67, 4505, 4002, 63, 3576, 18, 15330, 65, 33, 3767, 31, 203, 1082, 202, 4505, 1016, 18, 6206, 12, 3576, 18, 15330, 1769, 202, 203, 1082, 202, 14784, 429, 16348, 63, 3576, 18, 15330, 65, 33, 20, 225, 2437, 31, 203, 202, 202, 97, 202, 203, 3639, 327, 394, 17673, 31, 203, 565, 289, 203, 203, 203, 203, 203, 1082, 203, 202, 915, 312, 474, 50, 4464, 12, 1080, 3778, 389, 2316, 3098, 13, 203, 3639, 1071, 8843, 429, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 202, 202, 6528, 24899, 1650, 548, 63, 67, 2316, 3098, 65, 422, 374, 16, 315, 2503, 498, 353, 1818, 312, 474, 329, 8863, 203, 1082, 203, 3639, 389, 2316, 2673, 18, 15016, 5621, 203, 203, 3639, 2254, 5034, 394, 17673, 273, 389, 2316, 2673, 18, 2972, 5621, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 2 ]
// File: @openzeppelin/contracts/math/Math.sol pragma solidity 0.5.17; library Math { function MAX311(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN896(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE467(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity 0.5.17; library SafeMath { function ADD124(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB912(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB912(a, b, "SafeMath: subtraction overflow"); } function SUB912(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL612(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function DIV645(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV645(a, b, "SafeMath: division by zero"); } function DIV645(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function MOD528(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD528(a, b, "SafeMath: modulo by zero"); } function MOD528(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity 0.5.17; contract Context { // 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 _MSGSENDER219() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA337() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity 0.5.17; contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED705(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER219(); emit OWNERSHIPTRANSFERRED705(address(0), _owner); } function OWNER858() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER527() { //inject NONSTANDARD NAMING require(ISOWNER429(), "Ownable: caller is not the owner"); _; } function ISOWNER429() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER219() == _owner; } function RENOUNCEOWNERSHIP633() public ONLYOWNER527 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED705(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP10(address newOwner) public ONLYOWNER527 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP120(newOwner); } function _TRANSFEROWNERSHIP120(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED705(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity 0.5.17; interface IERC20 { function TOTALSUPPLY2() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF265(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER164(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function MINT263(address account, uint amount) external; //inject NONSTANDARD NAMING function BURN805(uint amount) external; //inject NONSTANDARD NAMING function ALLOWANCE538(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE42(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM15(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function MINTERS951(address account) external view returns (bool); //inject NONSTANDARD NAMING event TRANSFER380(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL481(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity 0.5.17; library Address { function ISCONTRACT794(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // 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 != 0x0 && codehash != accountHash); } function TOPAYABLE864(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE732(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line 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/SafeERC20.sol pragma solidity 0.5.17; library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER450(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.TRANSFER164.selector, to, value)); } function SAFETRANSFERFROM145(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.TRANSFERFROM15.selector, from, to, value)); } function SAFEAPPROVE302(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE538(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, value)); } function SAFEINCREASEALLOWANCE445(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE538(address(this), spender).ADD124(value); CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE538(address(this), spender).SUB912(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, newAllowance)); } function CALLOPTIONALRETURN337(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // 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).ISCONTRACT794(), "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/IRewardDistributionRecipient.sol pragma solidity 0.5.17; contract IRewardDistributionRecipient is Ownable { address public rewardReferral; function NOTIFYREWARDAMOUNT832(uint256 reward) external; //inject NONSTANDARD NAMING function SETREWARDREFERRAL334(address _rewardReferral) external ONLYOWNER527 { //inject NONSTANDARD NAMING rewardReferral = _rewardReferral; } } // File: contracts/CurveRewards.sol pragma solidity 0.5.17; contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; IERC20 public yfv = IERC20(0x45f24BaEef268BB6d63AEe5129015d69702BCDfa); uint256 private _totalSupply; mapping(address => uint256) private _balances; function TOTALSUPPLY2() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF265(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TOKENSTAKE952(uint256 amount, uint256 actualStakeAmount) internal { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.ADD124(actualStakeAmount); _balances[msg.sender] = _balances[msg.sender].ADD124(actualStakeAmount); yfv.SAFETRANSFERFROM145(msg.sender, address(this), amount); } function TOKENSTAKEONBEHALF333(address stakeFor, uint256 amount, uint256 actualStakeAmount) internal { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.ADD124(actualStakeAmount); _balances[stakeFor] = _balances[stakeFor].ADD124(actualStakeAmount); yfv.SAFETRANSFERFROM145(msg.sender, address(this), amount); } function TOKENWITHDRAW537(uint256 amount, uint256 actualWithdrawAmount) internal { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.SUB912(amount); _balances[msg.sender] = _balances[msg.sender].SUB912(amount); yfv.SAFETRANSFER450(msg.sender, actualWithdrawAmount); } } interface IYFVReferral { function SETREFERRER414(address farmer, address referrer) external; //inject NONSTANDARD NAMING function GETREFERRER855(address farmer) external view returns (address); //inject NONSTANDARD NAMING } contract YFVStakeV2 is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public vUSD = IERC20(0x1B8E12F839BD4e73A47adDF76cF7F0097d74c14C); IERC20 public vETH = IERC20(0x76A034e76Aa835363056dd418611E4f81870f16e); uint256 public vETH_REWARD_FRACTION_RATE = 1000; uint256 public constant duration178 = 7 days; //inject NONSTANDARD NAMING uint8 public constant number_epochs944 = 38; //inject NONSTANDARD NAMING uint256 public constant referral_commission_percent277 = 1; //inject NONSTANDARD NAMING uint256 public currentEpochReward = 0; uint256 public totalAccumulatedReward = 0; uint8 public currentEpoch = 0; uint256 public starttime = 1598968800; // Tuesday, September 1, 2020 2:00:00 PM (GMT+0) uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public constant default_epoch_reward278 = 230000 * (10 ** 9); // 230,000 vUSD (and 230 vETH) //inject NONSTANDARD NAMING uint256 public constant total_reward44 = default_epoch_reward278 * number_epochs944; // 8,740,000 vUSD (and 8,740 vETH) //inject NONSTANDARD NAMING uint256 public epochReward = default_epoch_reward278; uint256 public minStakingAmount = 90 ether; uint256 public unstakingFrozenTime = 40 hours; // ** DISABLED AT BEGINNING - WILL SET IT BY GOVERNANCE AFTER VIP-1.1 // ** unlockWithdrawFee = 0.1%: stakers will need to pay 0.1% (sent to insurance fund)of amount they want to withdraw if the coin still frozen // ** lowStakeDepositFee = 0.1%: stakers still can stake with low amount but need to pay 0.1% (sent to insurance fund) // specially, if lowStakeDepositFee = 10000 -> low amount stakers will not pay anything (richmen pay tax, not poormen) // ** highStakeDepositFee = 0.1%: stakers need to pay 0.1% of extra amount more than 90 YFV (sent to insurance fund) uint256 public lowStakeDepositFee = 0; // per ten thousand (eg. 15 -> 0.15%) uint256 public highStakeDepositFee = 0; // per ten thousand (eg. 15 -> 0.15%) uint256 public unlockWithdrawFee = 0; // per ten thousand (eg. 15 -> 0.15%) address public yfvInsuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public lastStakeTimes; mapping(address => uint256) public accumulatedStakingPower; // will accumulate every time staker does getReward() mapping(address => bool) public whitelistedPools; // for stake on behalf event REWARDADDED885(uint256 reward); //inject NONSTANDARD NAMING event YFVREWARDADDED261(uint256 reward); //inject NONSTANDARD NAMING event BURNED28(uint256 reward); //inject NONSTANDARD NAMING event STAKED939(address indexed user, uint256 amount, uint256 actualStakeAmount); //inject NONSTANDARD NAMING event WITHDRAWN649(address indexed user, uint256 amount, uint256 actualWithdrawAmount); //inject NONSTANDARD NAMING event REWARDPAID896(address indexed user, uint256 reward); //inject NONSTANDARD NAMING event COMMISSIONPAID234(address indexed user, uint256 reward); //inject NONSTANDARD NAMING constructor() public { whitelistedPools[0x62a9fE913eb596C8faC0936fd2F51064022ba22e] = true; // BAL Pool whitelistedPools[0x70b83A7f5E83B3698d136887253E0bf426C9A117] = true; // YFI Pool whitelistedPools[0x1c990fC37F399C935625b815975D0c9fAD5C31A1] = true; // BAT Pool whitelistedPools[0x752037bfEf024Bd2669227BF9068cb22840174B0] = true; // REN Pool whitelistedPools[0x9b74774f55C0351fD064CfdfFd35dB002C433092] = true; // KNC Pool whitelistedPools[0xFBDE07329FFc9Ec1b70f639ad388B94532b5E063] = true; // BTC Pool whitelistedPools[0x67FfB615EAEb8aA88fF37cCa6A32e322286a42bb] = true; // ETH Pool whitelistedPools[0x196CF719251579cBc850dED0e47e972b3d7810Cd] = true; // LINK Pool whitelistedPools[msg.sender] = true; // to be able to stakeOnBehalf farmer who have stucked fund in Pool Stake v1. } function ADDWHITELISTEDPOOL116(address _addressPool) public ONLYOWNER527 { //inject NONSTANDARD NAMING whitelistedPools[_addressPool] = true; } function REMOVEWHITELISTEDPOOL972(address _addressPool) public ONLYOWNER527 { //inject NONSTANDARD NAMING whitelistedPools[_addressPool] = false; } function SETYFVINSURANCEFUND27(address _yfvInsuranceFund) public ONLYOWNER527 { //inject NONSTANDARD NAMING yfvInsuranceFund = _yfvInsuranceFund; } function SETEPOCHREWARD899(uint256 _epochReward) public ONLYOWNER527 { //inject NONSTANDARD NAMING require(_epochReward <= default_epoch_reward278 * 10, "Insane big _epochReward!"); // At most 10x only epochReward = _epochReward; } function SETMINSTAKINGAMOUNT151(uint256 _minStakingAmount) public ONLYOWNER527 { //inject NONSTANDARD NAMING minStakingAmount = _minStakingAmount; } function SETUNSTAKINGFROZENTIME482(uint256 _unstakingFrozenTime) public ONLYOWNER527 { //inject NONSTANDARD NAMING unstakingFrozenTime = _unstakingFrozenTime; } function SETSTAKEDEPOSITFEE451(uint256 _lowStakeDepositFee, uint256 _highStakeDepositFee) public ONLYOWNER527 { //inject NONSTANDARD NAMING require(_lowStakeDepositFee <= 100 || _lowStakeDepositFee == 10000, "Dont be too greedy"); // <= 1% OR set to 10000 to disable low stake fee require(_highStakeDepositFee <= 100, "Dont be too greedy"); // <= 1% lowStakeDepositFee = _lowStakeDepositFee; highStakeDepositFee = _highStakeDepositFee; } function SETUNLOCKWITHDRAWFEE126(uint256 _unlockWithdrawFee) public ONLYOWNER527 { //inject NONSTANDARD NAMING require(_unlockWithdrawFee <= 1000, "Dont be too greedy"); // <= 10% unlockWithdrawFee = _unlockWithdrawFee; } // To upgrade vUSD contract (v1 is still experimental, we may need vUSDv2 with rebase() function working soon - then governance will call this upgrade) function UPGRADEVUSDCONTRACT293(address _vUSDContract) public ONLYOWNER527 { //inject NONSTANDARD NAMING vUSD = IERC20(_vUSDContract); } // To upgrade vETH contract (v1 is still experimental, we may need vETHv2 with rebase() function working soon - then governance will call this upgrade) function UPGRADEVETHCONTRACT116(address _vETHContract) public ONLYOWNER527 { //inject NONSTANDARD NAMING vETH = IERC20(_vETHContract); } modifier UPDATEREWARD641(address account) { //inject NONSTANDARD NAMING rewardPerTokenStored = REWARDPERTOKEN11(); lastUpdateTime = LASTTIMEREWARDAPPLICABLE544(); if (account != address(0)) { rewards[account] = EARNED432(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function LASTTIMEREWARDAPPLICABLE544() public view returns (uint256) { //inject NONSTANDARD NAMING return Math.MIN896(block.timestamp, periodFinish); } function REWARDPERTOKEN11() public view returns (uint256) { //inject NONSTANDARD NAMING if (TOTALSUPPLY2() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.ADD124( LASTTIMEREWARDAPPLICABLE544() .SUB912(lastUpdateTime) .MUL612(rewardRate) .MUL612(1e18) .DIV645(TOTALSUPPLY2()) ); } // vUSD balance function EARNED432(address account) public view returns (uint256) { //inject NONSTANDARD NAMING uint256 calculatedEarned = BALANCEOF265(account) .MUL612(REWARDPERTOKEN11().SUB912(userRewardPerTokenPaid[account])) .DIV645(1e18) .ADD124(rewards[account]); uint256 poolBalance = vUSD.BALANCEOF265(address(this)); // some rare case the reward can be slightly bigger than real number, we need to check against how much we have left in pool if (calculatedEarned > poolBalance) return poolBalance; return calculatedEarned; } function STAKINGPOWER96(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return accumulatedStakingPower[account].ADD124(EARNED432(account)); } function VETHBALANCE317(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return EARNED432(account).DIV645(vETH_REWARD_FRACTION_RATE); } function STAKE230(uint256 amount, address referrer) public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING require(amount >= 1 szabo, "Do not stake dust"); require(referrer != msg.sender, "You cannot refer yourself."); uint256 actualStakeAmount = amount; uint256 depositFee = 0; if (minStakingAmount > 0) { if (amount < minStakingAmount && lowStakeDepositFee < 10000) { // if amount is less than minStakingAmount and lowStakeDepositFee is not disabled // if governance does not allow low stake if (lowStakeDepositFee == 0) require(amount >= minStakingAmount, "Cannot stake below minStakingAmount"); // otherwise depositFee will be calculated based on the rate else depositFee = amount.MUL612(lowStakeDepositFee).DIV645(10000); } else if (amount > minStakingAmount && highStakeDepositFee > 0) { // if amount is greater than minStakingAmount and governance decides richman to pay tax (of the extra amount) depositFee = amount.SUB912(minStakingAmount).MUL612(highStakeDepositFee).DIV645(10000); } if (depositFee > 0) { actualStakeAmount = amount.SUB912(depositFee); } } super.TOKENSTAKE952(amount, actualStakeAmount); lastStakeTimes[msg.sender] = block.timestamp; emit STAKED939(msg.sender, amount, actualStakeAmount); if (depositFee > 0) { if (yfvInsuranceFund != address(0)) { // send fee to insurance yfv.SAFETRANSFER450(yfvInsuranceFund, depositFee); emit REWARDPAID896(yfvInsuranceFund, depositFee); } else { // or burn yfv.BURN805(depositFee); emit BURNED28(depositFee); } } if (rewardReferral != address(0) && referrer != address(0)) { IYFVReferral(rewardReferral).SETREFERRER414(msg.sender, referrer); } } function STAKEONBEHALF204(address stakeFor, uint256 amount) public UPDATEREWARD641(stakeFor) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING require(amount >= 1 szabo, "Do not stake dust"); require(whitelistedPools[msg.sender], "Sorry hackers, you should stay away from us (YFV community signed)"); uint256 actualStakeAmount = amount; uint256 depositFee = 0; if (minStakingAmount > 0) { if (amount < minStakingAmount && lowStakeDepositFee < 10000) { // if amount is less than minStakingAmount and lowStakeDepositFee is not disabled // if governance does not allow low stake if (lowStakeDepositFee == 0) require(amount >= minStakingAmount, "Cannot stake below minStakingAmount"); // otherwise depositFee will be calculated based on the rate else depositFee = amount.MUL612(lowStakeDepositFee).DIV645(10000); } else if (amount > minStakingAmount && highStakeDepositFee > 0) { // if amount is greater than minStakingAmount and governance decides richman to pay tax (of the extra amount) depositFee = amount.SUB912(minStakingAmount).MUL612(highStakeDepositFee).DIV645(10000); } if (depositFee > 0) { actualStakeAmount = amount.SUB912(depositFee); } } super.TOKENSTAKEONBEHALF333(stakeFor, amount, actualStakeAmount); lastStakeTimes[stakeFor] = block.timestamp; emit STAKED939(stakeFor, amount, actualStakeAmount); if (depositFee > 0) { actualStakeAmount = amount.SUB912(depositFee); if (yfvInsuranceFund != address(0)) { // send fee to insurance yfv.SAFETRANSFER450(yfvInsuranceFund, depositFee); emit REWARDPAID896(yfvInsuranceFund, depositFee); } else { // or burn yfv.BURN805(depositFee); emit BURNED28(depositFee); } } } function UNFROZENSTAKETIME568(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return lastStakeTimes[account] + unstakingFrozenTime; } function WITHDRAW21(uint256 amount) public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING require(amount > 0, "Cannot withdraw 0"); uint256 actualWithdrawAmount = amount; if (block.timestamp < UNFROZENSTAKETIME568(msg.sender)) { // if coin is still frozen and governance does not allow stakers to unstake before timer ends if (unlockWithdrawFee == 0) revert("Coin is still frozen"); // otherwise withdrawFee will be calculated based on the rate uint256 withdrawFee = amount.MUL612(unlockWithdrawFee).DIV645(10000); actualWithdrawAmount = amount.SUB912(withdrawFee); if (yfvInsuranceFund != address(0)) { // send fee to insurance yfv.SAFETRANSFER450(yfvInsuranceFund, withdrawFee); emit REWARDPAID896(yfvInsuranceFund, withdrawFee); } else { // or burn yfv.BURN805(withdrawFee); emit BURNED28(withdrawFee); } } super.TOKENWITHDRAW537(amount, actualWithdrawAmount); emit WITHDRAWN649(msg.sender, amount, actualWithdrawAmount); } function EXIT848() external { //inject NONSTANDARD NAMING WITHDRAW21(BALANCEOF265(msg.sender)); GETREWARD938(); } function GETREWARD938() public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING uint256 reward = rewards[msg.sender]; if (reward > 0) { accumulatedStakingPower[msg.sender] = accumulatedStakingPower[msg.sender].ADD124(rewards[msg.sender]); rewards[msg.sender] = 0; vUSD.SAFETRANSFER450(msg.sender, reward); vETH.SAFETRANSFER450(msg.sender, reward.DIV645(vETH_REWARD_FRACTION_RATE)); emit REWARDPAID896(msg.sender, reward); } } modifier CHECKNEXTEPOCH825() { //inject NONSTANDARD NAMING require(periodFinish > 0, "Pool has not started"); if (block.timestamp >= periodFinish) { currentEpochReward = epochReward; if (totalAccumulatedReward.ADD124(currentEpochReward) > total_reward44) { currentEpochReward = total_reward44.SUB912(totalAccumulatedReward); // limit total reward } if (currentEpochReward > 0) { if (!vUSD.MINTERS951(address(this)) || !vETH.MINTERS951(address(this))) { currentEpochReward = 0; } else { vUSD.MINT263(address(this), currentEpochReward); vETH.MINT263(address(this), currentEpochReward.DIV645(vETH_REWARD_FRACTION_RATE)); totalAccumulatedReward = totalAccumulatedReward.ADD124(currentEpochReward); } currentEpoch++; } rewardRate = currentEpochReward.DIV645(duration178); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.ADD124(duration178); emit REWARDADDED885(currentEpochReward); } _; } // Start the pool with reward amount for this epoch function NOTIFYREWARDAMOUNT832(uint256 reward) external ONLYOWNER527 UPDATEREWARD641(address(0)) { //inject NONSTANDARD NAMING require(periodFinish == 0, "Only can call once to start staking"); currentEpochReward = reward; if (totalAccumulatedReward.ADD124(currentEpochReward) > total_reward44) { currentEpochReward = total_reward44.SUB912(totalAccumulatedReward); // limit total reward } lastUpdateTime = block.timestamp; if (block.timestamp < starttime) { // epoch zero periodFinish = starttime; rewardRate = reward.DIV645(periodFinish.SUB912(block.timestamp)); } else { // 1st epoch periodFinish = lastUpdateTime.ADD124(duration178); rewardRate = reward.DIV645(duration178); currentEpoch++; } vUSD.MINT263(address(this), reward); vETH.MINT263(address(this), reward.DIV645(vETH_REWARD_FRACTION_RATE)); totalAccumulatedReward = totalAccumulatedReward.ADD124(reward); emit REWARDADDED885(reward); } // This function allows governance to take unsupported tokens out of the contract, since this pool exists longer than the other pools. // This is in an effort to make someone whole, should they seriously mess up. // There is no guarantee governance will vote to return these. // It also allows for removal of airdropped tokens. function GOVERNANCERECOVERUNSUPPORTED727(IERC20 _token, uint256 amount, address to) external { //inject NONSTANDARD NAMING // only gov require(msg.sender == OWNER858(), "!governance"); // cant take staked asset require(_token != yfv, "yfv"); // cant take reward asset require(_token != vUSD, "vUSD"); require(_token != vETH, "vETH"); // transfer to _token.SAFETRANSFER450(to, amount); } }
inject NONSTANDARD NAMING
function SETUNSTAKINGFROZENTIME482(uint256 _unstakingFrozenTime) public ONLYOWNER527 {
7,225,465
[ 1, 4625, 348, 7953, 560, 30, 4590, 18708, 882, 18264, 423, 2192, 1360, 203, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7855, 2124, 882, 14607, 1360, 42, 1457, 62, 2222, 3114, 8875, 22, 12, 11890, 5034, 389, 23412, 6159, 42, 9808, 950, 13, 1071, 20747, 29602, 25, 5324, 288, 202, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x47Bad9D30293971161FF575ffcd5BDda482a5325/sources/browser/HEXLOCK.sol
stakes hex - transfers HEX from user to contract - approval neededsenduser infostake HEXget the most recent stakeIndexupdate stake infomint bonus LOCK tokens relative to HEX amount and stake length (stake for more than 20 days and get larger bonus)
function stakeHex(uint hearts, uint dayLength, address payable ref) internal returns(bool) { updateUserData(hearts); hexInterface.stakeStart(hearts, dayLength); uint hexStakeIndex = hexInterface.stakeCount(address(this)).sub(1); updateStakeData(hearts, dayLength, ref, hexStakeIndex); if(dayLength < 10){ dayLength = 10; } require(mintLock(hearts * (dayLength / 100)), "Error: could not mint tokens"); return true; }
8,396,429
[ 1, 4625, 348, 7953, 560, 30, 384, 3223, 3827, 300, 29375, 23971, 628, 729, 358, 6835, 300, 23556, 3577, 4661, 1355, 1123, 334, 911, 23971, 588, 326, 4486, 8399, 384, 911, 1016, 2725, 384, 911, 8286, 362, 474, 324, 22889, 14631, 2430, 3632, 358, 23971, 3844, 471, 384, 911, 769, 261, 334, 911, 364, 1898, 2353, 4200, 4681, 471, 336, 10974, 324, 22889, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7037, 12, 11890, 3904, 485, 87, 16, 2254, 2548, 1782, 16, 1758, 8843, 429, 1278, 13, 203, 3639, 2713, 203, 3639, 1135, 12, 6430, 13, 203, 565, 288, 203, 3639, 1089, 19265, 12, 580, 485, 87, 1769, 203, 3639, 3827, 1358, 18, 334, 911, 1685, 12, 580, 485, 87, 16, 2548, 1782, 1769, 203, 3639, 2254, 3827, 510, 911, 1016, 273, 3827, 1358, 18, 334, 911, 1380, 12, 2867, 12, 2211, 13, 2934, 1717, 12, 21, 1769, 203, 3639, 1089, 510, 911, 751, 12, 580, 485, 87, 16, 2548, 1782, 16, 1278, 16, 3827, 510, 911, 1016, 1769, 203, 3639, 309, 12, 2881, 1782, 411, 1728, 15329, 203, 5411, 2548, 1782, 273, 1728, 31, 203, 3639, 289, 203, 3639, 2583, 12, 81, 474, 2531, 12, 580, 485, 87, 380, 261, 2881, 1782, 342, 2130, 13, 3631, 315, 668, 30, 3377, 486, 312, 474, 2430, 8863, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /* Polymath compliance protocol is intended to ensure regulatory compliance in the jurisdictions that security tokens are being offered in. The compliance protocol allows security tokens remain interoperable so that anyone can build on top of the Polymath platform and extend it's functionality. */ import './SafeMath.sol'; import './interfaces/ICompliance.sol'; import './interfaces/IOfferingFactory.sol'; import './Customers.sol'; import './Template.sol'; import './interfaces/ISecurityToken.sol'; import './interfaces/ISecurityTokenRegistrar.sol'; /** * @title Compilance * @dev Regulatory details offered by the security token */ contract Compliance is ICompliance { using SafeMath for uint256; string public VERSION = "2"; ISecurityTokenRegistrar public STRegistrar; //Structure used to hold reputation for template and offeringFactories struct Reputation { uint256 totalRaised; // Total amount raised by issuers that used the template / offeringFactory address[] usedBy; // Array of security token addresses that used this particular template / offeringFactory mapping (address => bool) usedBySecurityToken; // Mapping of STs using this Reputation } mapping(address => Reputation) public templates; // Mapping used for storing the template repuation mapping(address => address[]) public templateProposals; // Template proposals for a specific security token mapping(address => Reputation) public offeringFactories; // Mapping used for storing the offering factory reputation mapping(address => address[]) public offeringFactoryProposals; // OfferingFactory proposals for a specific security token mapping(address => mapping(address => bool)) public proposedTemplatesList; // Use to restrict the proposing the same templates again and again mapping(address => mapping(address => bool)) public proposedOfferingFactoryList; // Use to restrict the proposing the same offeringFactory again and again Customers public PolyCustomers; // Instance of the Compliance contract uint256 public constant MINIMUM_VESTING_PERIOD = 60 * 60 * 24 * 100; // 100 Day minimum vesting period for POLY earned // Notifications for templates event LogTemplateCreated(address indexed _creator, address indexed _template, string _offeringType); event LogNewTemplateProposal(address indexed _securityToken, address indexed _template, address indexed _delegate, uint _templateProposalIndex); event LogCancelTemplateProposal(address indexed _securityToken, address indexed _template, uint _templateProposalIndex); // Notifications for offering factories event LogOfferingFactoryRegistered(address indexed _creator, address indexed _offeringFactory, bytes32 _description); event LogNewOfferingFactoryProposal(address indexed _securityToken, address indexed _offeringFactory, address indexed _owner, uint _offeringFactoryProposalIndex); event LogCancelOfferingFactoryProposal(address indexed _securityToken, address indexed _offeringFactory, uint _offeringFactoryProposalIndex); /* @param _polyCustomersAddress The address of the Polymath Customers contract */ function Compliance(address _polyCustomersAddress) public { PolyCustomers = Customers(_polyCustomersAddress); } /** * @dev `setRegistrarAddress` This function set the SecurityTokenRegistrar contract address. * Called just after the deployment of smart contracts. * @param _STRegistrar It is the `this` reference of STR contract * @return bool */ function setRegistrarAddress(address _STRegistrar) public returns (bool) { require(_STRegistrar != address(0)); require(STRegistrar == address(0)); STRegistrar = ISecurityTokenRegistrar(_STRegistrar); return true; } /** * @dev `createTemplate` is a simple function to create a new compliance template * @param _offeringType The name of the security being issued * @param _issuerJurisdiction The jurisdiction id of the issuer * @param _accredited Accreditation status required for investors * @param _KYC KYC provider used by the template * @param _details Details of the offering requirements * @param _expires Timestamp of when the template will expire * @param _fee Amount of POLY to use the template (held in escrow until issuance) * @param _quorum Minimum percent of shareholders which need to vote to freeze * @param _vestingPeriod Length of time to vest funds */ function createTemplate( string _offeringType, bytes32 _issuerJurisdiction, bool _accredited, address _KYC, bytes32 _details, uint256 _expires, uint256 _fee, uint8 _quorum, uint256 _vestingPeriod ) public { require(_KYC != address(0)); require(_vestingPeriod >= MINIMUM_VESTING_PERIOD); require(_quorum > 0 && _quorum <= 100); address _template = new Template( msg.sender, _offeringType, _issuerJurisdiction, _accredited, _KYC, _details, _expires, _fee, _quorum, _vestingPeriod ); templates[_template] = Reputation({ totalRaised: 0, usedBy: new address[](0) }); //Keep track of templates created through Compliance.sol templates[_template].usedBySecurityToken[address(this)] = true; LogTemplateCreated(msg.sender, _template, _offeringType); } /** * @dev Propose a bid for a security token issuance * @param _securityToken The security token being bid on * @param _template The unique template address * @return bool success */ function proposeTemplate( address _securityToken, address _template ) public returns (bool success) { require(templates[_template].usedBySecurityToken[address(this)]); // Verifying that provided _securityToken is generated by securityTokenRegistrar only var (,, securityTokenOwner,) = STRegistrar.getSecurityTokenData(_securityToken); require(securityTokenOwner != address(0)); // Check whether the template is already proposed or not for the given securityToken require(!proposedTemplatesList[_securityToken][_template]); // Creating the instance of template to avail the function calling ITemplate template = ITemplate(_template); // This will fail if template is expired var (,finalized) = template.getTemplateDetails(); var (,,, owner,) = template.getUsageDetails(); // Require that the caller is the template owner // and that the template has been finalized require(owner == msg.sender); require(finalized); //Get a reference of the template contract and add it to the templateProposals array templateProposals[_securityToken].push(_template); proposedTemplatesList[_securityToken][_template] = true; LogNewTemplateProposal(_securityToken, _template, msg.sender, templateProposals[_securityToken].length - 1); return true; } /** * @dev Cancel a Template proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _templateProposalIndex The template proposal array index * @return bool success */ function cancelTemplateProposal( address _securityToken, uint256 _templateProposalIndex ) public returns (bool success) { address proposedTemplate = templateProposals[_securityToken][_templateProposalIndex]; ITemplate template = ITemplate(proposedTemplate); var (,,, owner,) = template.getUsageDetails(); // Cancelation is only being performed by the owner of template. require(owner == msg.sender); var (chosenTemplate,,,,,) = ISecurityToken(_securityToken).getTokenDetails(); // Template shouldn't be choosed one. require(chosenTemplate != proposedTemplate); templateProposals[_securityToken][_templateProposalIndex] = address(0); LogCancelTemplateProposal(_securityToken, proposedTemplate, _templateProposalIndex); return true; } /** * @dev Register the Offering factory by the developer. * @param _factoryAddress address of the offering factory * @return bool success */ function registerOfferingFactory( address _factoryAddress ) public returns (bool success) { require(_factoryAddress != address(0)); // Restrict to update the reputation of already registered offeringFactory require(!(offeringFactories[_factoryAddress].totalRaised > 0 || offeringFactories[_factoryAddress].usedBy.length > 0)); IOfferingFactory offeringFactory = IOfferingFactory(_factoryAddress); var (, quorum, vestingPeriod, owner, description) = offeringFactory.getUsageDetails(); // Validate Offering Factory details require(quorum > 0 && quorum <= 100); require(vestingPeriod >= MINIMUM_VESTING_PERIOD); require(owner != address(0)); // Add the factory in the available list of factory addresses offeringFactories[_factoryAddress] = Reputation({ totalRaised: 0, usedBy: new address[](0) }); // Keep track of offering factories registered through Compliance.sol offeringFactories[_factoryAddress].usedBySecurityToken[address(this)] = true; LogOfferingFactoryRegistered(owner, _factoryAddress, description); return true; } /** * @dev Propose a Security Token Offering Factory for an issuance * @param _securityToken The security token being bid on * @param _factoryAddress The address of the offering factory * @return bool success */ function proposeOfferingFactory( address _securityToken, address _factoryAddress ) public returns (bool success) { require(offeringFactories[_factoryAddress].usedBySecurityToken[address(this)]); // Verifying that provided _securityToken is generated by securityTokenRegistrar only var (,, securityTokenOwner,) = STRegistrar.getSecurityTokenData(_securityToken); require(securityTokenOwner != address(0)); // Check whether the offeringFactory is already proposed or not for the given securityToken require(!proposedOfferingFactoryList[_securityToken][_factoryAddress]); IOfferingFactory offeringFactory = IOfferingFactory(_factoryAddress); var (,,, owner,) = offeringFactory.getUsageDetails(); require(owner == msg.sender); offeringFactoryProposals[_securityToken].push(_factoryAddress); proposedOfferingFactoryList[_securityToken][_factoryAddress] = true; LogNewOfferingFactoryProposal(_securityToken, _factoryAddress, owner, offeringFactoryProposals[_securityToken].length - 1); return true; } /** * @dev Cancel a Offering factory proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _offeringFactoryProposalIndex The offeringFactory proposal array index * @return bool success */ function cancelOfferingFactoryProposal( address _securityToken, uint256 _offeringFactoryProposalIndex ) public returns (bool success) { address proposedOfferingFactory = offeringFactoryProposals[_securityToken][_offeringFactoryProposalIndex]; IOfferingFactory offeringFactory = IOfferingFactory(proposedOfferingFactory); var (,,, owner,) = offeringFactory.getUsageDetails(); // Cancelation is only being performed by the owner of template. require(owner == msg.sender); var (,,,,,chosenOfferingFactory) = ISecurityToken(_securityToken).getTokenDetails(); require(chosenOfferingFactory != proposedOfferingFactory); offeringFactoryProposals[_securityToken][_offeringFactoryProposalIndex] = address(0); LogCancelOfferingFactoryProposal(_securityToken, proposedOfferingFactory, _offeringFactoryProposalIndex); return true; } /** * @dev `updateTemplateReputation` is a function that updates the history of a security token template usage to keep track of previous uses * @param _template The unique template id * @param _polyRaised The amount of poly raised */ function updateTemplateReputation(address _template, uint256 _polyRaised) external returns (bool success) { // Check that the caller is a security token var (,, securityTokenOwner,) = STRegistrar.getSecurityTokenData(msg.sender); require(securityTokenOwner != address(0)); // If it is, then update reputation if (!templates[_template].usedBySecurityToken[msg.sender]) { templates[_template].usedBy.push(msg.sender); templates[_template].usedBySecurityToken[msg.sender] = true; } templates[_template].totalRaised = templates[_template].totalRaised.add(_polyRaised); return true; } /** * @dev `updateOfferingReputation` is a function that updates the history of a security token offeringFactory contract to keep track of previous uses * @param _offeringFactory The address of the offering factory * @param _polyRaised The amount of poly raised */ function updateOfferingFactoryReputation(address _offeringFactory, uint256 _polyRaised) external returns (bool success) { // Check that the caller is a security token var (,, securityTokenOwner,) = STRegistrar.getSecurityTokenData(msg.sender); require(securityTokenOwner != address(0)); // If it is, then update reputation if (!offeringFactories[_offeringFactory].usedBySecurityToken[msg.sender]) { offeringFactories[_offeringFactory].usedBy.push(msg.sender); offeringFactories[_offeringFactory].usedBySecurityToken[msg.sender] = true; } offeringFactories[_offeringFactory].totalRaised = offeringFactories[_offeringFactory].totalRaised.add(_polyRaised); return true; } /** * @dev Get template details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _templateIndex The array index of the template being checked * @return Template struct */ function getTemplateByProposal(address _securityTokenAddress, uint8 _templateIndex) view public returns ( address _template ){ return templateProposals[_securityTokenAddress][_templateIndex]; } /** * @dev Get an array containing the address of all template proposals for a given ST * @param _securityTokenAddress The security token address * @return Template proposals array */ function getAllTemplateProposals(address _securityTokenAddress) view public returns (address[]) { return templateProposals[_securityTokenAddress]; } /** * @dev Get security token offering smart contract details by the proposal index * @param _securityTokenAddress The security token address * @param _offeringFactoryProposalIndex The array index of the STO contract being checked * @return Contract struct */ function getOfferingFactoryByProposal(address _securityTokenAddress, uint8 _offeringFactoryProposalIndex) view public returns ( address _offeringFactoryAddress ){ return offeringFactoryProposals[_securityTokenAddress][_offeringFactoryProposalIndex]; } /** * @dev Get an array containing the address of all offering proposals for a given ST * @param _securityTokenAddress The security token address * @return Offering proposals array */ function getAllOfferingFactoryProposals(address _securityTokenAddress) view public returns (address[]) { return offeringFactoryProposals[_securityTokenAddress]; } }
Mapping used for storing the template repuation
mapping(address => Reputation) public templates;
2,548,401
[ 1, 4625, 348, 7953, 560, 30, 225, 9408, 1399, 364, 15729, 326, 1542, 2071, 11407, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.3; pragma experimental ABIEncoderV2; import "../openzeppelin-solidity/Math.sol"; import "../proxy/BZxProxiable.sol"; import "../shared/MiscFunctions.sol"; import "../oracle/OracleInterface.sol"; import "../tokens/EIP20.sol"; contract LoanMaintenance_MiscFunctions2 is BZxStorage, BZxProxiable, MiscFunctions { using SafeMath for uint256; constructor() public {} function() external { revert("fallback not allowed"); } function initialize( address _target) public onlyOwner { targets[bytes4(keccak256("changeTraderOwnership(bytes32,address)"))] = _target; targets[bytes4(keccak256("changeLenderOwnership(bytes32,address)"))] = _target; targets[bytes4(keccak256("updateLoanAsLender(bytes32,uint256,uint256,uint256)"))] = _target; targets[bytes4(keccak256("isPositionOpen(bytes32,address)"))] = _target; targets[bytes4(keccak256("setLoanOrderDesc(bytes32,string)"))] = _target; } /// @dev Allows the trader to transfer ownership of the underlying assets in a position to another user. /// @param loanOrderHash A unique hash representing the loan order /// @param newOwner The address receiving the transfer /// @return True on success function changeTraderOwnership( bytes32 loanOrderHash, address newOwner) external nonReentrant tracksGas returns (bool) { return false; /*if (orderListIndex[loanOrderHash][newOwner].isSet) { // user can't transfer ownership to another trader or lender already in this order revert("BZxLoanMaintenance::changeTraderOwnership: new owner is invalid"); } LoanOrder memory loanOrder = orders[loanOrderHash]; if (loanOrder.loanTokenAddress == address(0)) { revert("BZxLoanMaintenance::changeTraderOwnership: loanOrder.loanTokenAddress == address(0)"); } uint256 positionid = loanPositionsIds[loanOrderHash][msg.sender]; LoanPosition storage loanPosition = loanPositions[positionid]; if (loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active) { revert("BZxLoanMaintenance::changeTraderOwnership: loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active"); } if (loanPosition.trader != msg.sender) { revert("BZxLoanMaintenance::changeTraderOwnership: msg.sender is not the trader in this position"); } // remove old owner references to loanOrder and loanPosition delete loanPositionsIds[loanOrderHash][msg.sender]; _removeLoanOrder( loanOrderHash, msg.sender ); // add new owner references to loanOrder and loanPosition loanPosition.trader = newOwner; loanPositionsIds[loanOrderHash][newOwner] = positionid; orderList[newOwner].push(loanOrderHash); orderListIndex[loanOrderHash][newOwner] = ListIndex({ index: orderList[newOwner].length-1, isSet: true }); if (!OracleInterface(oracleAddresses[loanOrder.oracleAddress]).didChangeTraderOwnership( loanOrder, loanPosition, msg.sender, // old owner gasUsed // initial used gas, collected in modifier )) { revert("BZxLoanMaintenance::changeTraderOwnership: OracleInterface.didChangeTraderOwnership failed"); } emit LogChangeTraderOwnership( loanOrder.loanOrderHash, msg.sender, // old owner newOwner ); return true;*/ } /// @dev Allows the lender to transfer ownership of the underlying assets in a position to another user. /// @param loanOrderHash A unique hash representing the loan order /// @param newOwner The address receiving the transfer /// @return True on success function changeLenderOwnership( bytes32 loanOrderHash, address newOwner) external nonReentrant tracksGas returns (bool) { return false; /*if (orderLender[loanOrderHash] != msg.sender) { revert("BZxLoanMaintenance::changeLenderOwnership: msg.sender is not the lender in this position"); } if (orderListIndex[loanOrderHash][newOwner].isSet) { // user can't transfer ownership to another trader or lender already in this order revert("BZxLoanMaintenance::changeLenderOwnership: new owner is invalid"); } LoanOrder memory loanOrder = orders[loanOrderHash]; if (loanOrder.loanTokenAddress == address(0)) { revert("BZxLoanMaintenance::changeLenderOwnership: loanOrder.loanTokenAddress == address(0)"); } // remove old owner references to loanOrder _removeLoanOrder( loanOrderHash, msg.sender ); // add new owner references to loanOrder orderLender[loanOrderHash] = newOwner; orderList[newOwner].push(loanOrderHash); orderListIndex[loanOrderHash][newOwner] = ListIndex({ index: orderList[newOwner].length-1, isSet: true }); if (!OracleInterface(oracleAddresses[loanOrder.oracleAddress]).didChangeLenderOwnership( loanOrder, msg.sender, // old owner newOwner, gasUsed // initial used gas, collected in modifier )) { revert("BZxLoanMaintenance::changeLenderOwnership: OracleInterface.didChangeLenderOwnership failed"); } emit LogChangeLenderOwnership( loanOrder.loanOrderHash, msg.sender, // old owner newOwner ); return true; */ } /// @dev Allows the lender to set optional updates to their on-chain loan order that affects future borrowers /// @dev Setting a new interest rate will invalidate the off-chain bZx loan order (only the on-chain order can be taken) /// @param loanOrderHash A unique hash representing the loan order /// @param increaseAmountForLoan Optional parameter to specify the amount of loan token increase /// @param newInterestRate Optional parameter to specify the amount of loan token increase /// @param newExpirationTimestamp Optional parameter to set the expirationUnixTimestampSec on the loan to a different date. A value of MAX_UINT (2**256 - 1) removes the expiration date. /// @return True on success function updateLoanAsLender( bytes32 loanOrderHash, uint256 increaseAmountForLoan, uint256 newInterestRate, uint256 newExpirationTimestamp) external nonReentrant tracksGas returns (bool) { return false; /*if (orderLender[loanOrderHash] != msg.sender || orderAux[loanOrderHash].makerAddress != msg.sender) { revert("BZxOrderTaking::updateLoanAsLender: sender did not make order as lender"); } LoanOrder storage loanOrder = orders[loanOrderHash]; if (loanOrder.loanTokenAddress == address(0)) { revert("BZxOrderTaking::updateLoanAsLender: loanOrder.loanTokenAddress == address(0)"); } bool success = false; uint256 totalNewFillableAmount = loanOrder.loanTokenAmount.sub(_getUnavailableLoanTokenAmount(loanOrderHash)); if (increaseAmountForLoan > 0) { totalNewFillableAmount = totalNewFillableAmount.add(increaseAmountForLoan); // ensure adequate token balance //require (EIP20(loanOrder.loanTokenAddress).balanceOf(msg.sender) >= totalNewFillableAmount, "BZxOrderTaking::updateLoanAsLender: lender balance is insufficient"); // ensure adequate token allowance //require (EIP20(loanOrder.loanTokenAddress).allowance(msg.sender, vaultContract) >= totalNewFillableAmount, "BZxOrderTaking::updateLoanAsLender: lender allowance is insufficient"); uint256 newLoanTokenAmount = loanOrder.loanTokenAmount.add(increaseAmountForLoan); if (newInterestRate == 0 && loanOrder.interestAmount > 0 && loanOrder.loanTokenAmount > 0) { // Interest amount per day is calculated based on the fraction of loan token filled over total loanTokenAmount. // Since total loanTokenAmount is increasing, we increase interest proportionally. loanOrder.interestAmount = loanOrder.interestAmount.mul(newLoanTokenAmount).div(loanOrder.loanTokenAmount); } loanOrder.loanTokenAmount = newLoanTokenAmount; success = true; } if (newInterestRate > 0 && loanOrder.loanTokenAmount > 0) { // We will convert newInterestRate to an actual amount based on loan value, denominated in interestToken. // Percentage format: 2% of total filled loan token value per day = 2 * 10**18 // This is limited to tokens supported by the oracle if interestTokenAddress != loanTokenAddress uint256 loanToInterestAmount; if (loanOrder.interestTokenAddress == loanOrder.loanTokenAddress) { loanToInterestAmount = loanOrder.loanTokenAmount; } else { (uint256 sourceToDestRate, uint256 sourceToDestPrecision,) = OracleInterface(oracleAddresses[loanOrder.oracleAddress]).getTradeData( loanOrder.loanTokenAddress, loanOrder.interestTokenAddress, MAX_UINT // get best rate ); loanToInterestAmount = loanOrder.loanTokenAmount.mul(sourceToDestRate).div(sourceToDestPrecision); require(loanToInterestAmount > 0, "BZxOrderTaking::updateLoanAsLender: loanToInterestAmount == 0"); } loanOrder.interestAmount = loanToInterestAmount.mul(newInterestRate).div(10**20); success = true; } if (newExpirationTimestamp > 0 && newExpirationTimestamp > block.timestamp) { orderAux[loanOrderHash].expirationUnixTimestampSec = newExpirationTimestamp < MAX_UINT ? newExpirationTimestamp : 0; success = true; } if (success) { emit LogUpdateLoanAsLender( loanOrderHash, msg.sender, increaseAmountForLoan, totalNewFillableAmount, orderAux[loanOrderHash].expirationUnixTimestampSec ); if (!OracleInterface(oracleAddresses[loanOrder.oracleAddress]).didUpdateLoanAsLender( loanOrder, msg.sender, increaseAmountForLoan, totalNewFillableAmount, orderAux[loanOrderHash].expirationUnixTimestampSec, gasUsed // initial used gas, collected in modifier )) { revert("BZxOrderTaking::updateLoanAsLender: OracleInterface.didUpdateLoanAsLender failed"); } return true; } else { return false; }*/ } /// @param loanOrderHash A unique hash representing the loan order /// @param trader The trader of the position /// @return True if the position is open/active, false otherwise function isPositionOpen( bytes32 loanOrderHash, address trader) public view returns (bool) { LoanPosition memory loanPosition = loanPositions[loanPositionsIds[loanOrderHash][trader]]; if (loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active) { return false; } else { return true; } } /// @dev Allows the maker of an order to set a description /// @param loanOrderHash A unique hash representing the loan order /// @param desc Descriptive text to attach to the loan order /// @return True on success function setLoanOrderDesc( bytes32 loanOrderHash, string calldata desc) external nonReentrant tracksGas returns (bool) { LoanOrderAux storage loanOrderAux = orderAux[loanOrderHash]; require(loanOrderAux.makerAddress == msg.sender, "BZxLoanMaintenance::setLoanOrderDesc: loanOrderAux.makerAddress != msg.sender"); loanOrderAux.description = desc; return true; } }
We will convert newInterestRate to an actual amount based on loan value, denominated in interestToken. Percentage format: 2% of total filled loan token value per day = 2 * 10**18 This is limited to tokens supported by the oracle if interestTokenAddress != loanTokenAddress
if (newInterestRate > 0 && loanOrder.loanTokenAmount > 0) { uint256 loanToInterestAmount; if (loanOrder.interestTokenAddress == loanOrder.loanTokenAddress) { loanToInterestAmount = loanOrder.loanTokenAmount; (uint256 sourceToDestRate, uint256 sourceToDestPrecision,) = OracleInterface(oracleAddresses[loanOrder.oracleAddress]).getTradeData( loanOrder.loanTokenAddress, loanOrder.interestTokenAddress, ); loanToInterestAmount = loanOrder.loanTokenAmount.mul(sourceToDestRate).div(sourceToDestPrecision); require(loanToInterestAmount > 0, "BZxOrderTaking::updateLoanAsLender: loanToInterestAmount == 0"); } loanOrder.interestAmount = loanToInterestAmount.mul(newInterestRate).div(10**20); success = true; } else { }
13,099,990
[ 1, 4625, 348, 7953, 560, 30, 225, 1660, 903, 1765, 394, 29281, 4727, 358, 392, 3214, 3844, 2511, 603, 28183, 460, 16, 10716, 7458, 316, 16513, 1345, 18, 21198, 410, 740, 30, 576, 9, 434, 2078, 6300, 28183, 1147, 460, 1534, 2548, 273, 576, 380, 1728, 636, 2643, 1220, 353, 13594, 358, 2430, 3260, 635, 326, 20865, 309, 16513, 1345, 1887, 480, 28183, 1345, 1887, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 309, 261, 2704, 29281, 4727, 405, 374, 597, 28183, 2448, 18, 383, 304, 1345, 6275, 405, 374, 13, 288, 203, 203, 203, 5411, 2254, 5034, 28183, 774, 29281, 6275, 31, 203, 5411, 309, 261, 383, 304, 2448, 18, 2761, 395, 1345, 1887, 422, 28183, 2448, 18, 383, 304, 1345, 1887, 13, 288, 203, 7734, 28183, 774, 29281, 6275, 273, 28183, 2448, 18, 383, 304, 1345, 6275, 31, 203, 7734, 261, 11890, 5034, 1084, 774, 9378, 4727, 16, 2254, 5034, 1084, 774, 9378, 15410, 16, 13, 273, 28544, 1358, 12, 280, 16066, 7148, 63, 383, 304, 2448, 18, 280, 16066, 1887, 65, 2934, 588, 22583, 751, 12, 203, 10792, 28183, 2448, 18, 383, 304, 1345, 1887, 16, 203, 10792, 28183, 2448, 18, 2761, 395, 1345, 1887, 16, 203, 7734, 11272, 203, 7734, 28183, 774, 29281, 6275, 273, 28183, 2448, 18, 383, 304, 1345, 6275, 18, 16411, 12, 3168, 774, 9378, 4727, 2934, 2892, 12, 3168, 774, 9378, 15410, 1769, 203, 203, 7734, 2583, 12, 383, 304, 774, 29281, 6275, 405, 374, 16, 315, 38, 62, 92, 2448, 56, 6159, 2866, 2725, 1504, 304, 1463, 48, 2345, 30, 28183, 774, 29281, 6275, 422, 374, 8863, 203, 5411, 289, 203, 203, 5411, 28183, 2448, 18, 2761, 395, 6275, 273, 28183, 774, 29281, 6275, 18, 16411, 12, 2704, 29281, 4727, 2934, 2892, 12, 2163, 636, 3462, 1769, 203, 203, 5411, 2216, 273, 638, 31, 203, 5411, 289, 469, 288, 203, 3639, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/43114/0x45E82ea84e3d3672C909f8b22baa7701BaB3F89a/sources/contracts/DeathIDO.sol
20% of the DEATH for the liquidity (listing price 20 BUY per DEATH), the rest is for the buyers to claim
uint256 _DeathLiquidity = _DeathBalance / 5;
4,499,705
[ 1, 4625, 348, 7953, 560, 30, 225, 4200, 9, 434, 326, 2030, 3275, 364, 326, 4501, 372, 24237, 261, 21228, 6205, 4200, 10937, 61, 1534, 2030, 3275, 3631, 326, 3127, 353, 364, 326, 30143,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-100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-04-25 */ // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @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); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.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; } // 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 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); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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); } // OpenZeppelin Contracts (last updated v4.5.0) (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 * ==== * * [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); } } } } // 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; } } // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @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); } } // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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; } } // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.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); _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 = 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); _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(ERC721.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(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 {} /** * @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 {} } // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) /** * @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; } } // OpenZeppelin Contracts v4.4.1 (access/Ownable.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); } } contract Timewrecked is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supplyTier1; Counters.Counter private supplyTier2; Counters.Counter private supplyTier3; string public uriPrefix = ""; string public uriSuffix = ".json"; string public hiddenMetadataUri; uint256[] tierCosts = [10 ether, 1.5 ether, 0.1 ether]; uint256[] tierMaxSupplies = [1111, 1106, 1081]; uint256 public immutable maxSupply = 1111; bool public publicMintActive = true; bool public revealed = false; mapping(address => uint256) private _allowList; bool public isAllowListActive = false; constructor() ERC721("TIMEWRECKED", "TW") { setHiddenMetadataUri("ipfs://QmdegKBqZVBKCCJvsb7pbG5Vs6xzyTrwmiku1mKKxU6Q1h/hidden.json"); for (uint256 i = 0; i < 1081; i++) { supplyTier2.increment(); } for (uint256 i = 0; i < 1106; i++) { supplyTier1.increment(); } } /// @notice Validates that the mint is compliant and does not exceed the max supply of the given tier. /// @param _mintAmount amount that the caller would like to mint. /// @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3) modifier mintCompliance(uint256 _mintAmount, uint256 _tier) { require(_mintAmount > 0, "Invalid mint amount!"); if(_tier == 3) { require(supplyTier3.current() + _mintAmount <= tierMaxSupplies[2], "Max supply of Tier 3 exceeded!"); } else if (_tier == 2) { require(supplyTier2.current() + _mintAmount <= tierMaxSupplies[1], "Max supply of Tier 2 exceeded!"); } else { require(supplyTier1.current() + _mintAmount <= tierMaxSupplies[0], "Max supply of Tier 1 exceeded!"); } _; } /// @notice Returns the total supply of the collection, all tiers included. /// @return _totalSupply will return the integer amount of the total collection supply. function totalSupply() public view returns (uint256 _totalSupply) { return (supplyTier1.current() - tierMaxSupplies[1]) + (supplyTier2.current() - tierMaxSupplies[2]) + supplyTier3.current() ; } /// @notice Returns the total supply of the given tier within the collection. /// @param _tier the tier you would like to check the total supply of (Tier 1, 2, or 3) /// @return _totalSupply the total supply of the selected tier. function totalSupply(uint256 _tier) public view returns (uint256 _totalSupply) { if(_tier == 1) { return supplyTier1.current() - tierMaxSupplies[1]; } else if (_tier == 2) { return supplyTier2.current() - tierMaxSupplies[2]; } else if(_tier == 3) { return supplyTier3.current(); } } /// @notice Mint function that will check to make sure the public mint is active and the correct funds have been sent in msg.value /// @param _mintAmount the amount of NFTs that the caller would like to mint. /// @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3). function mint(uint256 _mintAmount, uint256 _tier) public payable mintCompliance(_mintAmount, _tier) { require(!publicMintActive, "Public mint is not active!"); if(_tier == 1){ require(msg.value >= tierCosts[0] * _mintAmount, "Insufficient funds for tier 1 mint!!"); } else if(_tier == 2) { require(msg.value >= tierCosts[1] * _mintAmount, "Insufficient funds for tier 2 mint!!"); } else if(_tier == 3) { require(msg.value >= tierCosts[2] * _mintAmount, "Insufficient funds for tier 3 mint!"); } _mintLoop(msg.sender, _mintAmount, _tier); } /// @notice Mint function for addresses that are on the allow list for early mint. Calls _mintLoop after require conditions are met. /// @param _mintAmount The amount of NFTs that the caller would like to mint in allow list. /// @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3). function mintAllowList(uint256 _mintAmount, uint256 _tier) external payable mintCompliance(_mintAmount, _tier) { require(isAllowListActive, "Allow list is not active"); require(_mintAmount <= _allowList[msg.sender], "Exceeded max available to purchase"); require(totalSupply(_tier) + _mintAmount <= tierMaxSupplies[_tier - 1], "Purchase would exceed max tokens"); require(tierCosts[_tier - 1] * _mintAmount <= msg.value, "Ether value sent is not correct"); _allowList[msg.sender] -= _mintAmount; _mintLoop(msg.sender, _mintAmount, _tier); } /// @notice Mints NFT(s) for a specified address, only the owner can call this function. /// @param _mintAmount The amount of NFTs that the caller would like to mint. /// @param _receiver the address that will recieve the NFT(s). /// @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3). function mintForAddress(uint256 _mintAmount, address _receiver, uint256 _tier) public mintCompliance(_mintAmount, _tier) onlyOwner { _mintLoop(_receiver, _mintAmount, _tier); } /// @notice Information on the wallet of a specified address /// @param _owner address that is being checked against. function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "Timewrecked: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } /// @notice Function to set whether the NFTs are revealed/unrevealed /// @param _state boolean flag set to true if revealed, false if unrevealed. function setRevealed(bool _state) public onlyOwner { revealed = _state; } /// @notice Function to set the cost of the NFT by tier. /// @param _cost value being set for the new cost of the selected tier. /// @param _tier the tier (1, 2, or 3) for which the cost is being updated. function setCost(uint256 _cost, uint256 _tier) public onlyOwner { if(_tier == 1) { tierCosts[0] = _cost; } else if(_tier == 2) { tierCosts[1] == _cost; } else if(_tier == 3) { tierCosts[2] == _cost; } } /// @notice Sets the URI for the metadata of the hidden/unrevealed NFT. /// @param _hiddenMetadataUri String for the URI for the hidden metadata. function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } /// @notice Sets the URI for the metadata of the revealed NFT. /// @param _uriPrefix String for the URI for the metadata. function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } /// @notice Sets the URI suffix for the metadata. (".json" by default). /// @param _uriSuffix String for the suffix to be set. function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } /// @notice Sets the public mint being active or inactive /// @param _state set to true if public mint is active, or false if inactive. function setPublicMintActive(bool _state) public onlyOwner { publicMintActive = _state; } /// @notice Function to allow the owner to withdraw funds from contract function withdraw() public onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } /// @notice Function to loop through the ttokens and mint multiple based on tier. /// @param _receiver address that is receiving the NFTs. /// @param _mintAmount the amount of NFTs that the caller would like to mint. /// @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3). function _mintLoop(address _receiver, uint256 _mintAmount, uint256 _tier) internal { if(_tier == 1) { for (uint256 i = 0; i < _mintAmount; i++) { supplyTier1.increment(); _safeMint(_receiver, supplyTier1.current()); } } else if(_tier == 2) { for (uint256 i = 0; i < _mintAmount; i++) { supplyTier2.increment(); _safeMint(_receiver, supplyTier2.current()); } } else if(_tier == 3) { for (uint256 i = 0; i < _mintAmount; i++) { supplyTier3.increment(); _safeMint(_receiver, supplyTier3.current()); } } } /// @notice Function to get the URI of the revealed NFT. /// @return string with the URI. function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } /// @notice Sets what addresses are part of the allow list for early mint. /// @param addresses array of addresses to be added to allow list. /// @param numAllowedToMint number of mints the given addresses will be able to mint in allow list period. function setAllowList(address[] calldata addresses, uint256 numAllowedToMint) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { _allowList[addresses[i]] = numAllowedToMint; } } /// @notice Checks to see whether the given address is on the allow list or not /// @param _address address being checked for allow list. /// @return returns boolean value, true if on allow list or false if not on allowlist. function checkAllowList(address _address) external view returns (bool) { if(_allowList[_address] > 0 ) { return true; } return false; } /// @notice Sets the allow list sale period to active or inactive. /// @param _isAllowListActive boolean flag on whether sale is active (true) or inactive (false). function setIsAllowListActive(bool _isAllowListActive) external onlyOwner { isAllowListActive = _isAllowListActive; } }
@notice Mints NFT(s) for a specified address, only the owner can call this function. @param _mintAmount The amount of NFTs that the caller would like to mint. @param _receiver the address that will recieve the NFT(s). @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3).
function mintForAddress(uint256 _mintAmount, address _receiver, uint256 _tier) public mintCompliance(_mintAmount, _tier) onlyOwner { _mintLoop(_receiver, _mintAmount, _tier); }
2,102,786
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 490, 28142, 423, 4464, 12, 87, 13, 364, 279, 1269, 1758, 16, 1338, 326, 3410, 848, 745, 333, 445, 18, 632, 891, 389, 81, 474, 6275, 1021, 3844, 434, 423, 4464, 87, 716, 326, 4894, 4102, 3007, 358, 312, 474, 18, 632, 891, 389, 24454, 326, 1758, 716, 903, 1950, 21271, 326, 423, 4464, 12, 87, 2934, 632, 891, 389, 88, 2453, 326, 17742, 434, 423, 4464, 716, 326, 4894, 4102, 3007, 358, 312, 474, 261, 15671, 404, 16, 576, 16, 578, 890, 2934, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1290, 1887, 12, 11890, 5034, 389, 81, 474, 6275, 16, 1758, 389, 24454, 16, 2254, 5034, 389, 88, 2453, 13, 1071, 312, 474, 16687, 24899, 81, 474, 6275, 16, 389, 88, 2453, 13, 1338, 5541, 288, 203, 3639, 389, 81, 474, 6452, 24899, 24454, 16, 389, 81, 474, 6275, 16, 389, 88, 2453, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.21 <0.7.0; import "./Vote.sol"; import "./ProposalContract.sol"; import "./Approval.sol"; import "./Safemath.sol"; // 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 contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function transfer(address to, uint tokens) public returns (uint success); function transferFrom(address from, address to, uint tokens) public returns (uint success); event Transfer(address indexed from, address indexed to, uint tokens); } contract GovToken is ERC20Interface { // change deployment addresses after deployment address proposal_contract_address = 0x40B4A36A8f733BbeC4E65FdD75Cd522faB53AeF5; ProposalContract p = ProposalContract(proposal_contract_address); address vote_contract_address = 0xD1DD440475d2d5b9185927B3751C8f716aEcABD2; Vote vote = Vote(vote_contract_address); address approval_contract_address = 0xec43E121aA96b79a4166FdB6CA0A353A415C14b0; Approval approval = Approval(approval_contract_address); string public symbol; string public name; uint public _totalSupply; uint current_epoch = 0; bool council_meeting = false; address internal _driver; mapping(address => uint8) internal _councilMembers; address[] internal councilMembersList; uint private MIN_SIGNATURES = 0; // struct Council{ // address root_user; // address council_member_one; // address council_member_two; // } modifier isOwner() { require(msg.sender == _driver); _; } modifier validOwner() { require(msg.sender == _driver || _councilMembers[msg.sender] == 1); _; } using SafeMath for uint256; mapping(address => uint256) public balances; mapping(address => string) account_type; // Council newCouncil = Council(address(0) , address(0) , address(0)); constructor(string memory _name , string memory _symbol , uint _supply) public { symbol = _symbol; name = _name; _totalSupply = _supply; balances[msg.sender] = _supply; // newCouncil.root_user = msg.sender; _driver = msg.sender; councilMembersList.push(msg.sender); emit Transfer(address(0), msg.sender, _supply); } function revert_casted_votes_after_epoch_ends() internal { uint end = p.getProposalCount(); for(uint i=0;i<end;i++){ uint casted_votes = vote.get_casted_votes_array_length(i); for(uint k=0;k<casted_votes;k++){ (uint votes ,address wallet_address ) = vote.get_token_and_address_for_a_cast(i,k); balances[wallet_address] = balances[wallet_address].add(votes); } } } // add a modifier to check if the msg.sender is a council member function start_new_epoch() validOwner public returns (uint){ // require(msg.sender == approval_contract_address, "Only the Approval contract can call start_new_epoch()"); revert_casted_votes_after_epoch_ends(); vote.clear_casted_votes_after_epoch_ends(); toggle_council_meeting(); approval.decide_final_approvals(); // rewarding the approved proposal vote.reward_most_voted_proposal(); // most voted reward increment_epoch(); return 1; } function getWalletBalance() public view returns(uint, address, uint, address){ return (balances[msg.sender], msg.sender, balances[_driver], _driver); } function getAccountType() public view returns (string memory){ return account_type[msg.sender]; } function initial_transfer(string memory wallet_type, address receiver_address , uint tokens) isOwner public returns (uint){ if(balances[receiver_address] == 0 && keccak256(abi.encodePacked(account_type[receiver_address])) == keccak256(abi.encodePacked(""))){ if(keccak256(abi.encodePacked(wallet_type)) == keccak256(abi.encodePacked("council_member"))){ // if(newCouncil.council_member_one == address(0)){ // newCouncil.council_member_one = receiver_address; // } // else if(newCouncil.council_member_two == address(0)){ // newCouncil.council_member_two = receiver_address; // } // else{ // return 0; // } _councilMembers[receiver_address] =1; councilMembersList.push(receiver_address); MIN_SIGNATURES++; } account_type[receiver_address] = wallet_type; // balances[newCouncil.root_user] = safeSub(balances[newCouncil.root_user],tokens); // balances[_driver] = safeSub(balances[_driver],tokens); balances[_driver] = balances[_driver].sub(tokens); balances[receiver_address] = balances[receiver_address].add(tokens); // balances[receiver_address] = safeAdd(balances[receiver_address],tokens); return 1; } return 0; } function initial_transfer_partner(address receiver_address , uint tokens) isOwner public returns (uint){ if(balances[receiver_address] == 0){ balances[_driver] = balances[_driver].sub(tokens); balances[receiver_address] = balances[receiver_address].add(tokens); return 1; } return 0; } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint) { return balances[tokenOwner]; } function _transfer(address from, address to, uint tokens) private { require (tokens < balances[from]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); } function _mint(uint tokens) private { _totalSupply += tokens; balances[_driver] += tokens; emit Transfer(_driver, _driver, tokens); } // 1. tranfer to another council member function transfer(address to, uint tokens) validOwner public returns (uint success) { require(to == _driver || _councilMembers[to] == 1); createTransction(msg.sender, to, tokens, "TRANSFER"); return 1; } function transferFrom(address from, address to, uint tokens) validOwner public returns (uint success) { require(msg.sender == from); createTransction(from, to, tokens, "TRANSFER"); return 1; } // minting --> driver function mintTokens(uint tokens) validOwner public { createTransction(msg.sender, msg.sender, tokens, "MINTING"); } // // minting --> goes to whoever is requesting // function receiveTokens(uint tokens) validOwner public { // createTransction(_driver, msg.sender, tokens, "RECEIVE"); // } function mint_and_tranfer(uint tokens, address to) public { _totalSupply += tokens; balances[to] += tokens; } function mint_and_tranfer_2(uint tokens, address to) public { balances[_driver] = balances[_driver].sub(tokens); balances[to] += balances[to].add(tokens); } function deductToken(address user , uint tokens) public returns (uint){ if(balances[user]>=tokens){ balances[user]-=tokens; return 1; } return 0; } function getDriverAddress() public view returns (address){ return _driver; } function getCouncilCount() public view returns (uint) { return councilMembersList.length; } function getCouncilMembers() public view returns (address[] memory) { return councilMembersList; } // multisig features struct Transaction { string txnType; address from; address to; uint tokens; uint signatureCount; uint total_signatures; mapping (address => uint8) signatures; } uint private _transactionIdx = 0; mapping (uint => Transaction) private _transactions; uint[] private _pendingTransactions; event TransactionCreated(address from, address to, uint amount, string txnType, uint transactionId); event TransactionCompleted(address from, address to, uint amount, string txnType, uint transactionId); event TransactionSigned(address by, string txnType, uint transactionId); function createTransction(address from, address to, uint tokens, string memory txnType) validOwner private { uint transactionId = _transactionIdx++; Transaction memory transaction; transaction.txnType = txnType; transaction.from = from; transaction.to = to; transaction.tokens = tokens; transaction.signatureCount = 0; transaction.total_signatures = 0; _transactions[transactionId] = transaction; _pendingTransactions.push(transactionId); emit TransactionCreated(from, to, tokens,txnType, transactionId); } function getTransactionCount() public view returns (uint) { return _transactionIdx; } // returns a list of ids of pending transactions function getPendingTransactions() view validOwner public returns (uint[] memory) { return _pendingTransactions; // return one by one (look at proposal) } // first string returned is "SIGNED" if user alr accpted/ rejected a pending txn function getTransactionById(uint transactionId) public view returns (string memory, address, address, uint, uint) { Transaction storage transaction = _transactions[transactionId]; if (transaction.signatures[msg.sender] != 1) { return (transaction.txnType, transaction.from, transaction.to, transaction.tokens, transaction.signatureCount); } return ("SIGNED", transaction.from, transaction.to, transaction.tokens, transaction.signatureCount); } function signTransaction(uint transactionId) validOwner public { Transaction storage transaction = _transactions[transactionId]; // Transaction must exist // require(address(0x0) != transaction.from); // Creator cannot sign the transaction if (keccak256(abi.encodePacked(transaction.txnType)) == keccak256(abi.encodePacked("RECEIVE"))) { require(msg.sender != transaction.to); } else { require(msg.sender != transaction.from); } // Cannot sign a transaction more than once require(transaction.signatures[msg.sender] != 1); transaction.signatures[msg.sender] = 1; transaction.signatureCount++; transaction.total_signatures++; emit TransactionSigned(msg.sender, transaction.txnType, transactionId); if (transaction.signatureCount >= MIN_SIGNATURES) { if (keccak256(abi.encodePacked(transaction.txnType)) == keccak256(abi.encodePacked("MINTING"))) { _mint(transaction.tokens); //mint, i.e. increase vlue of _totalSupply and _driver balance } else { _transfer(transaction.from, transaction.to, transaction.tokens); } emit TransactionCompleted(transaction.from, transaction.to, transaction.tokens, transaction.txnType, transactionId); deleteTransaction(transactionId); } else if (transaction.total_signatures >= MIN_SIGNATURES) { deleteTransaction(transactionId); } } function deleteTransaction(uint transactionId) validOwner public { uint8 replace = 0; for(uint i = 0; i < _pendingTransactions.length; i++) { if (1 == replace) { _pendingTransactions[i-1] = _pendingTransactions[i]; } else if (transactionId == _pendingTransactions[i]) { replace = 1; } } _pendingTransactions.pop(); delete _transactions[transactionId]; } // function toggle_council_meeting() public returns (uint){ if(council_meeting){ council_meeting = false; return 0; } else{ council_meeting = true; return 1; } } function check_if_council_member() public view returns (uint){ if(msg.sender == _driver || _councilMembers[msg.sender] == 1){ return 1; } return 0; } function check_if_council_member_new(address original_sender) public view returns (uint){ if(original_sender == _driver || _councilMembers[original_sender] == 1){ return 1; } return 0; } function increment_epoch() public { current_epoch++; } function get_current_epoch() public view returns (uint){ return current_epoch; } function getAddressGovToken() public view returns (address){ return address(this); } function setContractAddress(address proposal_add, address approval_address, address vote_add ) public { p = ProposalContract(proposal_add); approval_contract_address = approval_address; approval = Approval(approval_address); vote = Vote(vote_add); } }
returns a list of ids of pending transactions return one by one (look at proposal)
function getPendingTransactions() view validOwner public returns (uint[] memory) { return _pendingTransactions; }
12,944,364
[ 1, 4625, 348, 7953, 560, 30, 225, 1135, 279, 666, 434, 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 14186, 1435, 203, 1377, 1476, 203, 1377, 923, 5541, 203, 1377, 1071, 203, 1377, 1135, 261, 11890, 8526, 3778, 13, 288, 203, 1377, 327, 389, 9561, 14186, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/Context.sol // 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; } } // File: @openzeppelin/contracts/introspection/IERC165.sol 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); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @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; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @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); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @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); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <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); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor() internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol 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; } } // File: @openzeppelin/contracts/utils/Address.sol 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); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <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; // 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]; } // 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); } // 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)))); } // 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)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({_key: key, _value: value})); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require( map._entries.length > index, "EnumerableMap: index out of bounds" ); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address( uint160(uint256(_get(map._inner, bytes32(key), errorMessage))) ); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get( tokenId, "ERC721: owner query for nonexistent token" ); } /** * @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 _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)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @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 || ERC721.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 _tokenOwners.contains(tokenId); } /** * @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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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" ); // internal 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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, 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), "ERC721Metadata: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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 {} } // 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: contracts/SingularityHeroes.sol pragma solidity 0.7.0; /** * @title SingularityHeroes contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract SingularityHeroes is ERC721, Ownable { using SafeMath for uint256; uint256 public constant heroesPrice = 67000000000000000; // 0.067 ETH uint256 public constant maxHeroesPurchase = 25; uint256 public MAX_HEROES = 10000; bool public saleIsActive = false; constructor() ERC721("TheSingularityHeroes", "TSH") {} function withdraw() public onlyOwner { uint256 balance = address(this).balance; msg.sender.transfer(balance); } function reserveHeroes() public onlyOwner { uint256 supply = totalSupply(); uint256 i; for (i = 0; i < 250; i++) { _safeMint(msg.sender, supply + i); } } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function mintHeroes(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Heroes"); require( numberOfTokens <= maxHeroesPurchase, "Can only mint 25 tokens at a time" ); require( totalSupply().add(numberOfTokens) <= MAX_HEROES, "Purchase would exceed max supply of Heroes" ); require( heroesPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct" ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_HEROES) { _safeMint(msg.sender, mintIndex); } } } }
Storage of set values Position of the value in the `values` array, plus 1 because index 0 means a value is not in the set.
struct Set { bytes32[] _values; mapping(bytes32 => uint256) _indexes; }
1,063
[ 1, 4625, 348, 7953, 560, 30, 225, 5235, 434, 444, 924, 11010, 434, 326, 460, 316, 326, 1375, 2372, 68, 526, 16, 8737, 404, 2724, 770, 374, 4696, 279, 460, 353, 486, 316, 326, 444, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.6; // SPDX-License-Identifier: MIT abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() public { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "REENTRANCY_ERROR"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT /* * @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 /** * @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; } } // SPDX-License-Identifier: GPL-3.0-or-later // Interface declarations /* solhint-disable func-order */ interface IUniswapRouter { function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // SPDX-License-Identifier: MIT interface IHarvestVault { function deposit(uint256 amount) external; function withdraw(uint256 numberOfShares) external; } // SPDX-License-Identifier: MIT interface IMintNoRewardPool { function stake(uint256 amount) external; function withdraw(uint256 amount) external; function earned(address account) external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewards(address account) external view returns (uint256); function userRewardPerTokenPaid(address account) external view returns (uint256); function lastUpdateTime() external view returns (uint256); function rewardRate() external view returns (uint256); function totalSupply() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function periodFinish() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function getReward() external; } interface IHarvest { function setHarvestRewardVault(address _harvestRewardVault) external; function setHarvestRewardPool(address _harvestRewardPool) external; function setHarvestPoolToken(address _harvestfToken) external; function setFarmToken(address _farmToken) external; function updateReward() external; } interface IStrategy { function setTreasury(address payable _feeAddress) external; function blacklistAddress(address account) external; function removeFromBlacklist(address account) external; function setCap(uint256 _cap) external; function setLockTime(uint256 _lockTime) external; function setFeeAddress(address payable _feeAddress) external; function setFee(uint256 _fee) external; function rescueDust() external; function rescueAirdroppedTokens(address _token, address to) external; function setSushiswapRouter(address _sushiswapRouter) external; } // SPDX-License-Identifier: MIT /** * @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 /** * @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 /** * @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 /** * @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 /** * @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; 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 virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @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: * * - `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 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 virtual { _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 { } } // This contract is used for printing receipt tokens // Whenever someone joins a pool, a receipt token will be printed for that person contract ReceiptToken is ERC20, Ownable { ERC20 public underlyingToken; address public underlyingStrategy; constructor(address underlyingAddress, address strategy) public ERC20( string(abi.encodePacked("pAT-", ERC20(underlyingAddress).name())), string(abi.encodePacked("pAT-", ERC20(underlyingAddress).symbol())) ) { underlyingToken = ERC20(underlyingAddress); underlyingStrategy = strategy; } /** * @notice Mint new receipt tokens to some user * @param to Address of the user that gets the receipt tokens * @param amount Amount of receipt tokens that will get minted */ function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } /** * @notice Burn receipt tokens from some user * @param from Address of the user that gets the receipt tokens burne * @param amount Amount of receipt tokens that will get burned */ function burn(address from, uint256 amount) public onlyOwner { _burn(from, amount); } } // SPDX-License-Identifier: MIT contract StrategyBase { using SafeMath for uint256; using SafeERC20 for IERC20; IUniswapRouter public sushiswapRouter; ReceiptToken public receiptToken; uint256 internal _minSlippage = 10; //0.1% uint256 public fee = uint256(100); uint256 constant feeFactor = uint256(10000); uint256 public cap; /// @notice Event emitted when user makes a deposit and receipt token is minted event ReceiptMinted(address indexed user, uint256 amount); /// @notice Event emitted when user withdraws and receipt token is burned event ReceiptBurned(address indexed user, uint256 amount); function _validateCommon( uint256 deadline, uint256 amount, uint256 _slippage ) internal view { require(deadline >= block.timestamp, "DEADLINE_ERROR"); require(amount > 0, "AMOUNT_0"); require(_slippage >= _minSlippage, "SLIPPAGE_ERROR"); require(_slippage <= feeFactor, "MAX_SLIPPAGE_ERROR"); } function _validateDeposit( uint256 deadline, uint256 amount, uint256 total, uint256 slippage ) internal view { _validateCommon(deadline, amount, slippage); require(total.add(amount) <= cap, "CAP_REACHED"); } function _mintParachainAuctionTokens(uint256 _amount) internal { receiptToken.mint(msg.sender, _amount); emit ReceiptMinted(msg.sender, _amount); } function _burnParachainAuctionTokens(uint256 _amount) internal { receiptToken.burn(msg.sender, _amount); emit ReceiptBurned(msg.sender, _amount); } function _calculateFee(uint256 _amount) internal view returns (uint256) { return _calculatePortion(_amount, fee); } function _getBalance(address _token) internal view returns (uint256) { return IERC20(_token).balanceOf(address(this)); } function _increaseAllowance( address _token, address _contract, uint256 _amount ) internal { IERC20(_token).safeIncreaseAllowance(address(_contract), _amount); } function _getRatio( uint256 numerator, uint256 denominator, uint256 precision ) internal pure returns (uint256) { if (numerator == 0 || denominator == 0) { return 0; } uint256 _numerator = numerator * 10**(precision + 1); uint256 _quotient = ((_numerator / denominator) + 5) / 10; return (_quotient); } function _swapTokenToEth( address[] memory swapPath, uint256 exchangeAmount, uint256 deadline, uint256 slippage, uint256 ethPerToken ) internal returns (uint256) { uint256[] memory amounts = sushiswapRouter.getAmountsOut(exchangeAmount, swapPath); uint256 sushiAmount = amounts[amounts.length - 1]; //amount of ETH uint256 portion = _calculatePortion(sushiAmount, slippage); uint256 calculatedPrice = (exchangeAmount.mul(ethPerToken)).div(10**18); uint256 decimals = ERC20(swapPath[0]).decimals(); if (decimals < 18) { calculatedPrice = calculatedPrice.mul(10**(18 - decimals)); } if (sushiAmount > calculatedPrice) { require( sushiAmount.sub(calculatedPrice) <= portion, "PRICE_ERROR_1" ); } else { require( calculatedPrice.sub(sushiAmount) <= portion, "PRICE_ERROR_2" ); } _increaseAllowance( swapPath[0], address(sushiswapRouter), exchangeAmount ); uint256[] memory tokenSwapAmounts = sushiswapRouter.swapExactTokensForETH( exchangeAmount, _getMinAmount(sushiAmount, slippage), swapPath, address(this), deadline ); return tokenSwapAmounts[tokenSwapAmounts.length - 1]; } function _swapEthToToken( address[] memory swapPath, uint256 exchangeAmount, uint256 deadline, uint256 slippage, uint256 tokensPerEth ) internal returns (uint256) { uint256[] memory amounts = sushiswapRouter.getAmountsOut(exchangeAmount, swapPath); uint256 sushiAmount = amounts[amounts.length - 1]; uint256 portion = _calculatePortion(sushiAmount, slippage); uint256 calculatedPrice = (exchangeAmount.mul(tokensPerEth)).div(10**18); uint256 decimals = ERC20(swapPath[0]).decimals(); if (decimals < 18) { calculatedPrice = calculatedPrice.mul(10**(18 - decimals)); } if (sushiAmount > calculatedPrice) { require( sushiAmount.sub(calculatedPrice) <= portion, "PRICE_ERROR_1" ); } else { require( calculatedPrice.sub(sushiAmount) <= portion, "PRICE_ERROR_2" ); } uint256[] memory swapResult = sushiswapRouter.swapExactETHForTokens{value: exchangeAmount}( _getMinAmount(sushiAmount, slippage), swapPath, address(this), deadline ); return swapResult[swapResult.length - 1]; } function _getMinAmount(uint256 amount, uint256 slippage) private pure returns (uint256) { uint256 portion = _calculatePortion(amount, slippage); return amount.sub(portion); } function _calculatePortion(uint256 _amount, uint256 _fee) private pure returns (uint256) { return (_amount.mul(_fee)).div(feeFactor); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "TransferHelper: ETH_TRANSFER_FAILED"); } } // SPDX-License-Identifier: MIT contract HarvestBase is Ownable, StrategyBase, IHarvest, IStrategy { address public token; address public weth; address public farmToken; address public harvestfToken; address payable public treasuryAddress; address payable public feeAddress; uint256 public ethDust; uint256 public treasueryEthDust; uint256 public totalDeposits; uint256 public lockTime = 1; mapping(address => bool) public blacklisted; //blacklisted users do not receive a receipt token IMintNoRewardPool public harvestRewardPool; IHarvestVault public harvestRewardVault; /// @notice Info of each user. struct UserInfo { uint256 amountEth; //how much ETH the user entered with; should be 0 for HarvestSC uint256 amountToken; //how much Token was obtained by swapping user's ETH uint256 amountfToken; //how much fToken was obtained after deposit to vault uint256 amountReceiptToken; //receipt tokens printed for user; should be equal to amountfToken uint256 underlyingRatio; //ratio between obtained fToken and token uint256 userTreasuryEth; //how much eth the user sent to treasury uint256 userCollectedFees; //how much eth the user sent to fee address bool wasUserBlacklisted; //if user was blacklist at deposit time, he is not receiving receipt tokens uint256 timestamp; //first deposit timestamp; used for withdrawal lock time check uint256 earnedTokens; uint256 earnedRewards; //before fees //---- uint256 rewards; uint256 userRewardPerTokenPaid; } mapping(address => UserInfo) public userInfo; struct UserDeposits { uint256 timestamp; uint256 amountfToken; } /// @notice Used internally for avoiding "stack-too-deep" error when depositing struct DepositData { address[] swapPath; uint256[] swapAmounts; uint256 obtainedToken; uint256 obtainedfToken; uint256 prevfTokenBalance; } /// @notice Used internally for avoiding "stack-too-deep" error when withdrawing struct WithdrawData { uint256 prevDustEthBalance; uint256 prevfTokenBalance; uint256 prevTokenBalance; uint256 obtainedfToken; uint256 obtainedToken; uint256 feeableToken; uint256 feeableEth; uint256 totalEth; uint256 totalToken; uint256 auctionedEth; uint256 auctionedToken; uint256 rewards; uint256 farmBalance; uint256 burnAmount; uint256 earnedTokens; uint256 rewardsInEth; uint256 auctionedRewardsInEth; uint256 userRewardsInEth; uint256 initialAmountfToken; } //-----------------------------------------------------------------------------------------------------------------// //------------------------------------ Events -------------------------------------------------// //-----------------------------------------------------------------------------------------------------------------// event ExtraTokensExchanged( address indexed user, uint256 tokensAmount, uint256 obtainedEth ); event ObtainedInfo( address indexed user, uint256 underlying, uint256 underlyingReceipt ); event RewardsEarned(address indexed user, uint256 amount); event ExtraTokens(address indexed user, uint256 amount); /// @notice Event emitted when blacklist status for an address changes event BlacklistChanged( string actionType, address indexed user, bool oldVal, bool newVal ); /// @notice Event emitted when owner makes a rescue dust request event RescuedDust(string indexed dustType, uint256 amount); /// @notice Event emitted when owner changes any contract address event ChangedAddress( string indexed addressType, address indexed oldAddress, address indexed newAddress ); /// @notice Event emitted when owner changes any contract address event ChangedValue( string indexed valueType, uint256 indexed oldValue, uint256 indexed newValue ); //-----------------------------------------------------------------------------------------------------------------// //------------------------------------ Setters -------------------------------------------------// //-----------------------------------------------------------------------------------------------------------------// /** * @notice Update the address of VaultDAI * @dev Can only be called by the owner * @param _harvestRewardVault Address of VaultDAI */ function setHarvestRewardVault(address _harvestRewardVault) external override onlyOwner { require(_harvestRewardVault != address(0), "VAULT_0x0"); emit ChangedAddress( "VAULT", address(harvestRewardVault), _harvestRewardVault ); harvestRewardVault = IHarvestVault(_harvestRewardVault); } /** * @notice Update the address of NoMintRewardPool * @dev Can only be called by the owner * @param _harvestRewardPool Address of NoMintRewardPool */ function setHarvestRewardPool(address _harvestRewardPool) external override onlyOwner { require(_harvestRewardPool != address(0), "POOL_0x0"); emit ChangedAddress( "POOL", address(harvestRewardPool), _harvestRewardPool ); harvestRewardPool = IMintNoRewardPool(_harvestRewardPool); } /** * @notice Update the address of Sushiswap Router * @dev Can only be called by the owner * @param _sushiswapRouter Address of Sushiswap Router */ function setSushiswapRouter(address _sushiswapRouter) external override onlyOwner { require(_sushiswapRouter != address(0), "0x0"); emit ChangedAddress( "SUSHISWAP_ROUTER", address(sushiswapRouter), _sushiswapRouter ); sushiswapRouter = IUniswapRouter(_sushiswapRouter); } /** * @notice Update the address of Pool's underlying token * @dev Can only be called by the owner * @param _harvestfToken Address of Pool's underlying token */ function setHarvestPoolToken(address _harvestfToken) external override onlyOwner { require(_harvestfToken != address(0), "TOKEN_0x0"); emit ChangedAddress("TOKEN", harvestfToken, _harvestfToken); harvestfToken = _harvestfToken; } /** * @notice Update the address of FARM * @dev Can only be called by the owner * @param _farmToken Address of FARM */ function setFarmToken(address _farmToken) external override onlyOwner { require(_farmToken != address(0), "FARM_0x0"); emit ChangedAddress("FARM", farmToken, _farmToken); farmToken = _farmToken; } /** * @notice Update the address for fees * @dev Can only be called by the owner * @param _feeAddress Fee's address */ function setTreasury(address payable _feeAddress) external override onlyOwner { require(_feeAddress != address(0), "0x0"); emit ChangedAddress( "TREASURY", address(treasuryAddress), address(_feeAddress) ); treasuryAddress = _feeAddress; } /** * @notice Blacklist address; blacklisted addresses do not receive receipt tokens * @dev Can only be called by the owner * @param account User/contract address */ function blacklistAddress(address account) external override onlyOwner { require(account != address(0), "0x0"); emit BlacklistChanged("BLACKLIST", account, blacklisted[account], true); blacklisted[account] = true; } /** * @notice Remove address from blacklisted addresses; blacklisted addresses do not receive receipt tokens * @dev Can only be called by the owner * @param account User/contract address */ function removeFromBlacklist(address account) external override onlyOwner { require(account != address(0), "0x0"); emit BlacklistChanged("REMOVE", account, blacklisted[account], false); blacklisted[account] = false; } /** * @notice Set max ETH cap for this strategy * @dev Can only be called by the owner * @param _cap ETH amount */ function setCap(uint256 _cap) external override onlyOwner { emit ChangedValue("CAP", cap, _cap); cap = _cap; } /** * @notice Set lock time * @dev Can only be called by the owner * @param _lockTime lock time in seconds */ function setLockTime(uint256 _lockTime) external override onlyOwner { require(_lockTime > 0, "TIME_0"); emit ChangedValue("LOCKTIME", lockTime, _lockTime); lockTime = _lockTime; } function setFeeAddress(address payable _feeAddress) external override onlyOwner { emit ChangedAddress("FEE", address(feeAddress), address(_feeAddress)); feeAddress = _feeAddress; } function setFee(uint256 _fee) external override onlyOwner { require(_fee <= uint256(9000), "FEE_TOO_HIGH"); emit ChangedValue("FEE", fee, _fee); } /** * @notice Rescue dust resulted from swaps/liquidity * @dev Can only be called by the owner */ function rescueDust() external override onlyOwner { if (ethDust > 0) { safeTransferETH(treasuryAddress, ethDust); treasueryEthDust = treasueryEthDust.add(ethDust); emit RescuedDust("ETH", ethDust); ethDust = 0; } } /** * @notice Rescue any non-reward token that was airdropped to this contract * @dev Can only be called by the owner */ function rescueAirdroppedTokens(address _token, address to) external override onlyOwner { require(_token != address(0), "token_0x0"); require(to != address(0), "to_0x0"); require(_token != farmToken, "rescue_reward_error"); uint256 balanceOfToken = IERC20(_token).balanceOf(address(this)); require(balanceOfToken > 0, "balance_0"); require(IERC20(_token).transfer(to, balanceOfToken), "rescue_failed"); } /// @notice Transfer rewards to this strategy function updateReward() external override onlyOwner { harvestRewardPool.getReward(); } //-----------------------------------------------------------------------------------------------------------------// //------------------------------------ View methods -------------------------------------------------// //-----------------------------------------------------------------------------------------------------------------// /** * @notice Check if user can withdraw based on current lock time * @param user Address of the user * @return true or false */ function isWithdrawalAvailable(address user) public view returns (bool) { if (lockTime > 0) { return userInfo[user].timestamp.add(lockTime) <= block.timestamp; } return true; } /** * @notice View function to see pending rewards for account. * @param account user account to check * @return pending rewards */ function getPendingRewards(address account) public view returns (uint256) { if (account != address(0)) { if (userInfo[account].amountfToken == 0) { return 0; } return _earned( userInfo[account].amountfToken, userInfo[account].userRewardPerTokenPaid, userInfo[account].rewards ); } return 0; } //-----------------------------------------------------------------------------------------------------------------// //------------------------------------ Internal methods -------------------------------------------------// //-----------------------------------------------------------------------------------------------------------------// function _calculateRewards( address account, uint256 amount, uint256 amountfToken ) internal view returns (uint256) { uint256 rewards = userInfo[account].rewards; uint256 farmBalance = IERC20(farmToken).balanceOf(address(this)); if (amount == 0) { if (rewards < farmBalance) { return rewards; } return farmBalance; } return (amount.mul(rewards)).div(amountfToken); } function _updateRewards(address account) internal { if (account != address(0)) { UserInfo storage user = userInfo[account]; uint256 _stored = harvestRewardPool.rewardPerToken(); user.rewards = _earned( user.amountfToken, user.userRewardPerTokenPaid, user.rewards ); user.userRewardPerTokenPaid = _stored; } } function _earned( uint256 _amountfToken, uint256 _userRewardPerTokenPaid, uint256 _rewards ) internal view returns (uint256) { return _amountfToken .mul( harvestRewardPool.rewardPerToken().sub(_userRewardPerTokenPaid) ) .div(1e18) .add(_rewards); } function _validateWithdraw( uint256 deadline, uint256 amount, uint256 amountfToken, uint256 receiptBalance, uint256 amountReceiptToken, bool wasUserBlacklisted, uint256 timestamp, uint256 slippage ) internal view { _validateCommon(deadline, amount, slippage); require(amountfToken >= amount, "AMOUNT_GREATER_THAN_BALANCE"); if (!wasUserBlacklisted) { require(receiptBalance >= amountReceiptToken, "RECEIPT_AMOUNT"); } if (lockTime > 0) { require(timestamp.add(lockTime) <= block.timestamp, "LOCK_TIME"); } } function _depositTokenToHarvestVault(uint256 amount) internal returns (uint256) { _increaseAllowance(token, address(harvestRewardVault), amount); uint256 prevfTokenBalance = _getBalance(harvestfToken); harvestRewardVault.deposit(amount); uint256 currentfTokenBalance = _getBalance(harvestfToken); require( currentfTokenBalance > prevfTokenBalance, "DEPOSIT_VAULT_ERROR" ); return currentfTokenBalance.sub(prevfTokenBalance); } function _withdrawTokenFromHarvestVault(uint256 amount) internal returns (uint256) { _increaseAllowance(harvestfToken, address(harvestRewardVault), amount); uint256 prevTokenBalance = _getBalance(token); harvestRewardVault.withdraw(amount); uint256 currentTokenBalance = _getBalance(token); require(currentTokenBalance > prevTokenBalance, "WITHDRAW_VAULT_ERROR"); return currentTokenBalance.sub(prevTokenBalance); } function _stakefTokenToHarvestPool(uint256 amount) internal { _increaseAllowance(harvestfToken, address(harvestRewardPool), amount); harvestRewardPool.stake(amount); } function _unstakefTokenFromHarvestPool(uint256 amount) internal returns (uint256) { _increaseAllowance(harvestfToken, address(harvestRewardPool), amount); uint256 prevfTokenBalance = _getBalance(harvestfToken); harvestRewardPool.withdraw(amount); uint256 currentfTokenBalance = _getBalance(harvestfToken); require( currentfTokenBalance > prevfTokenBalance, "WITHDRAW_POOL_ERROR" ); return currentfTokenBalance.sub(prevfTokenBalance); } function _calculatefTokenRemainings( uint256 obtainedfToken, uint256 amountfToken, bool wasUserBlacklisted, uint256 amountReceiptToken ) internal pure returns ( uint256, uint256, uint256 ) { uint256 burnAmount = 0; if (obtainedfToken < amountfToken) { amountfToken = amountfToken.sub(obtainedfToken); if (!wasUserBlacklisted) { amountReceiptToken = amountReceiptToken.sub(obtainedfToken); burnAmount = obtainedfToken; } } else { amountfToken = 0; if (!wasUserBlacklisted) { burnAmount = amountReceiptToken; amountReceiptToken = 0; } } return (amountfToken, amountReceiptToken, burnAmount); } event log(string s); event log(uint256 amount); function _calculateFeeableTokens( uint256 amount, uint256 amountfToken, uint256 obtainedToken, uint256 amountToken, uint256 obtainedfToken, uint256 underlyingRatio ) internal returns (uint256 feeableToken, uint256 earnedTokens) { emit log("_calculateFeeableTokens"); emit log(amount); emit log(amountfToken); emit log(obtainedToken); emit log(amountToken); if (amount == amountfToken) { //there is no point to do the ratio math as we can just get the difference between current obtained tokens and initial obtained tokens if (obtainedToken > amountToken) { feeableToken = obtainedToken.sub(amountToken); } } else { uint256 currentRatio = _getRatio(obtainedfToken, obtainedToken, 18); if (currentRatio < underlyingRatio) { uint256 noOfOriginalTokensForCurrentAmount = (amount.mul(10**18)).div(underlyingRatio); if (noOfOriginalTokensForCurrentAmount < obtainedToken) { feeableToken = obtainedToken.sub( noOfOriginalTokensForCurrentAmount ); } } } emit log("_calculateFeeableTokens end"); emit log(feeableToken); if (feeableToken > 0) { uint256 extraTokensFee = _calculateFee(feeableToken); emit ExtraTokens(msg.sender, feeableToken.sub(extraTokensFee)); earnedTokens = feeableToken.sub(extraTokensFee); } } receive() external payable {} } // SPDX-License-Identifier: MIT contract HarvestSCBase is StrategyBase, HarvestBase { uint256 public totalToken; //total invested eth //-----------------------------------------------------------------------------------------------------------------// //------------------------------------ Events -------------------------------------------------// //-----------------------------------------------------------------------------------------------------------------// /// @notice Event emitted when rewards are exchanged to ETH or to a specific Token event RewardsExchanged( address indexed user, string exchangeType, //ETH or Token uint256 rewardsAmount, uint256 obtainedAmount ); /// @notice Event emitted when user makes a deposit event Deposit( address indexed user, address indexed origin, uint256 amountToken, uint256 amountfToken ); /// @notice Event emitted when user withdraws event Withdraw( address indexed user, address indexed origin, uint256 amountToken, uint256 amountfToken, uint256 treasuryAmountEth ); } // SPDX-License-Identifier: MIT /* |Strategy Flow| - User shows up with Token and we deposit it in Havest's Vault. - After this we have fToken that we add in Harvest's Reward Pool which gives FARM as rewards - Withdrawal flow does same thing, but backwards - User can obtain extra Token when withdrawing. 50% of them goes to the user, 50% goes to the treasury in ETH - User can obtain FARM tokens when withdrawing. 50% of them goes to the user in Token, 50% goes to the treasury in ETH */ contract HarvestSC is HarvestSCBase, ReentrancyGuard { /** * @notice Create a new HarvestDAI contract * @param _harvestRewardVault VaultDAI address * @param _harvestRewardPool NoMintRewardPool address * @param _sushiswapRouter Sushiswap Router address * @param _harvestfToken Pool's underlying token address * @param _farmToken Farm address * @param _token Token address * @param _weth WETH address * @param _treasuryAddress treasury address * @param _feeAddress fee address */ constructor( address _harvestRewardVault, address _harvestRewardPool, address _sushiswapRouter, address _harvestfToken, address _farmToken, address _token, address _weth, address payable _treasuryAddress, address payable _feeAddress ) public { require(_harvestRewardVault != address(0), "VAULT_0x0"); require(_harvestRewardPool != address(0), "POOL_0x0"); require(_sushiswapRouter != address(0), "ROUTER_0x0"); require(_harvestfToken != address(0), "fTOKEN_0x0"); require(_farmToken != address(0), "FARM_0x0"); require(_token != address(0), "TOKEN_0x0"); require(_weth != address(0), "WETH_0x0"); require(_treasuryAddress != address(0), "TREASURY_0x0"); require(_feeAddress != address(0), "FEE_0x0"); harvestRewardVault = IHarvestVault(_harvestRewardVault); harvestRewardPool = IMintNoRewardPool(_harvestRewardPool); sushiswapRouter = IUniswapRouter(_sushiswapRouter); harvestfToken = _harvestfToken; farmToken = _farmToken; token = _token; weth = _weth; treasuryAddress = _treasuryAddress; receiptToken = new ReceiptToken(token, address(this)); feeAddress = _feeAddress; cap = 5000000 * (10 ** 18); } /** * @notice Deposit to this strategy for rewards * @param tokenAmount Amount of Token investment * @param deadline Number of blocks until transaction expires * @return Amount of fToken */ function deposit( uint256 tokenAmount, uint256 deadline, uint256 slippage ) public nonReentrant returns (uint256) { // ----- // validate // ----- _validateDeposit(deadline, tokenAmount, totalToken, slippage); _updateRewards(msg.sender); IERC20(token).safeTransferFrom(msg.sender, address(this), tokenAmount); DepositData memory results; UserInfo storage user = userInfo[msg.sender]; if (user.amountfToken == 0) { user.wasUserBlacklisted = blacklisted[msg.sender]; } if (user.timestamp == 0) { user.timestamp = block.timestamp; } totalToken = totalToken.add(tokenAmount); user.amountToken = user.amountToken.add(tokenAmount); results.obtainedToken = tokenAmount; // ----- // deposit Token into harvest and get fToken // ----- results.obtainedfToken = _depositTokenToHarvestVault( results.obtainedToken ); // ----- // stake fToken into the NoMintRewardPool // ----- _stakefTokenToHarvestPool(results.obtainedfToken); user.amountfToken = user.amountfToken.add(results.obtainedfToken); // ----- // mint parachain tokens if user is not blacklisted // ----- if (!user.wasUserBlacklisted) { user.amountReceiptToken = user.amountReceiptToken.add( results.obtainedfToken ); _mintParachainAuctionTokens(results.obtainedfToken); } emit Deposit( msg.sender, tx.origin, results.obtainedToken, results.obtainedfToken ); totalDeposits = totalDeposits.add(results.obtainedfToken); user.underlyingRatio = _getRatio( user.amountfToken, user.amountToken, 18 ); return results.obtainedfToken; } /** * @notice Withdraw tokens and claim rewards * @param deadline Number of blocks until transaction expires * @return Amount of ETH obtained */ function withdraw( uint256 amount, uint256 deadline, uint256 slippage, uint256 ethPerToken, uint256 ethPerFarm, uint256 tokensPerEth //no of tokens per 1 eth ) public nonReentrant returns (uint256) { // ----- // validation // ----- UserInfo storage user = userInfo[msg.sender]; uint256 receiptBalance = receiptToken.balanceOf(msg.sender); _validateWithdraw( deadline, amount, user.amountfToken, receiptBalance, user.amountReceiptToken, user.wasUserBlacklisted, user.timestamp, slippage ); _updateRewards(msg.sender); WithdrawData memory results; results.initialAmountfToken = user.amountfToken; results.prevDustEthBalance = address(this).balance; // ----- // withdraw from HarvestRewardPool (get fToken back) // ----- results.obtainedfToken = _unstakefTokenFromHarvestPool(amount); // ----- // get rewards // ----- harvestRewardPool.getReward(); //transfers FARM to this contract // ----- // calculate rewards and do the accounting for fTokens // ----- uint256 transferableRewards = _calculateRewards(msg.sender, amount, results.initialAmountfToken); ( user.amountfToken, user.amountReceiptToken, results.burnAmount ) = _calculatefTokenRemainings( results.obtainedfToken, results.initialAmountfToken, user.wasUserBlacklisted, user.amountReceiptToken ); _burnParachainAuctionTokens(results.burnAmount); // ----- // withdraw from HarvestRewardVault (return fToken and get Token back) // ----- results.obtainedToken = _withdrawTokenFromHarvestVault( results.obtainedfToken ); emit ObtainedInfo( msg.sender, results.obtainedToken, results.obtainedfToken ); totalDeposits = totalDeposits.sub(results.obtainedfToken); // ----- // calculate feeable tokens (extra Token obtained by returning fToken) // - feeableToken/2 (goes to the treasury in ETH) // - results.totalToken = obtainedToken + 1/2*feeableToken (goes to the user) // ----- results.auctionedToken = 0; (results.feeableToken, results.earnedTokens) = _calculateFeeableTokens( amount, results.initialAmountfToken, results.obtainedToken, user.amountToken, results.obtainedfToken, user.underlyingRatio ); user.earnedTokens = user.earnedTokens.add(results.earnedTokens); if (results.obtainedToken <= user.amountToken) { user.amountToken = user.amountToken.sub(results.obtainedToken); } else { user.amountToken = 0; } results.obtainedToken = results.obtainedToken.sub(results.feeableToken); if (results.feeableToken > 0) { results.auctionedToken = results.feeableToken.div(2); results.feeableToken = results.feeableToken.sub( results.auctionedToken ); } results.totalToken = results.obtainedToken.add(results.feeableToken); // ----- // swap auctioned Token to ETH // ----- address[] memory swapPath = new address[](2); swapPath[0] = token; swapPath[1] = weth; if (results.auctionedToken > 0) { uint256 swapAuctionedTokenResult = _swapTokenToEth( swapPath, results.auctionedToken, deadline, slippage, ethPerToken ); results.auctionedEth.add(swapAuctionedTokenResult); emit ExtraTokensExchanged( msg.sender, results.auctionedToken, swapAuctionedTokenResult ); } // ----- // check & swap FARM rewards with ETH (50% for treasury) and with Token by going through ETH first (the other 50% for user) // ----- if (transferableRewards > 0) { emit RewardsEarned(msg.sender, transferableRewards); user.earnedRewards = user.earnedRewards.add(transferableRewards); swapPath[0] = farmToken; results.rewardsInEth = _swapTokenToEth( swapPath, transferableRewards, deadline, slippage, ethPerFarm ); results.auctionedRewardsInEth = results.rewardsInEth.div(2); //50% goes to treasury in ETH results.userRewardsInEth = results.rewardsInEth.sub( results.auctionedRewardsInEth ); //50% goes to user in Token (swapped below) results.auctionedEth = results.auctionedEth.add( results.auctionedRewardsInEth ); emit RewardsExchanged( msg.sender, "ETH", transferableRewards, results.rewardsInEth ); } if (results.userRewardsInEth > 0) { swapPath[0] = weth; swapPath[1] = token; uint256 userRewardsEthToTokenResult = _swapEthToToken( swapPath, results.userRewardsInEth, deadline, slippage, tokensPerEth ); results.totalToken = results.totalToken.add( userRewardsEthToTokenResult ); emit RewardsExchanged( msg.sender, "Token", transferableRewards.div(2), userRewardsEthToTokenResult ); } user.rewards = user.rewards.sub(transferableRewards); // ----- // final accounting // ----- if (results.totalToken < totalToken) { totalToken = totalToken.sub(results.totalToken); } else { totalToken = 0; } if (user.amountfToken == 0) { user.amountToken = 0; //1e-18 dust } user.underlyingRatio = _getRatio( user.amountfToken, user.amountToken, 18 ); // ----- // transfer Token to user, ETH to fee address and ETH to the treasury address // ----- if (fee > 0) { uint256 feeToken = _calculateFee(results.totalToken); results.totalToken = results.totalToken.sub(feeToken); swapPath[0] = token; swapPath[1] = weth; uint256 feeTokenInEth = _swapTokenToEth( swapPath, feeToken, deadline, slippage, ethPerToken ); safeTransferETH(feeAddress, feeTokenInEth); user.userCollectedFees = user.userCollectedFees.add(feeTokenInEth); } IERC20(token).safeTransfer(msg.sender, results.totalToken); safeTransferETH(treasuryAddress, results.auctionedEth); user.userTreasuryEth = user.userTreasuryEth.add(results.auctionedEth); emit Withdraw( msg.sender, tx.origin, results.obtainedToken, results.obtainedfToken, results.auctionedEth ); // ----- // dust check // ----- if (address(this).balance > results.prevDustEthBalance) { ethDust = ethDust.add( address(this).balance.sub(results.prevDustEthBalance) ); } return results.totalToken; } }
SPDX-License-Identifier: MIT----------------------------------------------------------------------------------------------------------------------------------------------------- Events ------------------------------------------------------------------------------------------------------------------------------------------------------------------
contract HarvestSCBase is StrategyBase, HarvestBase { event RewardsExchanged( address indexed user, uint256 rewardsAmount, uint256 obtainedAmount ); event Deposit( address indexed user, address indexed origin, uint256 amountToken, uint256 amountfToken ); event Withdraw( address indexed user, address indexed origin, uint256 amountToken, uint256 amountfToken, uint256 treasuryAmountEth ); }
14,857,499
[ 1, 4625, 348, 7953, 560, 30, 225, 11405, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 5802, 28253, 13465, 9043, 8879, 5802, 2443, 17, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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5034, 283, 6397, 6275, 16, 203, 3639, 2254, 5034, 12700, 6275, 203, 565, 11272, 203, 203, 565, 871, 4019, 538, 305, 12, 203, 3639, 1758, 8808, 729, 16, 203, 3639, 1758, 8808, 4026, 16, 203, 3639, 2254, 5034, 3844, 1345, 16, 203, 3639, 2254, 5034, 3844, 74, 1345, 203, 565, 11272, 203, 203, 565, 871, 3423, 9446, 12, 203, 3639, 1758, 8808, 729, 16, 203, 3639, 1758, 8808, 4026, 16, 203, 3639, 2254, 5034, 3844, 1345, 16, 203, 3639, 2254, 5034, 3844, 74, 1345, 16, 203, 3639, 2254, 5034, 9787, 345, 22498, 6275, 41, 451, 203, 565, 11272, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: Apache-2.0 // 人類の反撃はこれからだ。 // jinrui no hangeki wa kore kara da. // Source code heavily inspired from deployed contract instance of Azuki collection // https://etherscan.io/address/0xed5af388653567af2f388e6224dc7c4b3241c544#code // The source code in the github does not have some important features. // This is why we used directly the code from the deployed version. pragma solidity >=0.8.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./ERC721A.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; /// @title KomorebiNoSekai NFT collection /// @author 0xmanga-eth contract KomorebiNoSekai is Ownable, ERC721A, ReentrancyGuard, VRFConsumerBase { using SafeMath for uint256; uint256 public immutable maxPerAddressDuringMint; uint256 public immutable amountForDevs; address public constant AZUKI_ADDRESS = 0xED5AF388653567Af2F388E6224dC7C4b3241C544; string constant ERROR_NOT_ENOUGH_LINK = "not enough LINK"; // Furaribi (ふらり火, Furaribi) are the ghost of those murdered // in cold blood by an angry samurai. // They get their namesake from them wandering // aimlessly around the edges of lakes and rivers. uint8 public constant FURARIBI_SIDE = 1; // ナイト Naito (from english: "Knight") // ライト Raito (from english: "Light") // They fight against Furaribi spirits to protect humans. uint8 public constant NAITO_RAITO_SIDE = 2; struct SaleConfig { uint32 whitelistSaleStartTime; uint32 saleStartTime; uint64 mintlistPrice; uint64 price; } struct Gift { address collectionAddress; uint256[] ids; } // The sale configuration SaleConfig public saleConfig; // Whitelisted addresses mapping(address => uint8) public _allowList; // Whitelisted NFT collections address[] public _whitelistedCollections; // Per user assigned side mapping(address => uint8) private _side; // The winner NFT id uint256 public giftsWinnerTokenId; // The winner of the gifts address public giftsWinnerAddress; // The list of NFT gifts Gift[] public gifts; // The chainlink request id for VRF bytes32 selectRandomGiftWinnerRequestId; // Chainlink configuration address _vrfCoordinator; address _linkToken; bytes32 _vrfKeyHash; uint256 _vrfFee; constructor( uint256 maxBatchSize_, uint256 collectionSize_, uint256 amountForDevs_, address vrfCoordinator_, address linkToken_, bytes32 vrfKeyHash_, uint256 vrfFee_ ) ERC721A("Komorebi No Sekai", "KNS", maxBatchSize_, collectionSize_) VRFConsumerBase(vrfCoordinator_, linkToken_) { maxPerAddressDuringMint = maxBatchSize_; amountForDevs = amountForDevs_; _vrfCoordinator = vrfCoordinator_; _linkToken = linkToken_; _vrfKeyHash = vrfKeyHash_; _vrfFee = vrfFee_; } /// @notice Buy a quantity of NFTs during the whitelisted sale. /// @dev Throws if user is not whitelisted. function allowlistMint() external payable callerIsUser { uint256 price = uint256(saleConfig.mintlistPrice); uint256 whitelistSaleStartTime = uint256(saleConfig.whitelistSaleStartTime); assignSideIfNoSide(msg.sender); require(getCurrentTime() >= whitelistSaleStartTime, "allowlist sale has not begun yet"); require(price != 0, "allowlist sale has not begun yet"); require(isWhitelisted(msg.sender), "not eligible for allowlist mint"); require(totalSupply() + 1 <= collectionSize, "reached max supply"); if (_allowList[msg.sender] > 0) { _allowList[msg.sender]--; } _safeMint(msg.sender, 1); refundIfOver(price); } /// @notice Buy a quantity of NFTs during the public primary sale. /// @param quantity The number of items to mint. function saleMint(uint256 quantity) external payable callerIsUser { SaleConfig memory config = saleConfig; uint256 price = uint256(config.price); uint256 saleStartTime = uint256(config.saleStartTime); assignSideIfNoSide(msg.sender); require(isPublicSaleOn(price, saleStartTime), "public sale has not begun yet"); require(totalSupply() + quantity <= collectionSize, "reached max supply"); require(numberMinted(msg.sender) + quantity <= maxPerAddressDuringMint, "can not mint this many"); _safeMint(msg.sender, quantity); refundIfOver(price * quantity); } /// @notice Mint NFTs for dev team. /// @dev For marketing etc. function devMint(uint256 quantity) external onlyOwner { require(totalSupply() + quantity <= amountForDevs, "too many already minted before dev mint"); require(quantity % maxBatchSize == 0, "can only mint a multiple of the maxBatchSize"); uint256 numChunks = quantity / maxBatchSize; for (uint256 i = 0; i < numChunks; i++) { _safeMint(msg.sender, maxBatchSize); } } /// @notice Refund the difference if user sent more than the specified price. /// @param price The correct price. function refundIfOver(uint256 price) private { require(msg.value >= price, "Need to send more ETH."); if (msg.value > price) { payable(msg.sender).transfer(msg.value - price); } } /// @notice Return whether or not the public sale is live. /// @param priceWei The price set in WEI. /// @param saleStartTime The start time set. /// @return true if public sale is live, false otherwise. function isPublicSaleOn(uint256 priceWei, uint256 saleStartTime) public view returns (bool) { return priceWei != 0 && getCurrentTime() >= saleStartTime; } modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } /// @notice Add addresses to allow list. /// @param addresses The account addresses to whitelist. /// @param numAllowedToMint The number of allowed NFTs to mint per address. function setAllowList(address[] calldata addresses, uint8 numAllowedToMint) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { _allowList[addresses[i]] = numAllowedToMint; } } // // metadata URI string private _baseTokenURI; /// @notice Return the current base URI. /// @return The current base URI. function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /// @notice Set the base URI for the collection. /// @dev Can be used to handle a reveal separately. /// @param baseURI The new base URI. function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } /// @notice Withdraw ETH from the contract. /// @dev Only owner can call this function. function withdrawMoney() external onlyOwner nonReentrant { (bool success, ) = msg.sender.call{ value: address(this).balance }(""); require(success, "Transfer failed."); } /// @notice Return the number of minted NFTs for a given address. /// @param owner The address of the owner. /// @return The number of minted NFTs. function numberMinted(address owner) public view returns (uint256) { return _numberMinted(owner); } /// @notice Get ownership data. /// @param tokenId The token id. /// @return The `TokenOwnership` structure data associated to the token id. function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } /// @notice Return the current time. /// @dev Can be extended for testing purpose. /// @return The current timestamp. function getCurrentTime() internal view virtual returns (uint256) { return block.timestamp; } /// @notice Set whitelist sale start time. /// @param whitelistSaleStartTime_ The start time as a timestamp. function setWhitelistSaleStartTime(uint32 whitelistSaleStartTime_) external onlyOwner { SaleConfig storage config = saleConfig; config.whitelistSaleStartTime = whitelistSaleStartTime_; } /// @notice Set public sale start time. /// @param saleStartTime_ The start time as a timestamp. function setSaleStartTime(uint32 saleStartTime_) external onlyOwner { SaleConfig storage config = saleConfig; config.saleStartTime = saleStartTime_; } /// @notice Set current price for whitelisted sale. /// @param mintlistPrice_ The price in WEI. function setMintlistPrice(uint64 mintlistPrice_) external onlyOwner { SaleConfig storage config = saleConfig; config.mintlistPrice = mintlistPrice_; } /// @notice Set current price for public sale. /// @param price_ The price in WEI. function setPrice(uint64 price_) external onlyOwner { SaleConfig storage config = saleConfig; config.price = price_; } /// @notice Return the side of `msg.sender`. /// @return The side. function getMySide() public view returns (uint8) { return getSide(msg.sender); } /// @notice Return the side of a specified address. /// @return The side. function getSide(address account) public view returns (uint8) { return _side[account]; } /// @notice Return whether or not the specified address is assigned to a side. /// @return true if assigned, false otherwise. function hasSide(address account) public view returns (bool) { return _side[account] != 0; } /// @notice Assign a side to the specified address if not assigned yet. /// @param account The address to assign a side to. function assignSideIfNoSide(address account) internal { if (!hasSide(account)) { assignSide(account); } } /// @notice Assign a side to the specified address. /// @dev Throws if address has already a side assigned. /// @param account The address to assign a side to. function assignSide(address account) internal { require(!hasSide(account), "Account already assigned to a side"); uint8 side; uint256 seed = uint256(getSeed()); if (uint8(seed) % 2 == 0) { side = FURARIBI_SIDE; } else { side = NAITO_RAITO_SIDE; } _side[account] = side; } /// @notice Assign a side to `msg.sender` function assignMeASide() external { assignSideIfNoSide(msg.sender); } /// @notice Compute a new seed to serve for simple and non sensitive pseudo random use cases. /// @return The seed to use. function getSeed() internal view returns (bytes32) { return keccak256(abi.encodePacked(block.timestamp, block.basefee, gasleft(), msg.sender, totalSupply())); } /// @notice Whitelist holders of specific collection NFTs. /// @param collectionAddress The address of the collection. function whitelistHoldersOfCollection(address collectionAddress) external onlyOwner { _whitelistedCollections.push(collectionAddress); } /// @notice Whitelist holders of Azuki NFTs. function whitelistAzukiHolders() external onlyOwner { _whitelistedCollections.push(AZUKI_ADDRESS); } /// @notice Return whether or not the specified account is whitelisted. /// @param account The address to check. /// @return true if whitelisted, false otherwise. function isWhitelisted(address account) internal view returns (bool) { if (_allowList[account] > 0) { return true; } for (uint256 i = 0; i < _whitelistedCollections.length; i++) { IERC721 nftCollection = IERC721(_whitelistedCollections[i]); if (nftCollection.balanceOf(account) > 0) { return true; } } return false; } /// @notice Send NFT gifts to the selected winner. /// @dev Throws if the winner is not selected yet. function sendGiftsToWinner() external onlyIfWinnerSelected onlyOwner { for (uint256 i = 0; i < gifts.length; i++) { Gift memory gift = gifts[i]; IERC721 collection = IERC721(gift.collectionAddress); uint256[] memory ids = gift.ids; for (uint256 j = 0; j < ids.length; j++) { uint256 id = ids[j]; collection.safeTransferFrom(address(this), giftsWinnerAddress, id); } } } modifier onlyIfWinnerSelected() { require(giftsWinnerAddress != address(0x0), "winner must be selected"); _; } /// @notice Select a random winner using Chainlink VRF. function selectRandomWinnerForGifts() external onlyOwner requireFeeForLinkRequest { require(giftsWinnerAddress == address(0x0), "winner already selected"); selectRandomGiftWinnerRequestId = requestRandomness(_vrfKeyHash, _vrfFee); } /// @notice Withdraw Link /// @dev See chainlink documentation. function withdrawLink() external onlyOwner { IERC20 erc20 = IERC20(_linkToken); uint256 linkBalance = LINK.balanceOf(address(this)); if (linkBalance > 0) { erc20.transfer(owner(), linkBalance); } } modifier requireFeeForLinkRequest() { require(LINK.balanceOf(address(this)) >= _vrfFee, ERROR_NOT_ENOUGH_LINK); _; } /// @dev See `VRFConsumerBase` documentation. function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { if (requestId == selectRandomGiftWinnerRequestId && giftsWinnerAddress == address(0x0)) { giftsWinnerTokenId = randomness.mod(totalSupply()); giftsWinnerAddress = ownerOf(giftsWinnerTokenId); } } /// @notice Add gift to the list of gifts. /// @param collectionAddress Address of the NFT collection. /// @param ids The list of token ids. function addGift(address collectionAddress, uint256[] calldata ids) external { gifts.push(Gift(collectionAddress, ids)); } /// @notice Update VRF fee. function updateVRFFee(uint256 fee) external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 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, 8526, 1071, 389, 20409, 329, 15150, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "./Params.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; contract MockValidators is Params { using SafeMath for uint256; enum Status { // validator not exist, default status NotExist, // validator created Created, // anyone has staked for the validator Staked, // validator's staked coins < MinimalStakingCoin Unstaked, // validator is jailed by system(validator have to repropose) Jailed } struct Description { string moniker; string identity; string website; string email; string details; } struct Validator { address payable feeAddr; Status status; uint256 coins; Description description; uint256 hbIncoming; uint256 totalJailedHB; uint256 lastWithdrawProfitsBlock; // Address list of user who has staked for this validator address[] stakers; } struct StakingInfo { uint256 coins; // unstakeBlock != 0 means that you are unstaking your stake, so you can't // stake or unstake uint256 unstakeBlock; // index of the staker list in validator uint256 index; } mapping(address => Validator) validatorInfo; // staker => validator => info mapping(address => mapping(address => StakingInfo)) staked; // current validator set used by chain // only changed at block epoch address[] public currentValidatorSet; // highest validator set(dynamic changed) address[] public highestValidatorsSet; // total stake of all validators uint256 public totalStake; // total jailed hb uint256 public totalJailedHB; // System contracts // Proposal proposal; // Punish punish; enum Operations {Distribute, UpdateValidators} // Record the operations is done or not. mapping(uint256 => mapping(uint8 => bool)) operationsDone; event LogCreateValidator( address indexed val, address indexed fee, uint256 time ); event LogEditValidator( address indexed val, address indexed fee, uint256 time ); event LogReactive(address indexed val, uint256 time); event LogAddToTopValidators(address indexed val, uint256 time); event LogRemoveFromTopValidators(address indexed val, uint256 time); event LogUnstake( address indexed staker, address indexed val, uint256 amount, uint256 time ); event LogWithdrawStaking( address indexed staker, address indexed val, uint256 amount, uint256 time ); event LogWithdrawProfits( address indexed val, address indexed fee, uint256 hb, uint256 time ); event LogRemoveValidator(address indexed val, uint256 hb, uint256 time); event LogRemoveValidatorIncoming( address indexed val, uint256 hb, uint256 time ); event LogDistributeBlockReward( address indexed coinbase, uint256 blockReward, uint256 time ); event LogUpdateValidator(address[] newSet); event LogStake( address indexed staker, address indexed val, uint256 staking, uint256 time ); modifier onlyNotRewarded() { require( operationsDone[block.number][uint8(Operations.Distribute)] == false, "Block is already rewarded" ); _; } modifier onlyNotUpdated() { require( operationsDone[block.number][uint8(Operations.UpdateValidators)] == false, "Validators already updated" ); _; } function initialize(address[] calldata vals) external onlyNotInitialized { // proposal = Proposal(ProposalAddr); // punish = Punish(PunishContractAddr); for (uint256 i = 0; i < vals.length; i++) { require(vals[i] != address(0), "Invalid validator address"); // if (!isActiveValidator(vals[i])) { currentValidatorSet.push(vals[i]); // } // if (!isTopValidator(vals[i])) { highestValidatorsSet.push(vals[i]); // } // if (validatorInfo[vals[i]].feeAddr == address(0)) { validatorInfo[vals[i]].feeAddr = payable(vals[i]); // } // Important: NotExist validator can't get profits // if (validatorInfo[vals[i]].status == Status.NotExist) { validatorInfo[vals[i]].status = Status.Staked; // } } initialized = true; } // stake for the validator function stake(address validator) external payable onlyInitialized returns (bool) { address payable staker = msg.sender; uint256 staking = msg.value; require( validatorInfo[validator].status == Status.Created || validatorInfo[validator].status == Status.Staked, "Can't stake to a validator in abnormal status" ); // require( // proposal.pass(validator), // "The validator you want to stake must be authorized first" // ); require( staked[staker][validator].unstakeBlock == 0, "Can't stake when you are unstaking" ); Validator storage valInfo = validatorInfo[validator]; // The staked coins of validator must >= MinimalStakingCoin require( valInfo.coins.add(staking) >= MinimalStakingCoin, "Staking coins not enough" ); // stake at first time to this valiadtor if (staked[staker][validator].coins == 0) { // add staker to validator's record list staked[staker][validator].index = valInfo.stakers.length; valInfo.stakers.push(staker); } valInfo.coins = valInfo.coins.add(staking); if (valInfo.status != Status.Staked) { valInfo.status = Status.Staked; } tryAddValidatorToHighestSet(validator, valInfo.coins); // record staker's info staked[staker][validator].coins = staked[staker][validator].coins.add( staking ); totalStake = totalStake.add(staking); emit LogStake(staker, validator, staking, block.timestamp); return true; } function createOrEditValidator( address payable feeAddr, string calldata moniker, string calldata identity, string calldata website, string calldata email, string calldata details ) external onlyInitialized returns (bool) { require(feeAddr != address(0), "Invalid fee address"); require( validateDescription(moniker, identity, website, email, details), "Invalid description" ); address payable validator = msg.sender; bool isCreate = false; if (validatorInfo[validator].status == Status.NotExist) { // require(proposal.pass(validator), "You must be authorized first"); validatorInfo[validator].status = Status.Created; isCreate = true; } if (validatorInfo[validator].feeAddr != feeAddr) { validatorInfo[validator].feeAddr = feeAddr; } validatorInfo[validator].description = Description( moniker, identity, website, email, details ); if (isCreate) { emit LogCreateValidator(validator, feeAddr, block.timestamp); } else { emit LogEditValidator(validator, feeAddr, block.timestamp); } return true; } // // function tryReactive(address validator) // external // onlyProposalContract // onlyInitialized // returns (bool) // { // // Only update validator status if Unstaked/Jailed // if ( // validatorInfo[validator].status != Status.Unstaked && // validatorInfo[validator].status != Status.Jailed // ) { // return true; // } // // if (validatorInfo[validator].status == Status.Jailed) { // require(punish.cleanPunishRecord(validator), "clean failed"); // } // validatorInfo[validator].status = Status.Created; // // emit LogReactive(validator, block.timestamp); // } function unstake(address validator) external onlyInitialized returns (bool) { address staker = msg.sender; require( validatorInfo[validator].status != Status.NotExist, "Validator not exist" ); StakingInfo storage stakingInfo = staked[staker][validator]; Validator storage valInfo = validatorInfo[validator]; uint256 unstakeAmount = stakingInfo.coins; require( stakingInfo.unstakeBlock == 0, "You are already in unstaking status" ); require(unstakeAmount > 0, "You don't have any stake"); // You can't unstake if the validator is the only one top validator and // this unstake operation will cause staked coins of validator < MinimalStakingCoin require( !(highestValidatorsSet.length == 1 && isTopValidator(validator) && valInfo.coins.sub(unstakeAmount) < MinimalStakingCoin), "You can't unstake, validator list will be empty after this operation!" ); // try to remove this staker out of validator stakers list. if (stakingInfo.index != valInfo.stakers.length - 1) { valInfo.stakers[stakingInfo.index] = valInfo.stakers[valInfo .stakers .length - 1]; // update index of the changed staker. staked[valInfo.stakers[stakingInfo.index]][validator] .index = stakingInfo.index; } valInfo.stakers.pop(); valInfo.coins = valInfo.coins.sub(unstakeAmount); stakingInfo.unstakeBlock = block.number; stakingInfo.index = 0; totalStake = totalStake.sub(unstakeAmount); // try to remove it out of active validator set if validator's coins < MinimalStakingCoin if (valInfo.coins < MinimalStakingCoin) { valInfo.status = Status.Unstaked; // it's ok if validator not in highest set tryRemoveValidatorInHighestSet(validator); // call proposal contract to set unpass. // validator have to repropose to rebecome a validator. // proposal.setUnpassed(validator); } emit LogUnstake(staker, validator, unstakeAmount, block.timestamp); return true; } function withdrawStaking(address validator) external returns (bool) { address payable staker = payable(msg.sender); StakingInfo storage stakingInfo = staked[staker][validator]; require( validatorInfo[validator].status != Status.NotExist, "validator not exist" ); require(stakingInfo.unstakeBlock != 0, "You have to unstake first"); // Ensure staker can withdraw his staking back require( stakingInfo.unstakeBlock + StakingLockPeriod <= block.number, "Your staking haven't unlocked yet" ); require(stakingInfo.coins > 0, "You don't have any stake"); uint256 staking = stakingInfo.coins; stakingInfo.coins = 0; stakingInfo.unstakeBlock = 0; // send stake back to staker staker.transfer(staking); emit LogWithdrawStaking(staker, validator, staking, block.timestamp); return true; } // feeAddr can withdraw profits of it's validator function withdrawProfits(address validator) external returns (bool) { address payable feeAddr = payable(msg.sender); require( validatorInfo[validator].status != Status.NotExist, "Validator not exist" ); require( validatorInfo[validator].feeAddr == feeAddr, "You are not the fee receiver of this validator" ); require( validatorInfo[validator].lastWithdrawProfitsBlock + WithdrawProfitPeriod <= block.number, "You must wait enough blocks to withdraw your profits after latest withdraw of this validator" ); uint256 hbIncoming = validatorInfo[validator].hbIncoming; require(hbIncoming > 0, "You don't have any profits"); // update info validatorInfo[validator].hbIncoming = 0; validatorInfo[validator].lastWithdrawProfitsBlock = block.number; // send profits to fee address if (hbIncoming > 0) { feeAddr.transfer(hbIncoming); } emit LogWithdrawProfits( validator, feeAddr, hbIncoming, block.timestamp ); return true; } // distributeBlockReward distributes block reward to all active validators function distributeBlockReward() external payable onlyInitialized { operationsDone[block.number][uint8(Operations.Distribute)] = true; address val = msg.sender; uint256 hb = msg.value; // never reach this if (validatorInfo[val].status == Status.NotExist) { return; } // Jailed validator can't get profits. addProfitsToActiveValidatorsByStakePercentExcept(hb, address(0)); emit LogDistributeBlockReward(val, hb, block.timestamp); } function updateActiveValidatorSet(address[] memory newSet, uint256 epoch) public onlyMiner onlyNotUpdated onlyInitialized onlyBlockEpoch(epoch) { operationsDone[block.number][uint8(Operations.UpdateValidators)] = true; require(newSet.length > 0, "Validator set empty!"); currentValidatorSet = newSet; emit LogUpdateValidator(newSet); } function removeValidator(address val) external onlyPunishContract { uint256 hb = validatorInfo[val].hbIncoming; tryRemoveValidatorIncoming(val); // remove the validator out of active set // Note: the jailed validator may in active set if there is only one validator exists if (highestValidatorsSet.length > 1) { tryJailValidator(val); // call proposal contract to set unpass. // you have to repropose to be a validator. // proposal.setUnpassed(val); emit LogRemoveValidator(val, hb, block.timestamp); } } function removeValidatorIncoming(address val) external onlyPunishContract { tryRemoveValidatorIncoming(val); } function getValidatorDescription(address val) public view returns ( string memory, string memory, string memory, string memory, string memory ) { Validator memory v = validatorInfo[val]; return ( v.description.moniker, v.description.identity, v.description.website, v.description.email, v.description.details ); } function getValidatorInfo(address val) public view returns ( address payable, Status, uint256, uint256, uint256, uint256, address[] memory ) { Validator memory v = validatorInfo[val]; return ( v.feeAddr, v.status, v.coins, v.hbIncoming, v.totalJailedHB, v.lastWithdrawProfitsBlock, v.stakers ); } function getStakingInfo(address staker, address val) public view returns ( uint256, uint256, uint256 ) { return ( staked[staker][val].coins, staked[staker][val].unstakeBlock, staked[staker][val].index ); } function getActiveValidators() public view returns (address[] memory) { return currentValidatorSet; } function getTotalStakeOfActiveValidators() public view returns (uint256 total, uint256 len) { return getTotalStakeOfActiveValidatorsExcept(address(0)); } function getTotalStakeOfActiveValidatorsExcept(address val) private view returns (uint256 total, uint256 len) { for (uint256 i = 0; i < currentValidatorSet.length; i++) { if ( validatorInfo[currentValidatorSet[i]].status != Status.Jailed && val != currentValidatorSet[i] ) { total = total.add(validatorInfo[currentValidatorSet[i]].coins); len++; } } return (total, len); } function isActiveValidator(address who) public view returns (bool) { for (uint256 i = 0; i < currentValidatorSet.length; i++) { if (currentValidatorSet[i] == who) { return true; } } return false; } function isTopValidator(address who) public view returns (bool) { for (uint256 i = 0; i < highestValidatorsSet.length; i++) { if (highestValidatorsSet[i] == who) { return true; } } return false; } function getTopValidators() public view returns (address[] memory) { return highestValidatorsSet; } function validateDescription( string memory moniker, string memory identity, string memory website, string memory email, string memory details ) public pure returns (bool) { require(bytes(moniker).length <= 70, "Invalid moniker length"); require(bytes(identity).length <= 3000, "Invalid identity length"); require(bytes(website).length <= 140, "Invalid website length"); require(bytes(email).length <= 140, "Invalid email length"); require(bytes(details).length <= 280, "Invalid details length"); return true; } function tryAddValidatorToHighestSet(address val, uint256 staking) internal { // do nothing if you are already in highestValidatorsSet set for (uint256 i = 0; i < highestValidatorsSet.length; i++) { if (highestValidatorsSet[i] == val) { return; } } if (highestValidatorsSet.length < MaxValidators) { highestValidatorsSet.push(val); emit LogAddToTopValidators(val, block.timestamp); return; } // find lowest validator index in current validator set uint256 lowest = validatorInfo[highestValidatorsSet[0]].coins; uint256 lowestIndex = 0; for (uint256 i = 1; i < highestValidatorsSet.length; i++) { if (validatorInfo[highestValidatorsSet[i]].coins < lowest) { lowest = validatorInfo[highestValidatorsSet[i]].coins; lowestIndex = i; } } // do nothing if staking amount isn't bigger than current lowest if (staking <= lowest) { return; } // replace the lowest validator emit LogAddToTopValidators(val, block.timestamp); emit LogRemoveFromTopValidators( highestValidatorsSet[lowestIndex], block.timestamp ); highestValidatorsSet[lowestIndex] = val; } function tryRemoveValidatorIncoming(address val) private { // do nothing if validator not exist(impossible) if ( validatorInfo[val].status == Status.NotExist || currentValidatorSet.length <= 1 ) { return; } uint256 hb = validatorInfo[val].hbIncoming; if (hb > 0) { addProfitsToActiveValidatorsByStakePercentExcept(hb, val); // for display purpose totalJailedHB = totalJailedHB.add(hb); validatorInfo[val].totalJailedHB = validatorInfo[val] .totalJailedHB .add(hb); validatorInfo[val].hbIncoming = 0; } emit LogRemoveValidatorIncoming(val, hb, block.timestamp); } // add profits to all validators by stake percent except the punished validator or jailed validator function addProfitsToActiveValidatorsByStakePercentExcept( uint256 totalReward, address punishedVal ) private { if (totalReward == 0) { return; } uint256 totalRewardStake; uint256 rewardValsLen; ( totalRewardStake, rewardValsLen ) = getTotalStakeOfActiveValidatorsExcept(punishedVal); if (rewardValsLen == 0) { return; } uint256 remain; address last; // no stake(at genesis period) if (totalRewardStake == 0) { uint256 per = totalReward.div(rewardValsLen); remain = totalReward.sub(per.mul(rewardValsLen)); for (uint256 i = 0; i < currentValidatorSet.length; i++) { address val = currentValidatorSet[i]; if ( validatorInfo[val].status != Status.Jailed && val != punishedVal ) { validatorInfo[val].hbIncoming = validatorInfo[val] .hbIncoming .add(per); last = val; } } if (remain > 0 && last != address(0)) { validatorInfo[last].hbIncoming = validatorInfo[last] .hbIncoming .add(remain); } return; } uint256 added; for (uint256 i = 0; i < currentValidatorSet.length; i++) { address val = currentValidatorSet[i]; if ( validatorInfo[val].status != Status.Jailed && val != punishedVal ) { uint256 reward = totalReward.mul(validatorInfo[val].coins).div( totalRewardStake ); added = added.add(reward); last = val; validatorInfo[val].hbIncoming = validatorInfo[val] .hbIncoming .add(reward); } } remain = totalReward.sub(added); if (remain > 0 && last != address(0)) { validatorInfo[last].hbIncoming = validatorInfo[last].hbIncoming.add( remain ); } } function tryJailValidator(address val) private { // do nothing if validator not exist if (validatorInfo[val].status == Status.NotExist) { return; } // set validator status to jailed validatorInfo[val].status = Status.Jailed; // try to remove if it's in active validator set tryRemoveValidatorInHighestSet(val); } function tryRemoveValidatorInHighestSet(address val) private { for ( uint256 i = 0; // ensure at least one validator exist i < highestValidatorsSet.length && highestValidatorsSet.length > 1; i++ ) { if (val == highestValidatorsSet[i]) { // remove it if (i != highestValidatorsSet.length - 1) { highestValidatorsSet[i] = highestValidatorsSet[highestValidatorsSet .length - 1]; } highestValidatorsSet.pop(); emit LogRemoveFromTopValidators(val, block.timestamp); break; } } } }
do nothing if you are already in highestValidatorsSet set do nothing if staking amount isn't bigger than current lowest
function tryAddValidatorToHighestSet(address val, uint256 staking) internal { for (uint256 i = 0; i < highestValidatorsSet.length; i++) { if (highestValidatorsSet[i] == val) { return; } } if (highestValidatorsSet.length < MaxValidators) { highestValidatorsSet.push(val); emit LogAddToTopValidators(val, block.timestamp); return; } uint256 lowestIndex = 0; for (uint256 i = 1; i < highestValidatorsSet.length; i++) { if (validatorInfo[highestValidatorsSet[i]].coins < lowest) { lowest = validatorInfo[highestValidatorsSet[i]].coins; lowestIndex = i; } } if (staking <= lowest) { return; } emit LogRemoveFromTopValidators( highestValidatorsSet[lowestIndex], block.timestamp ); highestValidatorsSet[lowestIndex] = val; }
6,380,099
[ 1, 4625, 348, 7953, 560, 30, 225, 741, 5083, 309, 1846, 854, 1818, 316, 9742, 19420, 694, 444, 741, 5083, 309, 384, 6159, 3844, 5177, 1404, 18983, 2353, 783, 11981, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 775, 986, 5126, 774, 8573, 395, 694, 12, 2867, 1244, 16, 2254, 5034, 384, 6159, 13, 203, 565, 2713, 203, 565, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 9742, 19420, 694, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 8766, 395, 19420, 694, 63, 77, 65, 422, 1244, 13, 288, 203, 7734, 327, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 261, 8766, 395, 19420, 694, 18, 2469, 411, 4238, 19420, 13, 288, 203, 5411, 9742, 19420, 694, 18, 6206, 12, 1125, 1769, 203, 5411, 3626, 1827, 986, 774, 3401, 19420, 12, 1125, 16, 1203, 18, 5508, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 11981, 1016, 273, 374, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 404, 31, 277, 411, 9742, 19420, 694, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 7357, 966, 63, 8766, 395, 19420, 694, 63, 77, 65, 8009, 71, 9896, 411, 11981, 13, 288, 203, 7734, 11981, 273, 4213, 966, 63, 8766, 395, 19420, 694, 63, 77, 65, 8009, 71, 9896, 31, 203, 7734, 11981, 1016, 273, 277, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 261, 334, 6159, 1648, 11981, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 3626, 1827, 3288, 1265, 3401, 19420, 12, 203, 5411, 9742, 19420, 694, 63, 821, 395, 1016, 6487, 203, 5411, 1203, 18, 5508, 203, 3639, 11272, 203, 3639, 9742, 19420, 694, 63, 821, 395, 1016, 65, 273, 1244, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.11; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IERC20MintBurn.sol"; /** * @title JamonVault * @notice Profit sharing pool on the JamonV2 tokens deposited in stake. It distributes the tokens received based on the number of tokens staked in each wallet. */ contract JamonVault is ReentrancyGuard, Pausable, Ownable { //---------- Libraries ----------// using SafeMath for uint256; using Counters for Counters.Counter; using EnumerableSet for EnumerableSet.AddressSet; //---------- Contracts ----------// IERC20MintBurn private JamonV2; // JamonV2 token contract. //---------- Variables ----------// Counters.Counter public totalHolders; // Total wallets in stake. EnumerableSet.AddressSet internal validTokens; // Address map of valid tokens. uint256 constant month = 2629743; // 1 Month Timestamp. address public Governor; // Addres of Governor contract. uint256 private lastBlock; // Last block number processed for fixed apy. uint256 public totalStaked; // Total balance in stake. uint256 public lastUpdated; // Date in timestamp of the last balances update. uint256 private percentBlock; // Percentage with respect to the amount staked to be mined per block. bool public apyActived; // If fixed apy is active or not. //---------- Storage -----------// struct Wallet { // Tokens amount staked. uint256 stakedBal; // Dame in timestamp of the stake started. uint256 startTime; // Uint256 map of shared points. mapping(address => uint256) tokenPoints; // Uint256 map of pending rewards. mapping(address => uint256) pendingTokenbal; // Boolean to know if in stake. bool inStake; } mapping(address => Wallet) private stakeHolders; // Struct map of wallets in stake. mapping(address => uint256) private TokenPoints; // Uint256 map of shared points per tokens. mapping(address => uint256) private UnclaimedToken; // Uint256 map for store the tokens not claimed. mapping(address => uint256) private ProcessedToken; // Uit256 map for store the processed tokens. //---------- Events -----------// event Deposit(address indexed payee, uint256 amount, uint256 totalStaked); event Withdrawn(address indexed payee, uint256 amount); event Staked(address indexed wallet, uint256 amount); event UnStaked(address indexed wallet, uint256 amount); event ApyUpdated(uint256 apy, bool active); //---------- Constructor ----------// constructor(address jamonV2_, address governor_) { JamonV2 = IERC20MintBurn(jamonV2_); validTokens.add(jamonV2_); Governor = governor_; lastBlock = block.number; percentBlock = 32; // Anual Apy 5% = 0.00000032% per block apyActived = true; } //---------- Deposits -----------// /** * @dev Deposit and distribute permitted tokens. * @param token_ address of the token contract. * @param from_ address of the spender. * @param amount_ amount of tokens to distribute. */ function depositTokens( address token_, address from_, uint256 amount_ ) external nonReentrant { require(amount_ > 0, "Tokens too low"); require(validTokens.contains(token_), "Invalid token"); require(IERC20(token_).transferFrom(from_, address(this), amount_), "Transfer error"); _disburseToken(token_, amount_); } //----------- Internal Functions -----------// /** * @dev Distribute permitted tokens. * @param token_ address of the token contract. * @param amount_ amount of tokens to distribute. */ function _disburseToken(address token_, uint256 amount_) internal { if (totalStaked > 1000000 && amount_ >= 1000000) { TokenPoints[token_] = TokenPoints[token_].add( (amount_.mul(10e18)).div(totalStaked) ); UnclaimedToken[token_] = UnclaimedToken[token_].add(amount_); emit Deposit(_msgSender(), amount_, totalStaked); } } /** * @dev Mine the necessary amount with respect to the total balance in stake. */ function _updateApy() internal virtual { if (apyActived) { uint256 pendingBlocks = block.number.sub(lastBlock); uint256 blockApy = pendingBlocks.mul(percentBlock); uint256 toMint = totalStaked.mul(blockApy).div(10000000000); if (toMint > 0) { lastBlock = block.number; JamonV2.mint(address(this), toMint); } } } /** * @dev Calculates the tokens pending distribution and distributes them if there is an undistributed amount. */ function _recalculateBalances() internal virtual { uint256 tokensCount = validTokens.length(); for (uint256 i = 0; i < tokensCount; i++) { address token = validTokens.at(i); uint256 balance = token == address(JamonV2) ? IERC20(token).balanceOf(address(this)).sub(totalStaked) : IERC20(token).balanceOf(address(this)); uint256 processed = UnclaimedToken[token].add( ProcessedToken[token] ); if (balance > processed) { uint256 pending = balance.sub(processed); if (pending > 1000000) { _disburseToken(token, pending); } } } } /** * @dev Calculates a specific token pending distribution and distributes it if there is an undistributed amount. * @param token_ address of the token to calculate. */ function _recalculateTokenBalance(address token_) internal virtual { uint256 balance = IERC20(token_).balanceOf(address(this)); uint256 processed = UnclaimedToken[token_].add(ProcessedToken[token_]); if (balance > processed) { uint256 pending = balance.sub(processed); if (pending > 1000000) { _disburseToken(token_, pending); } } } /** * @dev Process pending rewards from a wallet. * @param wallet_ address of the wallet to be processed. */ function _processWalletTokens(address wallet_) internal virtual { uint256 tokensCount = validTokens.length(); for (uint256 i = 0; i < tokensCount; i++) { address token = validTokens.at(i); _processRewardsToken(token, wallet_); } } /** * @dev Process pending rewards from a wallet in a particular token. * @param token_ address of the token to process. * @param wallet_ address of the wallet to be processed. */ function _processRewardsToken(address token_, address wallet_) internal virtual { uint256 rewards = getRewardsToken(token_, wallet_); if (rewards > 0) { UnclaimedToken[token_] = UnclaimedToken[token_].sub(rewards); ProcessedToken[token_] = ProcessedToken[token_].add(rewards); stakeHolders[wallet_].tokenPoints[token_] = TokenPoints[token_]; stakeHolders[wallet_].pendingTokenbal[token_] = stakeHolders[ wallet_ ].pendingTokenbal[token_].add(rewards); } } /** * @dev Withdraw pending rewards of a specific token from a wallet. * @param token_ address of the token to withdraw. * @param wallet_ address of the wallet to withdraw. */ function _harvestToken(address token_, address wallet_) internal virtual { _processRewardsToken(token_, wallet_); uint256 amount = stakeHolders[wallet_].pendingTokenbal[token_]; if (amount > 0) { stakeHolders[wallet_].pendingTokenbal[token_] = 0; ProcessedToken[token_] = ProcessedToken[token_].sub(amount); IERC20(token_).transfer(wallet_, amount); emit Withdrawn(wallet_, amount); } } /** * @dev Withdraw pending rewards of all tokens from a wallet. * @param wallet_ address of the wallet to withdraw. */ function _harvestAll(address wallet_) internal virtual { _processWalletTokens(wallet_); uint256 tokensCount = validTokens.length(); for (uint256 i = 0; i < tokensCount; i++) { address token = validTokens.at(i); uint256 amount = stakeHolders[wallet_].pendingTokenbal[token]; if (amount > 0) { stakeHolders[wallet_].pendingTokenbal[token] = 0; ProcessedToken[token] = ProcessedToken[token].sub(amount); IERC20(token).transfer(wallet_, amount); emit Withdrawn(wallet_, amount); } } } /** * @dev Initialize a wallet joined with the current participation points. * @param wallet_ address of the wallet to initialize. */ function _initWalletPoints(address wallet_) internal virtual { uint256 tokensCount = validTokens.length(); Wallet storage w = stakeHolders[wallet_]; for (uint256 i = 0; i < tokensCount; i++) { address token = validTokens.at(i); w.tokenPoints[token] = TokenPoints[token]; } } /** * @dev Add a wallet to stake for the first time. * @param wallet_ address of the wallet to add. * @param amount_ amount to add. */ function _initStake(address wallet_, uint256 amount_) internal virtual returns (bool) { _recalculateBalances(); _initWalletPoints(wallet_); bool success = JamonV2.transferFrom(wallet_, address(this), amount_); stakeHolders[wallet_].startTime = block.timestamp; stakeHolders[wallet_].inStake = true; stakeHolders[wallet_].stakedBal = amount_; totalStaked = totalStaked.add(amount_); totalHolders.increment(); return success; } /** * @dev Add more tokens to stake from an existing wallet. * @param wallet_ address of the wallet. * @param amount_ amount to add. */ function _addStake(address wallet_, uint256 amount_) internal virtual returns (bool) { _recalculateBalances(); _processWalletTokens(wallet_); bool success = JamonV2.transferFrom(wallet_, address(this), amount_); stakeHolders[wallet_].stakedBal = stakeHolders[wallet_].stakedBal.add( amount_ ); totalStaked = totalStaked.add(amount_); return success; } /** * @dev Calculates the penalty for unstake based on the time you have in stake. Being a penalty of 1% on the balance per month in advance before a year. * @param wallet_ address of the wallet. * @return the amount of tokens to receive. */ function _unStakeBal(address wallet_) internal virtual returns (uint256) { uint256 accumulated = block.timestamp.sub( stakeHolders[wallet_].startTime ); uint256 balance = stakeHolders[wallet_].stakedBal; uint256 minPercent = 88; if (accumulated >= month.mul(12)) { return balance; } balance = balance.mul(10e18); if (accumulated < month) { balance = (balance.mul(minPercent)).div(100); return balance.div(10e18); } for (uint256 m = 1; m < 12; m++) { if (accumulated >= month.mul(m) && accumulated < month.mul(m + 1)) { minPercent = minPercent.add(m); balance = (balance.mul(minPercent)).div(100); return balance.div(10e18); } } return 0; } //----------- External Functions -----------// /** * @notice Check if a wallet address is in stake. * @return Boolean if in stake or not. */ function isInStake(address wallet_) external view returns (bool) { return stakeHolders[wallet_].inStake; } /** * @notice Check the reward amount of a specific token. * @param token_ Address of token to check. * @param wallet_ Address of the wallet to check. * @return Amount of reward for that token. */ function getRewardsToken(address token_, address wallet_) public view returns (uint256) { uint256 newTokenPoints = TokenPoints[token_].sub( stakeHolders[wallet_].tokenPoints[token_] ); return (stakeHolders[wallet_].stakedBal.mul(newTokenPoints)).div(10e18); } /** * @notice Check the reward amount of a specific token plus the processed balance. * @param token_ Address of token to check. * @param wallet_ Address of the wallet to check. * @return Amount of reward plus the processed for that token. */ function getPendingBal(address token_, address wallet_) external view returns (uint256) { uint256 newTokenPoints = TokenPoints[token_].sub( stakeHolders[wallet_].tokenPoints[token_] ); uint256 pending = stakeHolders[wallet_].pendingTokenbal[token_]; return (stakeHolders[wallet_].stakedBal.mul(newTokenPoints)) .div(10e18) .add(pending); } /** * @notice Check the info of stake for a wallet. * @param wallet_ Address of the wallet to check. * @return stakedBal amount of tokens staked. * @return startTime date in timestamp of the stake started. */ function getWalletInfo(address wallet_) public view returns (uint256 stakedBal, uint256 startTime) { Wallet storage w = stakeHolders[wallet_]; return (w.stakedBal, w.startTime); } /** * @notice Check if you have rewards for claiming or not. * @return If have reawrds. */ function pendingBalances() public view returns (bool) { uint256 tokensCount = validTokens.length(); for (uint256 i = 0; i < tokensCount; i++) { address token = validTokens.at(i); uint256 balance = token == address(JamonV2) ? IERC20(token).balanceOf(address(this)).sub(totalStaked) : IERC20(token).balanceOf(address(this)); uint256 processed = UnclaimedToken[token].add( ProcessedToken[token] ); if (balance > processed) { uint256 pending = balance.sub(processed); if (pending > 1000000) { return true; } } } return false; } /** * @notice Stake tokens to receive rewards. * @param amount_ Amount of tokens to deposit. */ function stake(uint256 amount_) external whenNotPaused nonReentrant { require(amount_ > 1000000, "Amount too low"); require( JamonV2.allowance(_msgSender(), address(this)) >= amount_, "Amount not allowed" ); if (stakeHolders[_msgSender()].inStake) { require(_addStake(_msgSender(), amount_), "Add stake error"); } else { require(_initStake(_msgSender(), amount_), "Init stake error"); } emit Staked(_msgSender(), amount_); } /** * @notice Withdraw rewards from a specific token. * @param token_ address of tokens to withdraw. */ function harvestToken(address token_) external whenNotPaused nonReentrant { require(stakeHolders[_msgSender()].inStake, "Not in stake"); require(validTokens.contains(token_), "Invalid token"); _harvestToken(token_, _msgSender()); } /** * @notice Withdraw rewards from all tokens. */ function harvestAll() external whenNotPaused nonReentrant { require(stakeHolders[_msgSender()].inStake, "Not in stake"); _harvestAll(_msgSender()); } /** * @notice Withdraw stake tokens and collect rewards. */ function unStake() external whenNotPaused nonReentrant { require(stakeHolders[_msgSender()].inStake, "Not in stake"); _harvestAll(_msgSender()); uint256 stakedBal = stakeHolders[_msgSender()].stakedBal; uint256 balance = _unStakeBal(_msgSender()); uint256 balanceDiff = stakedBal.sub(balance); if (balance > 0) { require(JamonV2.transfer(_msgSender(), balance), "Transfer error"); } totalStaked = totalStaked.sub(stakedBal); delete stakeHolders[_msgSender()]; totalHolders.decrement(); if (balanceDiff > 0) { require(JamonV2.transfer(Governor, balanceDiff), "Transfer error"); } emit UnStaked(_msgSender(), balance); } /** * @notice Safely withdraw staking tokens without collecting rewards. */ function safeUnStake() external whenPaused nonReentrant { require(stakeHolders[_msgSender()].inStake, "Not in stake"); uint256 stakedBal = stakeHolders[_msgSender()].stakedBal; delete stakeHolders[_msgSender()]; require(JamonV2.transfer(_msgSender(), stakedBal), "Transfer error"); totalStaked = totalStaked.sub(stakedBal); totalHolders.decrement(); } /** * @notice Update balances pending distribution if any. */ function updateBalances() external whenNotPaused nonReentrant { if (lastUpdated.add(1 days) < block.timestamp) { lastUpdated = block.timestamp; _updateApy(); _recalculateBalances(); } } /** * @notice Updates the balances pending distribution of a specific token in case there are any. * @param token_ address of token for update the pending balance. */ function updateTokenBalance(address token_) external onlyOwner { require(validTokens.contains(token_), "Invalid token"); _recalculateTokenBalance(token_); } /** * @notice Modify the list of valid tokens. * @param token_ address of token to add on list. * @param add_ boolean to enable or disable the token. */ function setTokenList(address token_, bool add_) external onlyOwner { require(token_ != address(0) && token_ != address(JamonV2), "Invalid address"); if (add_) { validTokens.add(token_); } else { validTokens.remove(token_); } } /** * @notice Get invalid tokens and send to Governor. * @param token_ address of token to send. */ function getInvalidTokens(address token_) external onlyOwner { require(!validTokens.contains(token_), "Invalid token" ); uint256 balance = IERC20(token_).balanceOf(address(this)); IERC20(token_).transfer(Governor, balance); } /** * @notice Set the fixed apy and activate it. * @param percent_ percentage with respect to the total stake to be mined per block, with a maximum of 0.00000640% (100% APY). * @param active_ boolean to enable or disable fixed apy. */ function setApy(uint256 percent_, bool active_) external onlyOwner { require(percent_ > 0 && percent_ < 640, "Invalid percent"); percentBlock = percent_; apyActived = active_; emit ApyUpdated(percent_, active_); } /** * @notice Functions for pause and unpause the contract. */ function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } }
* @notice Stake tokens to receive rewards. @param amount_ Amount of tokens to deposit./
function stake(uint256 amount_) external whenNotPaused nonReentrant { require(amount_ > 1000000, "Amount too low"); require( JamonV2.allowance(_msgSender(), address(this)) >= amount_, "Amount not allowed" ); if (stakeHolders[_msgSender()].inStake) { require(_addStake(_msgSender(), amount_), "Add stake error"); require(_initStake(_msgSender(), amount_), "Init stake error"); } emit Staked(_msgSender(), amount_); }
12,585,583
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 934, 911, 2430, 358, 6798, 283, 6397, 18, 632, 891, 3844, 67, 16811, 434, 2430, 358, 443, 1724, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12, 11890, 5034, 3844, 67, 13, 3903, 1347, 1248, 28590, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 8949, 67, 405, 15088, 16, 315, 6275, 4885, 4587, 8863, 203, 3639, 2583, 12, 203, 5411, 804, 301, 265, 58, 22, 18, 5965, 1359, 24899, 3576, 12021, 9334, 1758, 12, 2211, 3719, 1545, 3844, 67, 16, 203, 5411, 315, 6275, 486, 2935, 6, 203, 3639, 11272, 203, 203, 3639, 309, 261, 334, 911, 27003, 63, 67, 3576, 12021, 1435, 8009, 267, 510, 911, 13, 288, 203, 5411, 2583, 24899, 1289, 510, 911, 24899, 3576, 12021, 9334, 3844, 67, 3631, 315, 986, 384, 911, 555, 8863, 203, 5411, 2583, 24899, 2738, 510, 911, 24899, 3576, 12021, 9334, 3844, 67, 3631, 315, 2570, 384, 911, 555, 8863, 203, 3639, 289, 203, 3639, 3626, 934, 9477, 24899, 3576, 12021, 9334, 3844, 67, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 ton-solidity >= 0.45.0; pragma AbiHeader expire; pragma AbiHeader pubkey; pragma AbiHeader time; import "./DEXConnector.sol"; import "./interfaces/IRootTokenContract.sol"; import "./interfaces/ITONTokenWallet.sol"; import "./interfaces/ITokensReceivedCallback.sol"; import "./interfaces/IDEXConnector.sol"; import "./interfaces/IDEXConnect.sol"; import "./interfaces/IDEXClient.sol"; import "./interfaces/IDEXPair.sol"; import "./interfaces/IDEXRoot.sol"; import "./interfaces/ILockStakeSafeCallback.sol"; import "./interfaces/ILimitOrder.sol"; contract DEXClient is ITokensReceivedCallback, IDEXClient, IDEXConnect, ILockStakeSafeCallback { address static public rootDEX; uint256 static public soUINT; TvmCell static public codeDEXConnector; address public owner; // Grams constants uint128 constant public GRAMS_CONNECT_PAIR = 1.5 ton; uint128 constant public GRAMS_SET_CALLBACK_ADDR = 0.3 ton; uint128 constant public GRAMS_SWAP = 1.5 ton; uint128 constant public GRAMS_PROCESS_LIQUIDITY = 1.5 ton; uint128 constant public GRAMS_RETURN_LIQUIDITY = 1.5 ton; uint128 constant public MIN_GRAMS_TO_CONNECT_ROOT = 3.0 ton; uint128 constant public MIN_GRAMS_TO_CREATE_CONNECTOR = 1.0 ton; uint128 constant public MIN_BALANCE = 1 ton; uint128 constant public SET_CALLBACK_TO_ROOT = 0.5 ton; struct Connector { address root_address; uint256 souint; bool status; } address[] public rootKeys; mapping (address => address) public rootWallet; mapping (address => address) public rootConnector; mapping (address => Connector) connectors; uint256 public souintLast; uint public counterCallback; // Callback structure. struct Callback { address token_wallet; address token_root; uint128 amount; uint256 sender_public_key; address sender_address; address sender_wallet; address original_gas_to; uint128 updated_balance; uint8 payload_arg0; address payload_arg1; address payload_arg2; uint128 payload_arg3; uint128 payload_arg4; } mapping (uint => Callback) public callbacks; // Pair structure struct Pair { bool status; address rootA; address walletA; address rootB; address walletB; address rootAB; } mapping(address => Pair) public pairs; address[] public pairKeys; // Function for check internal owner. function isInternalOwner(address forCheck) private inline view returns (bool) { return owner != address(0) && forCheck == owner; } modifier checkOwnerAndAccept { require(msg.pubkey() == tvm.pubkey() || isInternalOwner(msg.sender), 102); tvm.accept(); _; } modifier checkOwner { require(msg.pubkey() == tvm.pubkey(), 107); _; } modifier checkPairAndAccept { require(pairs.exists(msg.sender), 108); tvm.rawReserve(address(this).balance - msg.value, 2); _; } modifier checkConnectorAndAccept { require(connectors.exists(msg.sender), 109); tvm.rawReserve(address(this).balance - msg.value, 2); _; } constructor(address ownerAddr) public { if (msg.sender == rootDEX) { tvm.rawReserve(address(this).balance + MIN_BALANCE - msg.value, 2); owner = ownerAddr; counterCallback = 0; TvmCell body = tvm.encodeBody(IDEXRoot(rootDEX).createDEXclientCallback, tvm.pubkey(), address(this), owner); rootDEX.transfer({value: 0, flag: 128, body:body}); } else { tvm.accept(); owner = address(0); counterCallback = 0; TvmCell body = tvm.encodeBody(IDEXRoot(rootDEX).createDEXclientCallback, tvm.pubkey(), address(this), owner); rootDEX.transfer({value: SET_CALLBACK_TO_ROOT, flag: 0, body:body}); } } // Function to connect DEXClient to new DEXPair. function connectPair(address pairAddr) public checkOwnerAndAccept returns (bool statusConnection) { require (address(this).balance >= GRAMS_CONNECT_PAIR, 110); statusConnection = false; if (!pairs.exists(pairAddr)){ Pair cp = pairs[pairAddr]; cp.status = false; pairs[pairAddr] = cp; pairKeys.push(pairAddr); TvmCell body = tvm.encodeBody(IDEXPair(pairAddr).connect); pairAddr.transfer({value:GRAMS_CONNECT_PAIR, body:body}); statusConnection = true; } } // Function for get first callback id. function getFirstCallback() private inline view returns (uint) { optional(uint, Callback) rc = callbacks.min(); if (rc.hasValue()) {(uint number, ) = rc.get();return number;} else {return 0;} } // Callback for DEXpair to set connection data. function setPair(address arg0, address arg1, address arg2, address arg3, address arg4) public checkPairAndAccept override { address dexpair = msg.sender; Pair cp = pairs[dexpair]; cp.status = true; cp.rootA = arg0; cp.walletA = arg1; cp.rootB = arg2; cp.walletB = arg3; cp.rootAB = arg4; pairs[dexpair] = cp; } // Function for compute connector address function computeConnectorAddress(uint256 souint) private inline view returns (address) { TvmCell stateInit = tvm.buildStateInit({ contr: DEXConnector, varInit: { soUINT: souint, dexclient: address(this) }, code: codeDEXConnector, pubkey: tvm.pubkey() }); return address(tvm.hash(stateInit)); } // Function for get computed connector address function getConnectorAddress(uint256 connectorSoArg) public view responsible returns (address) { return { value: 0, bounce: false, flag: 64 } computeConnectorAddress( connectorSoArg); } // Function for connect to Root function connectRoot(address root, uint256 souint, uint128 gramsToConnector, uint128 gramsToRoot) public checkOwnerAndAccept returns (bool statusConnected){ require (gramsToConnector >= MIN_GRAMS_TO_CREATE_CONNECTOR && gramsToRoot >= MIN_GRAMS_TO_CONNECT_ROOT && address(this).balance >= (gramsToConnector + gramsToRoot), 111); statusConnected = false; if (!rootWallet.exists(root) && souint > souintLast) { TvmCell stateInit = tvm.buildStateInit({ contr: DEXConnector, varInit: { soUINT: souint, dexclient: address(this) }, code: codeDEXConnector, pubkey: tvm.pubkey() }); TvmCell init = tvm.encodeBody(DEXConnector); address connector = tvm.deploy(stateInit, init, gramsToConnector, address(this).wid); Connector cr = connectors[connector]; cr.root_address = root; cr.souint = souint; cr.status = false; connectors[connector] = cr; TvmCell body = tvm.encodeBody(IDEXConnector(connector).deployEmptyWallet, root); connector.transfer({value:gramsToRoot, bounce:true, body:body}); souintLast = souint; statusConnected = true; } } // Function for callback from DEX Connector in process connect to Root function connectCallback(address wallet) public override checkConnectorAndAccept { address connector = msg.sender; Connector cc = connectors[connector]; rootKeys.push(cc.root_address); rootWallet[cc.root_address] = wallet; rootConnector[cc.root_address] = connector; TvmCell bodySTC = tvm.encodeBody(IDEXConnector(connector).setTransferCallback); connector.transfer({value: GRAMS_SET_CALLBACK_ADDR, bounce:true, flag: 0, body:bodySTC}); TvmCell bodySBC = tvm.encodeBody(IDEXConnector(connector).setBouncedCallback); connector.transfer({value: GRAMS_SET_CALLBACK_ADDR, bounce:true, flag: 0, body:bodySBC}); cc.status = true; connectors[connector] = cc; } // Function to check DEXclient for swap processing. function isReady(address pair) private inline view returns (bool) { Pair cp = pairs[pair]; Connector ccA = connectors[rootConnector[cp.rootA]]; Connector ccB = connectors[rootConnector[cp.rootB]]; return cp.status && rootWallet.exists(cp.rootA) && rootWallet.exists(cp.rootB) && rootConnector.exists(cp.rootA) && rootConnector.exists(cp.rootB) && ccA.status && ccB.status; } // Function to check DEXclient for provide liquidity processing. function isReadyToProvide(address pair) private inline view returns (bool) { Pair cp = pairs[pair]; Connector ccA = connectors[rootConnector[cp.rootA]]; Connector ccB = connectors[rootConnector[cp.rootB]]; return cp.status && rootWallet.exists(cp.rootA) && rootWallet.exists(cp.rootB) && rootWallet.exists(cp.rootAB) && rootConnector.exists(cp.rootA) && rootConnector.exists(cp.rootB) && ccA.status && ccB.status; } // Function to get all connected pairs and created wallets of DEXclient. function getAllDataPreparation() public view returns(address[] pairKeysR, address[] rootKeysR){ pairKeysR = pairKeys; rootKeysR = rootKeys; } // Function to swap A. function processSwapA(address pairAddr, uint128 qtyA, uint128 minQtyB, uint128 maxQtyB) public view checkOwnerAndAccept returns (bool processSwapStatus) { require (address(this).balance >= GRAMS_SWAP, 112); processSwapStatus = false; if (isReady(pairAddr)) { Pair cp = pairs[pairAddr]; address connector = rootConnector[cp.rootA]; TvmBuilder builder; builder.store(uint8(1), address(this), rootWallet[cp.rootB], minQtyB, maxQtyB); TvmCell payload = builder.toCell(); TvmCell body = tvm.encodeBody(IDEXConnector(connector).transfer, cp.walletA, qtyA, payload); connector.transfer({value: GRAMS_SWAP, bounce:true, body:body}); processSwapStatus = true; } } // Function to swap B. function processSwapB(address pairAddr, uint128 qtyB, uint128 minQtyA, uint128 maxQtyA) public view checkOwnerAndAccept returns (bool processSwapStatus) { require (address(this).balance >= GRAMS_SWAP, 112); processSwapStatus = false; if (isReady(pairAddr)) { Pair cp = pairs[pairAddr]; address connector = rootConnector[cp.rootB]; TvmBuilder builder; builder.store(uint8(1), address(this), rootWallet[cp.rootA], minQtyA, maxQtyA); TvmCell payload = builder.toCell(); TvmCell body = tvm.encodeBody(IDEXConnector(connector).transfer, cp.walletB, qtyB, payload); connector.transfer({value: GRAMS_SWAP, bounce:true, body:body}); processSwapStatus = true; } } // Function to provide liquidity to DEXpair. function processLiquidity(address pairAddr, uint128 qtyA, uint128 qtyB) public view checkOwnerAndAccept returns (bool processLiquidityStatus) { processLiquidityStatus = false; if (isReadyToProvide(pairAddr)) { Pair cp = pairs[pairAddr]; address connectorA = rootConnector[cp.rootA]; address connectorB = rootConnector[cp.rootB]; TvmBuilder builderA; builderA.store(uint8(2), address(this), rootWallet[cp.rootAB], uint128(2), uint128(2)); TvmCell payloadA = builderA.toCell(); TvmBuilder builderB; builderB.store(uint8(2), address(this), rootWallet[cp.rootAB], uint128(2), uint128(2)); TvmCell payloadB = builderB.toCell(); TvmCell bodyA = tvm.encodeBody(IDEXConnector(connectorA).transfer, cp.walletA, qtyA, payloadA); TvmCell bodyB = tvm.encodeBody(IDEXConnector(connectorB).transfer, cp.walletB, qtyB, payloadB); connectorA.transfer({value: GRAMS_PROCESS_LIQUIDITY, bounce:true, body:bodyA}); connectorB.transfer({value: GRAMS_PROCESS_LIQUIDITY, bounce:true, body:bodyB}); processLiquidityStatus = true; } } // Function to returm liquidity from DEXpair. function returnLiquidity(address pairAddr, uint128 tokens) public view checkOwnerAndAccept returns (bool returnLiquidityStatus) { returnLiquidityStatus = false; if (isReadyToProvide(pairAddr)) { Pair cp = pairs[pairAddr]; TvmBuilder builder; builder.store(uint8(3), rootWallet[cp.rootA], rootWallet[cp.rootB], uint128(3), uint128(3)); TvmCell callback_payload = builder.toCell(); TvmCell body = tvm.encodeBody(IDEXConnector(rootConnector[cp.rootAB]).burn, tokens, pairAddr, callback_payload); rootConnector[cp.rootAB].transfer({value:GRAMS_RETURN_LIQUIDITY, body:body}); returnLiquidityStatus = true; } } // Function to receive callbacks from DEXClient TONToken Wallets and processing. function tokensReceivedCallback( address token_wallet, address token_root, uint128 amount, uint256 sender_public_key, address sender_address, address sender_wallet, address original_gas_to, uint128 updated_balance, TvmCell payload ) public override { tvm.rawReserve(address(this).balance - msg.value, 2); Callback cc = callbacks[counterCallback]; cc.token_wallet = token_wallet; cc.token_root = token_root; cc.amount = amount; cc.sender_public_key = sender_public_key; cc.sender_address = sender_address; cc.sender_wallet = sender_wallet; cc.original_gas_to = original_gas_to; cc.updated_balance = updated_balance; TvmSlice slice = payload.toSlice(); (uint8 arg0, address arg1, address arg2, uint128 arg3, uint128 arg4) = slice.decode(uint8, address, address, uint128, uint128); cc.payload_arg0 = arg0; cc.payload_arg1 = arg1; cc.payload_arg2 = arg2; cc.payload_arg3 = arg3; cc.payload_arg4 = arg4; callbacks[counterCallback] = cc; counterCallback++; if (counterCallback > 10){delete callbacks[getFirstCallback()];} } // Function for get callback function getCallback(uint id) public view checkOwnerAndAccept returns ( address token_wallet, address token_root, uint128 amount, uint256 sender_public_key, address sender_address, address sender_wallet, address original_gas_to, uint128 updated_balance, uint8 payload_arg0, address payload_arg1, address payload_arg2, uint128 payload_arg3, uint128 payload_arg4 ){ Callback cc = callbacks[id]; token_wallet = cc.token_wallet; token_root = cc.token_root; amount = cc.amount; sender_public_key = cc.sender_public_key; sender_address = cc.sender_address; sender_wallet = cc.sender_wallet; original_gas_to = cc.original_gas_to; updated_balance = cc.updated_balance; payload_arg0 = cc.payload_arg0; payload_arg1 = cc.payload_arg1; payload_arg2 = cc.payload_arg2; payload_arg3 = cc.payload_arg3; payload_arg4 = cc.payload_arg4; } // Function for get this contract TON gramms balance function thisBalance() private inline pure returns (uint128) { return address(this).balance; } // Function for external get this contract TON gramms balance function getBalance() public pure responsible returns (uint128) { return { value: 0, bounce: false, flag: 64 } thisBalance(); } // Function to create DEXpair by DEXclient via DEXroot. function createNewPair( address root0, address root1, uint256 pairSoArg, uint256 connectorSoArg0, uint256 connectorSoArg1, uint256 rootSoArg, bytes rootName, bytes rootSymbol, uint8 rootDecimals, uint128 grammsForPair, uint128 grammsForRoot, uint128 grammsForConnector, uint128 grammsForWallet, uint128 grammsTotal ) public view checkOwner { require (!(grammsTotal < (grammsForPair+2*grammsForConnector+2*grammsForWallet+grammsForRoot)) && !(grammsTotal < 5 ton),106); require (!(address(this).balance < grammsTotal),105); tvm.accept(); TvmCell body = tvm.encodeBody(IDEXRoot(rootDEX).createDEXpair, root0,root1,pairSoArg,connectorSoArg0,connectorSoArg1,rootSoArg,rootName,rootSymbol,rootDecimals,grammsForPair,grammsForRoot,grammsForConnector,grammsForWallet); rootDEX.transfer({value:grammsTotal, bounce: true, flag: 1, body:body}); } // Function to get connected pair data. function getPairData(address pairAddr) public view returns ( bool pairStatus, address pairRootA, address pairWalletA, address pairRootB, address pairWalletB, address pairRootAB, address curPair ){ Pair cp = pairs[pairAddr]; pairStatus = cp.status; pairRootA = cp.rootA; pairWalletA = cp.walletA; pairRootB = cp.rootB; pairWalletB = cp.walletB; pairRootAB = cp.rootAB; curPair = pairAddr; } // Function to send Tokens. function sendTokens(address tokenRoot, address to, uint128 tokens, uint128 grams) public checkOwnerAndAccept view returns (bool sendTokenStatus){ sendTokenStatus = false; if (rootConnector[tokenRoot] != address(0)) { address connector = rootConnector[tokenRoot]; TvmBuilder builder; builder.store(uint8(4), address(this), rootWallet[tokenRoot], uint128(4), uint128(4)); TvmCell payload = builder.toCell(); TvmCell body = tvm.encodeBody(IDEXConnector(connector).transfer, to, tokens, payload); connector.transfer({value: grams, bounce:true, body:body}); sendTokenStatus = true; } } // Function to send Transaction with setting bounce, flags and payload. function sendTransaction(address dest, uint128 value, bool bounce, uint8 flags, TvmCell payload) public pure checkOwnerAndAccept { dest.transfer(value, bounce, flags, payload); } // Function to receive deploy callbacks from StakeSafe. function deployLockStakeSafeCallback(address lockStakeSafe, address nftKey, uint128 amount, uint256 period) public override { tvm.rawReserve(address(this).balance - msg.value, 2); lockStakeSafe; nftKey; amount; period; } // Function to receive transferOwnership callbacks from StakeSafe's NFT . function transferOwnershipCallback(address addrFrom, address addrTo) public override { tvm.rawReserve(address(this).balance - msg.value, 2); addrFrom; addrTo; } // Callback structure. struct ProcessLiquidity { address walletA; uint128 amountA; uint128 provideA; uint128 unusedReturnA; address walletB; uint128 amountB; uint128 provideB; uint128 unusedReturnB; address walletAB; uint128 mintAB; } ProcessLiquidity public pl; // Callback structure. struct ReturnLiquidity { address walletAB; uint128 burnAB; address walletA; uint128 returnA; address walletB; uint128 returnB; } ReturnLiquidity public rl; // Function to receive processLiquidity callbacks from DEXpair. function processLiquidityCallback( address walletA, uint128 amountA, uint128 provideA, uint128 unusedReturnA, address walletB, uint128 amountB, uint128 provideB, uint128 unusedReturnB, address walletAB, uint128 mintAB ) public override checkPairAndAccept { pl = ProcessLiquidity(walletA, amountA, provideA, unusedReturnA, walletB, amountB, provideB, unusedReturnB, walletAB, mintAB); } // Function to receive returnLiquidity callbacks from DEXpair. function returnLiquidityCallback( address walletAB, uint128 burnAB, address walletA, uint128 returnA, address walletB, uint128 returnB ) public override checkPairAndAccept { rl = ReturnLiquidity(walletAB, burnAB, walletA, returnA, walletB, returnB); } // Function to makeLimitOrderA function makeLimitOrderA(address routerWalletA, address pairAddr, uint128 qtyA, uint128 priceA) public view checkOwnerAndAccept returns (bool makeLimitOrderStatus) { require (address(this).balance >= GRAMS_SWAP, 112); makeLimitOrderStatus = false; if (isReady(pairAddr)) { Pair cp = pairs[pairAddr]; address connector = rootConnector[cp.rootA]; TvmBuilder builder; builder.store(uint8(4), pairAddr, rootWallet[cp.rootB], priceA, qtyA); TvmCell payload = builder.toCell(); TvmCell body = tvm.encodeBody(IDEXConnector(connector).transfer, routerWalletA, qtyA, payload); connector.transfer({value: GRAMS_SWAP, bounce:true, body:body}); makeLimitOrderStatus = true; } } // Function to makeLimitOrderB function makeLimitOrderB(address routerWalletB, address pairAddr, uint128 qtyB, uint128 priceB) public view checkOwnerAndAccept returns (bool makeLimitOrderStatus) { require (address(this).balance >= GRAMS_SWAP, 112); makeLimitOrderStatus = false; if (isReady(pairAddr)) { Pair cp = pairs[pairAddr]; address connector = rootConnector[cp.rootB]; TvmBuilder builder; builder.store(uint8(5), pairAddr, rootWallet[cp.rootA], priceB, qtyB); TvmCell payload = builder.toCell(); TvmCell body = tvm.encodeBody(IDEXConnector(connector).transfer, routerWalletB, qtyB, payload); connector.transfer({value: GRAMS_SWAP, bounce:true, body:body}); makeLimitOrderStatus = true; } } // Function to transferLimitOrder function transferLimitOrder(address limitOrder, address addrNewOwner, address walletNewOwnerFrom, address walletNewOwnerTo) public view checkOwnerAndAccept returns (bool transferLimitOrderStatus) { require (address(this).balance >= GRAMS_SWAP, 112); transferLimitOrderStatus = false; TvmCell body = tvm.encodeBody(ILimitOrder(limitOrder).transferOwnership, addrNewOwner, walletNewOwnerFrom, walletNewOwnerTo); limitOrder.transfer({value: GRAMS_SWAP, bounce:true, body:body}); transferLimitOrderStatus = true; } // Function to changePrice function changeLimitOrderPrice(address limitOrder, uint128 newPrice) public view checkOwnerAndAccept returns (bool changePriceStatus) { require (address(this).balance >= GRAMS_SWAP, 112); changePriceStatus = false; TvmCell body = tvm.encodeBody(ILimitOrder(limitOrder).changePrice, newPrice); limitOrder.transfer({value: GRAMS_SWAP, bounce:true, body:body}); changePriceStatus = true; } // Function to cancelOrder function cancelLimitOrder(address limitOrder) public view checkOwnerAndAccept returns (bool cancelOrderStatus) { require (address(this).balance >= GRAMS_SWAP, 112); cancelOrderStatus = false; TvmCell body = tvm.encodeBody(ILimitOrder(limitOrder).cancelOrder); limitOrder.transfer({value: GRAMS_SWAP, bounce:true, body:body}); cancelOrderStatus = true; } // Function to takeLimitOrderA function takeLimitOrderA(address pairAddr, address limitOrderA, address routerWalletB, uint128 qtyB, uint128 priceB) public view checkOwnerAndAccept returns (bool takeLimitOrderStatus) { require (address(this).balance >= GRAMS_SWAP, 112); takeLimitOrderStatus = false; if (isReady(pairAddr)) { Pair cp = pairs[pairAddr]; address connector = rootConnector[cp.rootB]; TvmBuilder builder; builder.store(uint8(6), limitOrderA, rootWallet[cp.rootA], priceB, qtyB); TvmCell payload = builder.toCell(); TvmCell body = tvm.encodeBody(IDEXConnector(connector).transfer, routerWalletB, qtyB, payload); connector.transfer({value: GRAMS_SWAP, bounce:true, body:body}); takeLimitOrderStatus = true; } } // Function to takeLimitOrderB function takeLimitOrderB(address pairAddr, address limitOrderB, address routerWalletA, uint128 qtyA, uint128 priceA) public view checkOwnerAndAccept returns (bool takeLimitOrderStatus) { require (address(this).balance >= GRAMS_SWAP, 112); takeLimitOrderStatus = false; if (isReady(pairAddr)) { Pair cp = pairs[pairAddr]; address connector = rootConnector[cp.rootA]; TvmBuilder builder; builder.store(uint8(7), limitOrderB, rootWallet[cp.rootB], priceA, qtyA); TvmCell payload = builder.toCell(); TvmCell body = tvm.encodeBody(IDEXConnector(connector).transfer, routerWalletA, qtyA, payload); connector.transfer({value: GRAMS_SWAP, bounce:true, body:body}); takeLimitOrderStatus = true; } } // Function to receive plain transfers. receive() external { } }
Function to send Transaction with setting bounce, flags and payload.
function sendTransaction(address dest, uint128 value, bool bounce, uint8 flags, TvmCell payload) public pure checkOwnerAndAccept { dest.transfer(value, bounce, flags, payload); }
13,128,144
[ 1, 4625, 348, 7953, 560, 30, 225, 4284, 358, 1366, 5947, 598, 3637, 324, 8386, 16, 2943, 471, 2385, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 5933, 288, 203, 565, 1570, 18, 13866, 12, 1132, 16, 324, 8386, 16, 2943, 16, 2385, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xF314466C692e3832f15cDf127A7FeE536279fFb8/sources/joytest1.sol
fileHash = masterFile[masterRef]; fileType = fileTypeMemory[masterRef];
function getMetadata(uint256 tokenId) public view returns (string memory artTitle, string memory description, string memory artType, uint256 editionCap, uint256 editionNumber){ uint256 masterRef = fileMasterReference[tokenId]; artTitle = artTitleMemory[masterRef]; artType = artTypeMemory[masterRef]; description = descriptionMemory[masterRef]; editionCap = editionCapMemory[masterRef]; editionNumber = editionNumberMemory[tokenId]; }
8,523,804
[ 1, 4625, 348, 7953, 560, 30, 540, 585, 2310, 273, 4171, 812, 63, 7525, 1957, 15533, 3639, 21939, 273, 21939, 6031, 63, 7525, 1957, 15533, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 11159, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 1135, 261, 1080, 3778, 3688, 4247, 16, 533, 3778, 2477, 16, 533, 3778, 3688, 559, 16, 2254, 5034, 28432, 4664, 16, 2254, 5034, 28432, 1854, 15329, 203, 3639, 2254, 5034, 4171, 1957, 273, 585, 7786, 2404, 63, 2316, 548, 15533, 203, 540, 203, 3639, 3688, 4247, 273, 3688, 4247, 6031, 63, 7525, 1957, 15533, 203, 3639, 3688, 559, 273, 3688, 559, 6031, 63, 7525, 1957, 15533, 203, 3639, 2477, 273, 2477, 6031, 63, 7525, 1957, 15533, 203, 3639, 28432, 4664, 273, 28432, 4664, 6031, 63, 7525, 1957, 15533, 203, 3639, 28432, 1854, 273, 28432, 1854, 6031, 63, 2316, 548, 15533, 203, 540, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xc41A4FC84A5B096c99A06cE38988114F4BCb5B67/sources/contracts/DebtToken.sol
* Transfer tokens from one address to another @notice couldn't override in interface @dev modifier onlyCommunityContract @param _sender address - the address to debit tokens from @param _recipient address - the address to credit tokens to @param _amount uint256 - the amount of tokens to be transferred @return bool - true if transfer was successful, and false otherwise/
function transferFrom( address _sender, address _recipient, uint256 _amount ) public override onlyCommunityContract returns (bool) { _transfer(_sender, _recipient, _amount); return true; }
654,600
[ 1, 4625, 348, 7953, 560, 30, 380, 12279, 2430, 628, 1245, 1758, 358, 4042, 632, 20392, 17991, 1404, 3849, 316, 1560, 632, 5206, 9606, 1338, 12136, 13352, 8924, 632, 891, 389, 15330, 1758, 300, 326, 1758, 358, 443, 3682, 2430, 628, 632, 891, 389, 20367, 1758, 300, 326, 1758, 358, 12896, 2430, 358, 632, 891, 389, 8949, 2254, 5034, 300, 326, 3844, 434, 2430, 358, 506, 906, 4193, 632, 2463, 1426, 300, 638, 309, 7412, 1703, 6873, 16, 471, 629, 3541, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 1265, 12, 203, 3639, 1758, 389, 15330, 16, 203, 3639, 1758, 389, 20367, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 1071, 3849, 1338, 12136, 13352, 8924, 1135, 261, 6430, 13, 288, 203, 3639, 389, 13866, 24899, 15330, 16, 389, 20367, 16, 389, 8949, 1769, 203, 3639, 327, 638, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/42/0xa8E3f997951637FF80a975E81f74fe86EA4EB444/sources/KBaseQuestions.sol
bytes32 public alphaChainBytes32JobId; address public alphaChainKovanOracle;
contract KBaseQuestions is ChainlinkClient { uint256 public questionIdCounter; mapping(uint256 => Question) public questions; mapping(bytes32 => uint256) public requestToQuestions; IERC20 public kbaseToken; uint256 public answerStakeAmount; bytes32 public ipfsJobId; address public chainlinkOracle; uint256 public fee; int256 public STARTING_CHAR_DEFAULT; struct Question { address asker; string CID; uint256 answerCounter; mapping(uint256 => Answer) answers; mapping(bytes32 => bool) firstQuestionRequestIds; bool fulfilled; } struct Answer { address answerer; string CID; bool accepted; uint256 votes; } constructor(address _kbaseTokenAddress, address _link) public{ if (_link == address(0)) { setPublicChainlinkToken(); setChainlinkToken(_link); } questionIdCounter = 0; kbaseToken = IERC20(_kbaseTokenAddress); chainlinkOracle = 0xBCEe35D8DC726Bf19811C1e036783b298F4F059f; } constructor(address _kbaseTokenAddress, address _link) public{ if (_link == address(0)) { setPublicChainlinkToken(); setChainlinkToken(_link); } questionIdCounter = 0; kbaseToken = IERC20(_kbaseTokenAddress); chainlinkOracle = 0xBCEe35D8DC726Bf19811C1e036783b298F4F059f; } } else { ipfsJobId = "6e85c42d6bbe439a8ad7e4a9b552102f"; STARTING_CHAR_DEFAULT = 32; function createQuestion(string memory questionText, string memory questionTitle)public returns(uint256 questionId){ bytes32 requestIdStart = createQuestionFragment(questionText, questionTitle, 0); bytes32 requestIdEnd = createQuestionFragment(questionText, questionTitle, STARTING_CHAR_DEFAULT); Question storage question = questions[questionIdCounter]; questionId = questionIdCounter; requestToQuestions[requestIdStart] = questionIdCounter; requestToQuestions[requestIdEnd] = questionIdCounter; question.firstQuestionRequestIds[requestIdStart] = true; question.firstQuestionRequestIds[requestIdEnd] = false; question.asker = msg.sender; questionIdCounter = questionIdCounter + 1; return questionId; } function createQuestionFragment(string memory questionText, string memory questionTitle, int256 starting_char) internal returns (bytes32 requestId){ Chainlink.Request memory request_fragment = buildChainlinkRequest(ipfsJobId, address(this), this.fulfillQuestionAskFragment.selector); request_fragment.add("text_for_file", questionText); request_fragment.add("text_for_file_name", questionTitle); request_fragment.addInt("starting_char", starting_char); return sendChainlinkRequestTo(chainlinkOracle, request_fragment, fee); } function createAnswer(string memory answerText, string memory answerTitle) public returns (bytes32 requestId){ Chainlink.Request memory request = buildChainlinkRequest(ipfsJobId, address(this), this.fulfillAnswerQuestion.selector); request.add("text_for_file", answerText); request.add("text_for_file_name", answerTitle); return sendChainlinkRequestTo(chainlinkOracle, request, fee); } function fulfillQuestionAskFragment(bytes32 ipfsCIDQuestionBytes, bytes32 requestId) public recordChainlinkFulfillment(requestId) returns (bool){ string memory ipfsCIDQuestion = bytes32ToString(ipfsCIDQuestionBytes); uint256 questionId = requestToQuestions[requestId]; uint256 questionByteSize = bytes(questions[questionId].CID).length; if(questions[questionId].firstQuestionRequestIds[requestId] == true && questionByteSize > 0){ string memory tmp = questions[questionId].CID; questions[questionId].CID = string(abi.encodePacked(ipfsCIDQuestion, tmp)); questions[questionId].fulfilled = true; return true; } if (questions[questionId].firstQuestionRequestIds[requestId] == true && questionByteSize == 0){ questions[questionId].CID = ipfsCIDQuestion; return true; } if(questions[questionId].firstQuestionRequestIds[requestId] == false){ questions[questionId].CID = string(abi.encodePacked(questions[questionId].CID, ipfsCIDQuestion)); questions[questionId].fulfilled = true; return true; } return false; } function fulfillQuestionAskFragment(bytes32 ipfsCIDQuestionBytes, bytes32 requestId) public recordChainlinkFulfillment(requestId) returns (bool){ string memory ipfsCIDQuestion = bytes32ToString(ipfsCIDQuestionBytes); uint256 questionId = requestToQuestions[requestId]; uint256 questionByteSize = bytes(questions[questionId].CID).length; if(questions[questionId].firstQuestionRequestIds[requestId] == true && questionByteSize > 0){ string memory tmp = questions[questionId].CID; questions[questionId].CID = string(abi.encodePacked(ipfsCIDQuestion, tmp)); questions[questionId].fulfilled = true; return true; } if (questions[questionId].firstQuestionRequestIds[requestId] == true && questionByteSize == 0){ questions[questionId].CID = ipfsCIDQuestion; return true; } if(questions[questionId].firstQuestionRequestIds[requestId] == false){ questions[questionId].CID = string(abi.encodePacked(questions[questionId].CID, ipfsCIDQuestion)); questions[questionId].fulfilled = true; return true; } return false; } function fulfillQuestionAskFragment(bytes32 ipfsCIDQuestionBytes, bytes32 requestId) public recordChainlinkFulfillment(requestId) returns (bool){ string memory ipfsCIDQuestion = bytes32ToString(ipfsCIDQuestionBytes); uint256 questionId = requestToQuestions[requestId]; uint256 questionByteSize = bytes(questions[questionId].CID).length; if(questions[questionId].firstQuestionRequestIds[requestId] == true && questionByteSize > 0){ string memory tmp = questions[questionId].CID; questions[questionId].CID = string(abi.encodePacked(ipfsCIDQuestion, tmp)); questions[questionId].fulfilled = true; return true; } if (questions[questionId].firstQuestionRequestIds[requestId] == true && questionByteSize == 0){ questions[questionId].CID = ipfsCIDQuestion; return true; } if(questions[questionId].firstQuestionRequestIds[requestId] == false){ questions[questionId].CID = string(abi.encodePacked(questions[questionId].CID, ipfsCIDQuestion)); questions[questionId].fulfilled = true; return true; } return false; } function fulfillQuestionAskFragment(bytes32 ipfsCIDQuestionBytes, bytes32 requestId) public recordChainlinkFulfillment(requestId) returns (bool){ string memory ipfsCIDQuestion = bytes32ToString(ipfsCIDQuestionBytes); uint256 questionId = requestToQuestions[requestId]; uint256 questionByteSize = bytes(questions[questionId].CID).length; if(questions[questionId].firstQuestionRequestIds[requestId] == true && questionByteSize > 0){ string memory tmp = questions[questionId].CID; questions[questionId].CID = string(abi.encodePacked(ipfsCIDQuestion, tmp)); questions[questionId].fulfilled = true; return true; } if (questions[questionId].firstQuestionRequestIds[requestId] == true && questionByteSize == 0){ questions[questionId].CID = ipfsCIDQuestion; return true; } if(questions[questionId].firstQuestionRequestIds[requestId] == false){ questions[questionId].CID = string(abi.encodePacked(questions[questionId].CID, ipfsCIDQuestion)); questions[questionId].fulfilled = true; return true; } return false; } function fulfillAnswerQuestion(string memory ipfsCIDAnswer, uint256 questionId) public { Answer storage answer = questions[questionId].answers[questions[questionId].answerCounter]; answer.answerer = msg.sender; answer.CID = ipfsCIDAnswer; answer.accepted = false; answer.votes = 0; questions[questionId].answerCounter = questions[questionId].answerCounter + 1; kbaseToken.transfer(msg.sender, 1000000000000000000); } function acceptAnswer(uint256 questionId, uint256 answerId) public onlyQuestionAsker(questionId){ questions[questionId].answers[answerId].accepted = true; kbaseToken.transfer(questions[questionId].answers[answerId].answerer, 1000000000000000000); } function getAnswerCID(uint256 questionId, uint256 answerId) public view returns (string memory){ string memory CID = questions[questionId].answers[answerId].CID; return CID; } function getAnswerStatus(uint256 questionId, uint256 answerId) public view returns (bool){ bool accepted = questions[questionId].answers[answerId].accepted; return accepted; } function getQuestionAsker(uint256 questionId) public view returns (address){ return questions[questionId].asker; } function getQuestionCID(uint256 questionId) public view returns (string memory){ return questions[questionId].CID; } modifier onlyQuestionAsker(uint256 questionId) { require( msg.sender == questions[questionId].asker, "Only the question asker can call this function." ); _; } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } }
3,408,591
[ 1, 4625, 348, 7953, 560, 30, 225, 1731, 1578, 1071, 4190, 3893, 2160, 1578, 23378, 31, 1758, 1071, 4190, 3893, 47, 1527, 304, 23601, 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,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1475, 2171, 30791, 1115, 353, 7824, 1232, 1227, 288, 203, 565, 2254, 5034, 1071, 5073, 548, 4789, 31, 203, 565, 2874, 12, 11890, 5034, 516, 18267, 13, 1071, 13494, 31, 203, 565, 2874, 12, 3890, 1578, 516, 2254, 5034, 13, 1071, 590, 774, 30791, 1115, 31, 203, 565, 467, 654, 39, 3462, 1071, 417, 1969, 1345, 31, 203, 565, 2254, 5034, 1071, 5803, 510, 911, 6275, 31, 203, 565, 1731, 1578, 1071, 2359, 2556, 23378, 31, 203, 565, 1758, 1071, 2687, 1232, 23601, 31, 203, 203, 565, 2254, 5034, 1071, 14036, 31, 203, 203, 565, 509, 5034, 1071, 10485, 1360, 67, 7305, 67, 5280, 31, 203, 203, 203, 565, 1958, 18267, 288, 203, 3639, 1758, 6827, 264, 31, 203, 3639, 533, 385, 734, 31, 203, 3639, 2254, 5034, 5803, 4789, 31, 203, 3639, 2874, 12, 11890, 5034, 516, 21019, 13, 12415, 31, 203, 3639, 2874, 12, 3890, 1578, 516, 1426, 13, 1122, 11665, 691, 2673, 31, 203, 3639, 1426, 16136, 13968, 31, 7010, 565, 289, 203, 203, 565, 1958, 21019, 288, 203, 3639, 1758, 5803, 264, 31, 203, 3639, 533, 385, 734, 31, 203, 3639, 1426, 8494, 31, 203, 3639, 2254, 5034, 19588, 31, 203, 565, 289, 203, 203, 565, 3885, 12, 2867, 389, 79, 1969, 1345, 1887, 16, 1758, 389, 1232, 13, 1071, 95, 203, 3639, 309, 261, 67, 1232, 422, 1758, 12, 20, 3719, 288, 203, 3639, 27467, 3893, 1232, 1345, 5621, 203, 3639, 444, 3893, 1232, 1345, 24899, 1232, 1769, 203, 3639, 289, 203, 3639, 5073, 548, 4789, 273, 374, 31, 203, 3639, 417, 1969, 1345, 273, 467, 654, 39, 3462, 24899, 79, 1969, 1345, 1887, 1769, 203, 203, 3639, 2687, 1232, 23601, 273, 374, 20029, 1441, 73, 4763, 40, 28, 5528, 27, 5558, 38, 74, 30234, 2499, 39, 21, 73, 4630, 26, 8285, 23, 70, 5540, 28, 42, 24, 42, 20, 6162, 74, 31, 203, 203, 565, 289, 203, 203, 565, 3885, 12, 2867, 389, 79, 1969, 1345, 1887, 16, 1758, 389, 1232, 13, 1071, 95, 203, 3639, 309, 261, 67, 1232, 422, 1758, 12, 20, 3719, 288, 203, 3639, 27467, 3893, 1232, 1345, 5621, 203, 3639, 444, 3893, 1232, 1345, 24899, 1232, 1769, 203, 3639, 289, 203, 3639, 5073, 548, 4789, 273, 374, 31, 203, 3639, 417, 1969, 1345, 273, 467, 654, 39, 3462, 24899, 79, 1969, 1345, 1887, 1769, 203, 203, 3639, 2687, 1232, 23601, 273, 374, 20029, 1441, 73, 4763, 40, 28, 5528, 27, 5558, 38, 74, 30234, 2499, 39, 21, 73, 4630, 26, 8285, 23, 70, 5540, 28, 42, 24, 42, 20, 6162, 74, 31, 203, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 3639, 2359, 2556, 23378, 273, 315, 26, 73, 7140, 71, 9452, 72, 26, 70, 2196, 24, 5520, 69, 28, 361, 27, 73, 24, 69, 29, 70, 2539, 22, 20481, 74, 14432, 203, 203, 3639, 10485, 1360, 67, 7305, 67, 5280, 273, 3847, 31, 203, 565, 445, 752, 11665, 12, 1080, 3778, 5073, 1528, 16, 533, 3778, 5073, 4247, 13, 482, 1135, 12, 11890, 5034, 5073, 548, 15329, 203, 3639, 1731, 1578, 14459, 1685, 273, 752, 11665, 7456, 12, 4173, 1528, 16, 5073, 4247, 16, 374, 1769, 203, 3639, 1731, 1578, 14459, 1638, 273, 752, 11665, 7456, 12, 4173, 1528, 16, 5073, 4247, 16, 10485, 1360, 67, 7305, 67, 5280, 1769, 203, 3639, 18267, 2502, 5073, 273, 13494, 63, 4173, 548, 4789, 15533, 7010, 3639, 5073, 548, 273, 5073, 548, 4789, 31, 203, 3639, 590, 774, 30791, 1115, 63, 2293, 548, 1685, 65, 273, 5073, 548, 4789, 31, 203, 3639, 590, 774, 30791, 1115, 63, 2293, 548, 1638, 65, 273, 5073, 548, 4789, 31, 203, 3639, 5073, 18, 3645, 11665, 691, 2673, 63, 2293, 548, 1685, 65, 273, 638, 31, 203, 3639, 5073, 18, 3645, 11665, 691, 2673, 63, 2293, 548, 1638, 65, 273, 629, 31, 203, 3639, 5073, 18, 835, 264, 273, 1234, 18, 15330, 31, 203, 3639, 5073, 548, 4789, 273, 5073, 548, 4789, 397, 404, 31, 203, 3639, 327, 5073, 548, 31, 203, 565, 289, 203, 203, 565, 445, 752, 11665, 7456, 12, 1080, 3778, 5073, 1528, 16, 533, 3778, 5073, 4247, 16, 509, 5034, 5023, 67, 3001, 13, 2713, 1135, 261, 3890, 1578, 14459, 15329, 203, 3639, 7824, 1232, 18, 691, 3778, 590, 67, 11956, 273, 1361, 3893, 1232, 691, 12, 625, 2556, 23378, 16, 1758, 12, 2211, 3631, 333, 18, 2706, 5935, 11665, 23663, 7456, 18, 9663, 1769, 203, 3639, 590, 67, 11956, 18, 1289, 2932, 955, 67, 1884, 67, 768, 3113, 5073, 1528, 1769, 203, 3639, 590, 67, 11956, 18, 1289, 2932, 955, 67, 1884, 67, 768, 67, 529, 3113, 5073, 4247, 1769, 203, 3639, 590, 67, 11956, 18, 1289, 1702, 2932, 18526, 67, 3001, 3113, 5023, 67, 3001, 1769, 203, 3639, 327, 1366, 3893, 1232, 691, 774, 12, 5639, 1232, 23601, 16, 590, 67, 11956, 16, 14036, 1769, 203, 565, 289, 203, 203, 565, 445, 752, 13203, 12, 1080, 3778, 5803, 1528, 16, 533, 3778, 5803, 4247, 13, 1071, 1135, 261, 3890, 1578, 14459, 15329, 203, 3639, 7824, 1232, 18, 691, 3778, 590, 273, 1361, 3893, 1232, 691, 12, 625, 2556, 23378, 16, 1758, 12, 2211, 3631, 333, 18, 2706, 5935, 13203, 11665, 18, 9663, 1769, 203, 3639, 590, 18, 1289, 2932, 955, 67, 1884, 67, 768, 3113, 5803, 1528, 1769, 203, 3639, 590, 18, 1289, 2932, 955, 67, 1884, 67, 768, 67, 529, 3113, 5803, 4247, 1769, 203, 3639, 327, 1366, 3893, 1232, 691, 774, 12, 5639, 1232, 23601, 16, 590, 16, 14036, 1769, 203, 565, 289, 203, 203, 565, 445, 22290, 11665, 23663, 7456, 12, 3890, 1578, 2359, 2556, 25992, 11665, 2160, 16, 1731, 1578, 14459, 13, 1071, 1409, 3893, 1232, 23747, 5935, 475, 12, 2293, 548, 13, 1135, 261, 6430, 15329, 203, 3639, 533, 3778, 2359, 2556, 25992, 11665, 273, 1731, 1578, 5808, 12, 625, 2556, 25992, 11665, 2160, 1769, 203, 3639, 2254, 5034, 5073, 548, 273, 590, 774, 30791, 1115, 63, 2293, 548, 15533, 203, 3639, 2254, 5034, 5073, 3216, 1225, 273, 1731, 12, 9758, 63, 4173, 548, 8009, 25992, 2934, 2469, 31, 203, 3639, 309, 12, 9758, 63, 4173, 548, 8009, 3645, 11665, 691, 2673, 63, 2293, 548, 65, 422, 638, 597, 5073, 3216, 1225, 405, 2 ]
./full_match/1/0x700B276ac277BFBC04Ffb34E7aA1347C2cEb802a/sources/contracts/PhilanthropyToken.sol
Mapping to track buyer purchase timestamps
contract PhilanthropyToken is ERC20, Ownable { using Admin for *; using Security for *; using Utils for *; uint256 public TOTAL_INITIAL_RELEASED = 0; uint256 public TOTAL_INVESTOR_CLAIMED = 0; uint256 public presaleStartTime; mapping(address => uint256) public lastPurchaseTimestamp; string private secretCode; mapping(address => bool) private admins; pragma solidity ^0.8.0; modifier onlyAdmin() { require(admins[msg.sender] || msg.sender == owner(), "Not an admin"); _; } constructor() ERC20("PhilanthropyToken", "PTPH") { _mint(address(this), MARKET_CAP); presaleStartTime = block.timestamp; } function setAdmin(address _admin, bool _status) external onlyAdmin { admins[_admin] = _status; } function mint(uint256 amount) external onlyAdmin { uint256 currentSupply = totalSupply(); require( currentSupply + amount <= MAX_TOTAL_SUPPLY, "Exceeds maximum total supply" ); _mint(address(this), amount); } function buyPresaleTokens(uint256 amount) external payable { require(amount > 0, "Invalid purchase amount"); require( block.timestamp >= presaleStartTime, "Presale has not started yet" ); require( block.timestamp <= presaleStartTime + 182.5 days, "Presale has ended" ); uint256 totalPrice = amount * PRESALE_PRICE; require(msg.value >= totalPrice, "Insufficient funds sent"); uint256 remainingPresaleAllocation = PRESALE_TOTAL_SOLD; require( amount <= remainingPresaleAllocation, "Not enough tokens available for purchase" ); _transfer(address(this), msg.sender, amount); lastPurchaseTimestamp[msg.sender] = block.timestamp; if (msg.value > totalPrice) { payable(msg.sender).transfer(msg.value - totalPrice); } PRESALE_TOTAL_SOLD += amount; } function buyPresaleTokens(uint256 amount) external payable { require(amount > 0, "Invalid purchase amount"); require( block.timestamp >= presaleStartTime, "Presale has not started yet" ); require( block.timestamp <= presaleStartTime + 182.5 days, "Presale has ended" ); uint256 totalPrice = amount * PRESALE_PRICE; require(msg.value >= totalPrice, "Insufficient funds sent"); uint256 remainingPresaleAllocation = PRESALE_TOTAL_SOLD; require( amount <= remainingPresaleAllocation, "Not enough tokens available for purchase" ); _transfer(address(this), msg.sender, amount); lastPurchaseTimestamp[msg.sender] = block.timestamp; if (msg.value > totalPrice) { payable(msg.sender).transfer(msg.value - totalPrice); } PRESALE_TOTAL_SOLD += amount; } function initialRelease( address[] memory recipients, uint256[] memory amounts ) external onlyAdmin { require( recipients.length == amounts.length, "Array lengths do not match" ); for (uint256 i = 0; i < recipients.length; i++) { address recipient = recipients[i]; uint256 amount = amounts[i]; require(recipient != address(0), "Invalid recipient address"); require(amount > 0, "Invalid amount"); TOTAL_INITIAL_RELEASED += amount; require( TOTAL_INITIAL_RELEASED <= CHARITY_ALLOCATION, "Total distribution exceeds CHARITY_ALLOCATION" ); _transfer(address(this), recipient, amount); } } function initialRelease( address[] memory recipients, uint256[] memory amounts ) external onlyAdmin { require( recipients.length == amounts.length, "Array lengths do not match" ); for (uint256 i = 0; i < recipients.length; i++) { address recipient = recipients[i]; uint256 amount = amounts[i]; require(recipient != address(0), "Invalid recipient address"); require(amount > 0, "Invalid amount"); TOTAL_INITIAL_RELEASED += amount; require( TOTAL_INITIAL_RELEASED <= CHARITY_ALLOCATION, "Total distribution exceeds CHARITY_ALLOCATION" ); _transfer(address(this), recipient, amount); } } function claimInvestorTokens( address[] memory investors, uint256[] memory amounts ) external onlyAdmin { require( investors.length == amounts.length, "Array lengths do not match" ); require( block.timestamp >= presaleStartTime + INVESTOR_LOCK_PERIOD, "Lock-up period not over" ); for (uint256 i = 0; i < investors.length; i++) { address investor = investors[i]; uint256 amount = amounts[i]; require(investor != address(0), "Invalid investor address"); require(amount > 0, "Invalid amount"); TOTAL_INVESTOR_CLAIMED += amount; require( TOTAL_INVESTOR_CLAIMED <= INVESTOR_ALLOCATION, "Total distribution exceeds INVESTOR_ALLOCATION" ); _transfer(address(this), investor, amount); } } function claimInvestorTokens( address[] memory investors, uint256[] memory amounts ) external onlyAdmin { require( investors.length == amounts.length, "Array lengths do not match" ); require( block.timestamp >= presaleStartTime + INVESTOR_LOCK_PERIOD, "Lock-up period not over" ); for (uint256 i = 0; i < investors.length; i++) { address investor = investors[i]; uint256 amount = amounts[i]; require(investor != address(0), "Invalid investor address"); require(amount > 0, "Invalid amount"); TOTAL_INVESTOR_CLAIMED += amount; require( TOTAL_INVESTOR_CLAIMED <= INVESTOR_ALLOCATION, "Total distribution exceeds INVESTOR_ALLOCATION" ); _transfer(address(this), investor, amount); } } function setSecretCode(string memory code) external onlyAdmin { secretCode = code; } function checkSecretCode(string memory code) public view onlyOwner { require( keccak256(abi.encodePacked(code)) == keccak256(abi.encodePacked(secretCode)), "Incorrect secret code" ); } function transfer( address recipient, uint256 amount, string memory code ) external onlyAdmin { if (amount > TRANSACTION_THRESHOLD) { require( keccak256(abi.encodePacked(code)) == keccak256(abi.encodePacked(secretCode)), "Incorrect secret code" ); } _transfer(address(this), recipient, amount); } function transfer( address recipient, uint256 amount, string memory code ) external onlyAdmin { if (amount > TRANSACTION_THRESHOLD) { require( keccak256(abi.encodePacked(code)) == keccak256(abi.encodePacked(secretCode)), "Incorrect secret code" ); } _transfer(address(this), recipient, amount); } function transferFrom( address recipient, uint256 amount, string memory code ) external { if (amount > TRANSACTION_THRESHOLD) { require( keccak256(abi.encodePacked(code)) == keccak256(abi.encodePacked(secretCode)), "Incorrect secret code" ); } _transfer(msg.sender, recipient, amount); } function transferFrom( address recipient, uint256 amount, string memory code ) external { if (amount > TRANSACTION_THRESHOLD) { require( keccak256(abi.encodePacked(code)) == keccak256(abi.encodePacked(secretCode)), "Incorrect secret code" ); } _transfer(msg.sender, recipient, amount); } function mintWhenNeedded() external onlyAdmin { uint256 currentBalance = balanceOf(address(this)); if (currentBalance < MIN_BALANCE_TO_INCREASE_SUPPLY) { uint256 additionalSupply = MARKET_CAP; _mint(address(this), additionalSupply); } } function mintWhenNeedded() external onlyAdmin { uint256 currentBalance = balanceOf(address(this)); if (currentBalance < MIN_BALANCE_TO_INCREASE_SUPPLY) { uint256 additionalSupply = MARKET_CAP; _mint(address(this), additionalSupply); } } function burn(uint256 amount) public onlyAdmin { _burn(address(this), amount); } function getUnsudedSupplies() external view onlyAdmin returns (uint256) { return balanceOf(address(this)); } function getTotalIInvestorAllocation() external view onlyAdmin returns (uint256) { return INVESTOR_ALLOCATION; } function getTotalInitialAllocation() external view onlyAdmin returns (uint256) { return CHARITY_ALLOCATION; } function getTotalInitialReleased() external view onlyAdmin returns (uint256) { return TOTAL_INITIAL_RELEASED; } function getTotalInvestorClaimed() external view onlyAdmin returns (uint256) { return TOTAL_INVESTOR_CLAIMED; } function transferBetweenCategories( uint256 amount, bool fromInitialToInvestor ) external onlyAdmin { require( fromInitialToInvestor || TOTAL_INITIAL_RELEASED >= amount, "Insufficient tokens in INITIAL_RELEASED" ); require( !fromInitialToInvestor || TOTAL_INVESTOR_CLAIMED >= amount, "Insufficient tokens in INVESTOR_CLAIMED" ); if (fromInitialToInvestor) { CHARITY_ALLOCATION -= amount; INVESTOR_ALLOCATION += amount; INVESTOR_ALLOCATION -= amount; CHARITY_ALLOCATION += amount; } _transfer(address(this), msg.sender, amount); } function transferBetweenCategories( uint256 amount, bool fromInitialToInvestor ) external onlyAdmin { require( fromInitialToInvestor || TOTAL_INITIAL_RELEASED >= amount, "Insufficient tokens in INITIAL_RELEASED" ); require( !fromInitialToInvestor || TOTAL_INVESTOR_CLAIMED >= amount, "Insufficient tokens in INVESTOR_CLAIMED" ); if (fromInitialToInvestor) { CHARITY_ALLOCATION -= amount; INVESTOR_ALLOCATION += amount; INVESTOR_ALLOCATION -= amount; CHARITY_ALLOCATION += amount; } _transfer(address(this), msg.sender, amount); } } else { function topupCategories( uint256 amount, bool fromInitialToInvestor ) external onlyAdmin { require( fromInitialToInvestor || CHARITY_ALLOCATION >= amount, "Insufficient tokens in INITIAL_RELEASED" ); require( !fromInitialToInvestor || TOTAL_INVESTOR_CLAIMED >= amount, "Insufficient tokens in INVESTOR_CLAIMED" ); if (fromInitialToInvestor) { CHARITY_ALLOCATION -= amount; INVESTOR_ALLOCATION += amount; INVESTOR_ALLOCATION -= amount; CHARITY_ALLOCATION += amount; } function topupCategories( uint256 amount, bool fromInitialToInvestor ) external onlyAdmin { require( fromInitialToInvestor || CHARITY_ALLOCATION >= amount, "Insufficient tokens in INITIAL_RELEASED" ); require( !fromInitialToInvestor || TOTAL_INVESTOR_CLAIMED >= amount, "Insufficient tokens in INVESTOR_CLAIMED" ); if (fromInitialToInvestor) { CHARITY_ALLOCATION -= amount; INVESTOR_ALLOCATION += amount; INVESTOR_ALLOCATION -= amount; CHARITY_ALLOCATION += amount; } } else { } function transferWithSecretCode( address recipient, uint256 amount, string memory code ) external { require(amount <= TRANSACTION_THRESHOLD, "Amount exceeds threshold"); require( code.checkSecretCode(secretCode) || bytes(code).length == 0, "Incorrect secret code" ); _transfer(msg.sender, recipient, amount); } function topUpCharityAllocation(uint256 amount) external onlyAdmin { uint256 availableBalance = balanceOf(address(this)); require(amount <= availableBalance, "Exceeds available balance"); CHARITY_ALLOCATION += amount; _transfer(address(this), address(this), amount); } function topUpInvestorAllocation(uint256 amount) external onlyAdmin { uint256 availableBalance = balanceOf(address(this)); require(amount <= availableBalance, "Exceeds available balance"); INVESTOR_ALLOCATION += amount; _transfer(address(this), address(this), amount); } }
9,643,187
[ 1, 4625, 348, 7953, 560, 30, 225, 9408, 358, 3298, 27037, 23701, 11267, 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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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4360, 330, 304, 451, 8405, 1345, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 7807, 364, 380, 31, 203, 565, 1450, 6036, 364, 380, 31, 203, 565, 1450, 6091, 364, 380, 31, 203, 203, 203, 203, 565, 2254, 5034, 1071, 399, 19851, 67, 28497, 67, 30762, 40, 273, 374, 31, 203, 565, 2254, 5034, 1071, 399, 19851, 67, 706, 3412, 882, 916, 67, 15961, 3114, 40, 273, 374, 31, 203, 203, 203, 565, 2254, 5034, 1071, 4075, 5349, 13649, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 1142, 23164, 4921, 31, 203, 565, 533, 3238, 4001, 1085, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 31116, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 9606, 1338, 4446, 1435, 288, 203, 3639, 2583, 12, 3666, 87, 63, 3576, 18, 15330, 65, 747, 1234, 18, 15330, 422, 3410, 9334, 315, 1248, 392, 3981, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 3731, 330, 304, 451, 8405, 1345, 3113, 315, 1856, 8939, 7923, 288, 203, 3639, 389, 81, 474, 12, 2867, 12, 2211, 3631, 20503, 1584, 67, 17296, 1769, 203, 3639, 4075, 5349, 13649, 273, 1203, 18, 5508, 31, 203, 203, 565, 289, 203, 203, 565, 445, 444, 4446, 12, 2867, 389, 3666, 16, 1426, 389, 2327, 13, 3903, 1338, 4446, 288, 203, 3639, 31116, 63, 67, 3666, 65, 273, 389, 2327, 31, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 11890, 5034, 3844, 13, 3903, 1338, 4446, 288, 203, 3639, 2254, 5034, 783, 3088, 1283, 273, 2078, 3088, 1283, 5621, 203, 3639, 2583, 12, 203, 5411, 783, 3088, 1283, 397, 3844, 1648, 4552, 67, 28624, 67, 13272, 23893, 16, 203, 5411, 315, 424, 5288, 87, 4207, 2078, 14467, 6, 203, 3639, 11272, 203, 3639, 389, 81, 474, 12, 2867, 12, 2211, 3631, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 30143, 12236, 5349, 5157, 12, 11890, 5034, 3844, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 1941, 23701, 3844, 8863, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 5508, 1545, 4075, 5349, 13649, 16, 203, 5411, 315, 12236, 5349, 711, 486, 5746, 4671, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 5508, 1648, 4075, 5349, 13649, 397, 6549, 22, 18, 25, 4681, 16, 203, 5411, 315, 12236, 5349, 711, 16926, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 2078, 5147, 273, 3844, 380, 7071, 5233, 900, 67, 7698, 1441, 31, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 2078, 5147, 16, 315, 5048, 11339, 284, 19156, 3271, 8863, 203, 203, 3639, 2254, 5034, 4463, 12236, 5349, 17353, 273, 7071, 5233, 900, 67, 28624, 67, 55, 11846, 31, 203, 3639, 2583, 12, 203, 5411, 3844, 1648, 4463, 12236, 5349, 17353, 16, 203, 5411, 315, 1248, 7304, 2430, 2319, 364, 23701, 6, 203, 3639, 11272, 203, 203, 3639, 389, 13866, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 3844, 1769, 203, 203, 3639, 1142, 23164, 4921, 63, 3576, 18, 15330, 65, 273, 1203, 18, 5508, 31, 203, 203, 3639, 309, 261, 3576, 18, 1132, 405, 2078, 5147, 13, 288, 203, 5411, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 3576, 18, 1132, 300, 2078, 5147, 1769, 203, 3639, 289, 203, 3639, 7071, 5233, 900, 67, 28624, 67, 55, 11846, 1011, 3844, 31, 203, 565, 289, 203, 203, 565, 445, 30143, 12236, 5349, 5157, 12, 11890, 5034, 3844, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 1941, 23701, 3844, 8863, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 5508, 1545, 4075, 5349, 13649, 16, 203, 5411, 315, 12236, 5349, 711, 486, 5746, 4671, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 5508, 1648, 4075, 5349, 13649, 397, 6549, 22, 18, 25, 4681, 16, 203, 5411, 315, 12236, 5349, 711, 16926, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 2078, 5147, 273, 3844, 380, 7071, 5233, 900, 67, 7698, 1441, 31, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 2078, 5147, 16, 315, 5048, 11339, 284, 19156, 3271, 8863, 203, 203, 3639, 2254, 5034, 4463, 12236, 5349, 17353, 273, 7071, 5233, 900, 67, 28624, 67, 55, 11846, 31, 203, 3639, 2583, 12, 203, 5411, 3844, 1648, 4463, 12236, 5349, 17353, 16, 203, 5411, 315, 1248, 7304, 2430, 2319, 364, 23701, 6, 203, 3639, 11272, 203, 203, 3639, 389, 13866, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 3844, 1769, 203, 203, 3639, 1142, 23164, 4921, 63, 3576, 18, 15330, 65, 273, 1203, 18, 5508, 31, 203, 203, 3639, 309, 261, 3576, 18, 1132, 405, 2078, 5147, 13, 288, 203, 5411, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 3576, 18, 1132, 300, 2078, 5147, 1769, 203, 3639, 289, 203, 3639, 7071, 5233, 900, 67, 28624, 67, 55, 11846, 1011, 3844, 31, 203, 565, 289, 203, 203, 565, 445, 2172, 7391, 12, 203, 3639, 1758, 8526, 3778, 12045, 16, 203, 3639, 2254, 5034, 8526, 3778, 30980, 203, 565, 262, 3903, 1338, 4446, 288, 203, 3639, 2583, 12, 203, 5411, 12045, 18, 2469, 422, 30980, 18, 2469, 16, 203, 5411, 315, 1076, 10917, 741, 486, 845, 6, 203, 3639, 11272, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 12045, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 8027, 273, 12045, 63, 77, 15533, 203, 5411, 2254, 5034, 3844, 273, 30980, 63, 77, 15533, 203, 203, 5411, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 1941, 8027, 1758, 8863, 203, 5411, 2583, 12, 8949, 405, 374, 16, 315, 1941, 3844, 8863, 203, 203, 5411, 399, 19851, 67, 28497, 67, 30762, 40, 1011, 3844, 31, 203, 5411, 2583, 12, 203, 7734, 399, 19851, 67, 28497, 67, 30762, 40, 1648, 12090, 4107, 67, 1013, 15277, 16, 203, 7734, 315, 5269, 7006, 14399, 12090, 4107, 67, 1013, 15277, 6, 203, 5411, 11272, 203, 203, 5411, 389, 13866, 12, 2867, 12, 2211, 3631, 8027, 16, 3844, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 2172, 7391, 12, 203, 3639, 2 ]
./full_match/1/0xA4c4808777c16F5A846C92173592272198103DaE/sources/contracts/RockPaperScissors_V8.sol
@dev min bet amount in wei
uint256 public minBetAmount;
3,130,728
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 1131, 2701, 3844, 316, 732, 77, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5034, 1071, 1131, 38, 278, 6275, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // Copied from Compound/ExponentialNoError /** * @title Exponential module for storing fixed-precision decimals * @author DeFil * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { 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 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 Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @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)}); } } interface Distributor { // The asset to be distributed function asset() external view returns (address); // Return the accrued amount of account based on stored data function accruedStored(address account) external view returns (uint); // Accrue and distribute for caller, but not actually transfer assets to the caller // returns the new accrued amount function accrue() external returns (uint); // Claim asset, transfer the given amount assets to receiver function claim(address receiver, uint amount) external returns (uint); } contract Redistributor is Distributor, ExponentialNoError { /** * @notice The superior Distributor contract */ Distributor public superior; // The accrued amount of this address in superior Distributor uint public superiorAccruedAmount; // The initial accrual index uint internal constant initialAccruedIndex = 1e36; // The last accrued block number uint public accrualBlockNumber; // The last accrued index uint public globalAccruedIndex; // Total count of shares. uint internal totalShares; struct AccountState { /// @notice The share of account uint share; // The last accrued index of account uint accruedIndex; /// @notice The accrued but not yet transferred to account uint accruedAmount; } // The AccountState for each account mapping(address => AccountState) internal accountStates; /*** Events ***/ // Emitted when dfl is accrued event Accrued(uint amount, uint globalAccruedIndex); // Emitted when distribute to a account event Distributed(address account, uint amount, uint accruedIndex); // Emitted when account claims asset event Claimed(address account, address receiver, uint amount); // Emitted when account transfer asset event Transferred(address from, address to, uint amount); constructor(Distributor superior_) public { // set superior superior = superior_; // init accrued index globalAccruedIndex = initialAccruedIndex; } function asset() external view returns (address) { return superior.asset(); } // Return the accrued amount of account based on stored data function accruedStored(address account) external view returns(uint) { uint storedGlobalAccruedIndex; if (totalShares == 0) { storedGlobalAccruedIndex = globalAccruedIndex; } else { uint superiorAccruedStored = superior.accruedStored(address(this)); uint delta = sub_(superiorAccruedStored, superiorAccruedAmount); Double memory ratio = fraction(delta, totalShares); Double memory doubleGlobalAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio); storedGlobalAccruedIndex = doubleGlobalAccruedIndex.mantissa; } (, uint instantAccountAccruedAmount) = accruedStoredInternal(account, storedGlobalAccruedIndex); return instantAccountAccruedAmount; } // Return the accrued amount of account based on stored data function accruedStoredInternal(address account, uint withGlobalAccruedIndex) internal view returns(uint, uint) { AccountState memory state = accountStates[account]; Double memory doubleGlobalAccruedIndex = Double({mantissa: withGlobalAccruedIndex}); Double memory doubleAccountAccruedIndex = Double({mantissa: state.accruedIndex}); if (doubleAccountAccruedIndex.mantissa == 0 && doubleGlobalAccruedIndex.mantissa > 0) { doubleAccountAccruedIndex.mantissa = initialAccruedIndex; } Double memory deltaIndex = sub_(doubleGlobalAccruedIndex, doubleAccountAccruedIndex); uint delta = mul_(state.share, deltaIndex); return (delta, add_(state.accruedAmount, delta)); } function accrueInternal() internal { uint blockNumber = getBlockNumber(); if (accrualBlockNumber == blockNumber) { return; } uint newSuperiorAccruedAmount = superior.accrue(); if (totalShares == 0) { accrualBlockNumber = blockNumber; return; } uint delta = sub_(newSuperiorAccruedAmount, superiorAccruedAmount); Double memory ratio = fraction(delta, totalShares); Double memory doubleAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio); // update globalAccruedIndex globalAccruedIndex = doubleAccruedIndex.mantissa; superiorAccruedAmount = newSuperiorAccruedAmount; accrualBlockNumber = blockNumber; emit Accrued(delta, doubleAccruedIndex.mantissa); } /** * @notice accrue and returns accrued stored of msg.sender */ function accrue() external returns (uint) { accrueInternal(); (, uint instantAccountAccruedAmount) = accruedStoredInternal(msg.sender, globalAccruedIndex); return instantAccountAccruedAmount; } function distributeInternal(address account) internal { (uint delta, uint instantAccruedAmount) = accruedStoredInternal(account, globalAccruedIndex); AccountState storage state = accountStates[account]; state.accruedIndex = globalAccruedIndex; state.accruedAmount = instantAccruedAmount; // emit Distributed event emit Distributed(account, delta, globalAccruedIndex); } function claim(address receiver, uint amount) external returns (uint) { address account = msg.sender; // keep fresh accrueInternal(); distributeInternal(account); AccountState storage state = accountStates[account]; require(amount <= state.accruedAmount, "claim: insufficient value"); // claim from superior require(superior.claim(receiver, amount) == amount, "claim: amount mismatch"); // update storage state.accruedAmount = sub_(state.accruedAmount, amount); superiorAccruedAmount = sub_(superiorAccruedAmount, amount); emit Claimed(account, receiver, amount); return amount; } function claimAll() external { address account = msg.sender; // accrue and distribute accrueInternal(); distributeInternal(account); AccountState storage state = accountStates[account]; uint amount = state.accruedAmount; // claim from superior require(superior.claim(account, amount) == amount, "claim: amount mismatch"); // update storage state.accruedAmount = 0; superiorAccruedAmount = sub_(superiorAccruedAmount, amount); emit Claimed(account, account, amount); } function transfer(address to, uint amount) external { address from = msg.sender; // keep fresh accrueInternal(); distributeInternal(from); AccountState storage fromState = accountStates[from]; uint actualAmount = amount; if (actualAmount == 0) { actualAmount = fromState.accruedAmount; } require(fromState.accruedAmount >= actualAmount, "transfer: insufficient value"); AccountState storage toState = accountStates[to]; // update storage fromState.accruedAmount = sub_(fromState.accruedAmount, actualAmount); toState.accruedAmount = add_(toState.accruedAmount, actualAmount); emit Transferred(from, to, actualAmount); } function getBlockNumber() public view returns (uint) { return block.number; } } /** * @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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @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 == msg.sender, "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 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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract PrivilegedRedistributor is Redistributor, Ownable { /// @notice A list of all valid members address[] public members; /// @notice Emitted when members changed event Changed(address[] newMembers, uint[] newPercentages); constructor(Distributor superior_) Redistributor(superior_) public {} function allMembers() external view returns (address[] memory, uint[] memory) { address[] memory storedMembers = members; uint[] memory percentages = new uint[](storedMembers.length); for (uint i = 0; i < storedMembers.length; i++) { percentages[i] = accountStates[storedMembers[i]].share; } return (storedMembers, percentages); } function memberState(address member) external view returns (uint, uint, uint) { AccountState memory state = accountStates[member]; return (state.share, state.accruedIndex, state.accruedAmount); } /*** Admin Functions ***/ /** * @notice Admin function to change members and their percentages */ function _setPercentages(uint[] calldata newPercentages) external onlyOwner { uint sumNewPercentagesMantissa; for (uint i = 0; i < newPercentages.length; i++) { sumNewPercentagesMantissa = add_(sumNewPercentagesMantissa, newPercentages[i]); } // Check sum of new percentages equals 1 require(sumNewPercentagesMantissa == mantissaOne, "_setPercentages: bad sum"); // reference storage address[] storage storedMembers = members; require(storedMembers.length == newPercentages.length, "_setPercentages: bad length"); // accrue first accrueInternal(); // distribute to members if its percentage changes for (uint i = 0; i < storedMembers.length; i++) { AccountState storage state = accountStates[storedMembers[i]]; distributeInternal(storedMembers[i]); // set new percentage for member state.share = newPercentages[i]; } emit Changed(storedMembers, newPercentages); } /** * @notice Admin function to change members and their percentages */ function _setMembers(address[] memory newMembers, uint[] memory newPercentages) public onlyOwner { require(newMembers.length == newPercentages.length, "_setMembers: bad length"); uint sumNewPercentagesMantissa; for (uint i = 0; i < newPercentages.length; i++) { require(newPercentages[i] != 0, "_setMembers: bad percentage"); sumNewPercentagesMantissa = add_(sumNewPercentagesMantissa, newPercentages[i]); } // Check sum of new percentages equals 1 require(sumNewPercentagesMantissa == mantissaOne, "_setMembers: bad sum"); // accrue first accrueInternal(); // distribute for old members address[] storage storedMembers = members; for (uint i = 0; i < storedMembers.length; i++) { distributeInternal(storedMembers[i]); AccountState storage state = accountStates[storedMembers[i]]; state.share = 0; } // clear old members storedMembers.length = 0; for (uint i = 0; i < newMembers.length; i++) { AccountState storage state = accountStates[newMembers[i]]; accountStates[newMembers[i]] = AccountState({share: newPercentages[i], accruedIndex: globalAccruedIndex, accruedAmount: state.accruedAmount}); storedMembers.push(newMembers[i]); } totalShares = mantissaOne; emit Changed(newMembers, newPercentages); } }
@notice A list of all valid members @notice Emitted when members changed
constructor(Distributor superior_) Redistributor(superior_) public {}
10,159,129
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 432, 666, 434, 777, 923, 4833, 632, 20392, 512, 7948, 1347, 4833, 3550, 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, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12, 1669, 19293, 2240, 9659, 67, 13, 8505, 19293, 12, 9565, 9659, 67, 13, 1071, 2618, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/40/0x2AE991C66cE9D9Fd4318e67B0b94E2B4170faa5D/sources/contracts/ProxyWithdrawal.sol
Transfer coins (only for owner) @param _to address Destination address @param _amount uint Transfer amount
function transferCoins(address _to, uint _amount) external onlyOwner { require(!_to.isContract(), "Withdrawal: target address is contract"); require(getBalance() >= _amount, "Withdrawal: balance not enough"); require(successFee, "Withdrawal: transfer failed"); emit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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 39, 9896, 12, 2867, 389, 869, 16, 2254, 389, 8949, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 5, 67, 869, 18, 291, 8924, 9334, 315, 1190, 9446, 287, 30, 1018, 1758, 353, 6835, 8863, 203, 3639, 2583, 12, 588, 13937, 1435, 1545, 389, 8949, 16, 315, 1190, 9446, 287, 30, 11013, 486, 7304, 8863, 203, 3639, 2583, 12, 4768, 14667, 16, 315, 1190, 9446, 287, 30, 7412, 2535, 8863, 203, 3639, 3626, 12279, 1133, 24899, 869, 16, 389, 8949, 16, 1758, 12, 20, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: AGPL-3.0-or-later pragma solidity 0.6.11; // 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 (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint); /** * @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, uint 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 (uint); /** * @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, uint 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, uint 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, uint 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, uint 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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint a, uint b) internal pure returns (bool, uint) { uint 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (bool, uint) { // 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); uint 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (uint) { uint 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { 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) { // 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. uint 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, uint 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, uint 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, uint 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); } } } } // 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 IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer( IERC20 token, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint 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, uint 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, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint value ) internal { uint 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" ); } } } // File: contracts/protocol/IStrategy.sol /* version 1.2.0 Changes Changes listed here do not affect interaction with other contracts (Vault and Controller) - removed function assets(address _token) external view returns (bool); - remove function deposit(uint), declared in IStrategyERC20 - add function setSlippage(uint _slippage); - add function setDelta(uint _delta); */ interface IStrategy { function admin() external view returns (address); function controller() external view returns (address); function vault() external view returns (address); /* @notice Returns address of underlying asset (ETH or ERC20) @dev Must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy */ function underlying() external view returns (address); /* @notice Returns total amount of underlying transferred from vault */ function totalDebt() external view returns (uint); function performanceFee() external view returns (uint); function slippage() external view returns (uint); /* @notice Multiplier used to check total underlying <= total debt * delta / DELTA_MIN */ function delta() external view returns (uint); /* @dev Flag to force exit in case normal exit fails */ function forceExit() external view returns (bool); function setAdmin(address _admin) external; function setController(address _controller) external; function setPerformanceFee(uint _fee) external; function setSlippage(uint _slippage) external; function setDelta(uint _delta) external; function setForceExit(bool _forceExit) external; /* @notice Returns amount of underlying asset locked in this contract @dev Output may vary depending on price of liquidity provider token where the underlying asset is invested */ function totalAssets() external view returns (uint); /* @notice Withdraw `_amount` underlying asset @param amount Amount of underlying asset to withdraw */ function withdraw(uint _amount) external; /* @notice Withdraw all underlying asset from strategy */ function withdrawAll() external; /* @notice Sell any staking rewards for underlying and then deposit undelying */ function harvest() external; /* @notice Increase total debt if profit > 0 and total assets <= max, otherwise transfers profit to vault. @dev Guard against manipulation of external price feed by checking that total assets is below factor of total debt */ function skim() external; /* @notice Exit from strategy @dev Must transfer all underlying tokens back to vault */ function exit() external; /* @notice Transfer token accidentally sent here to admin @param _token Address of token to transfer @dev _token must not be equal to underlying token */ function sweep(address _token) external; } // File: contracts/protocol/IStrategyERC20.sol interface IStrategyERC20 is IStrategy { /* @notice Deposit `amount` underlying ERC20 token @param amount Amount of underlying ERC20 token to deposit */ function deposit(uint _amount) external; } // File: contracts/protocol/IController.sol interface IController { function ADMIN_ROLE() external view returns (bytes32); function HARVESTER_ROLE() external view returns (bytes32); function admin() external view returns (address); function treasury() external view returns (address); function setAdmin(address _admin) external; function setTreasury(address _treasury) external; function grantRole(bytes32 _role, address _addr) external; function revokeRole(bytes32 _role, address _addr) external; /* @notice Set strategy for vault @param _vault Address of vault @param _strategy Address of strategy @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy( address _vault, address _strategy, uint _min ) external; // calls to strategy /* @notice Invest token in vault into strategy @param _vault Address of vault */ function invest(address _vault) external; function harvest(address _strategy) external; function skim(address _strategy) external; /* @notice Withdraw from strategy to vault @param _strategy Address of strategy @param _amount Amount of underlying token to withdraw @param _min Minimum amount of underlying token to withdraw */ function withdraw( address _strategy, uint _amount, uint _min ) external; /* @notice Withdraw all from strategy to vault @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function withdrawAll(address _strategy, uint _min) external; /* @notice Exit from strategy @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function exit(address _strategy, uint _min) external; } // File: contracts/StrategyERC20.sol /* version 1.2.0 Changes from StrategyBase - performance fee capped at 20% - add slippage gaurd - update skim(), increments total debt withoud withdrawing if total assets is near total debt - sweep - delete mapping "assets" and use require to explicitly check protected tokens - add immutable to vault - add immutable to underlying - add force exit */ // used inside harvest abstract contract StrategyERC20 is IStrategyERC20 { using SafeERC20 for IERC20; using SafeMath for uint; address public override admin; address public override controller; address public immutable override vault; address public immutable override underlying; // total amount of underlying transferred from vault uint public override totalDebt; // performance fee sent to treasury when harvest() generates profit uint public override performanceFee = 500; uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee uint internal constant PERFORMANCE_FEE_MAX = 10000; // prevent slippage from deposit / withdraw uint public override slippage = 100; uint internal constant SLIPPAGE_MAX = 10000; /* Multiplier used to check totalAssets() is <= total debt * delta / DELTA_MIN */ uint public override delta = 10050; uint private constant DELTA_MIN = 10000; // Force exit, in case normal exit fails bool public override forceExit; constructor( address _controller, address _vault, address _underlying ) public { require(_controller != address(0), "controller = zero address"); require(_vault != address(0), "vault = zero address"); require(_underlying != address(0), "underlying = zero address"); admin = msg.sender; controller = _controller; vault = _vault; underlying = _underlying; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyAuthorized() { require( msg.sender == admin || msg.sender == controller || msg.sender == vault, "!authorized" ); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function setController(address _controller) external override onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } function setPerformanceFee(uint _fee) external override onlyAdmin { require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap"); performanceFee = _fee; } function setSlippage(uint _slippage) external override onlyAdmin { require(_slippage <= SLIPPAGE_MAX, "slippage > max"); slippage = _slippage; } function setDelta(uint _delta) external override onlyAdmin { require(_delta >= DELTA_MIN, "delta < min"); delta = _delta; } function setForceExit(bool _forceExit) external override onlyAdmin { forceExit = _forceExit; } function _increaseDebt(uint _underlyingAmount) private { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransferFrom(vault, address(this), _underlyingAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); totalDebt = totalDebt.add(balAfter.sub(balBefore)); } function _decreaseDebt(uint _underlyingAmount) private { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransfer(vault, _underlyingAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balBefore.sub(balAfter); if (diff >= totalDebt) { totalDebt = 0; } else { totalDebt -= diff; } } function _totalAssets() internal view virtual returns (uint); /* @notice Returns amount of underlying tokens locked in this contract */ function totalAssets() external view override returns (uint) { return _totalAssets(); } function _deposit() internal virtual; /* @notice Deposit underlying token into this strategy @param _underlyingAmount Amount of underlying token to deposit */ function deposit(uint _underlyingAmount) external override onlyAuthorized { require(_underlyingAmount > 0, "deposit = 0"); _increaseDebt(_underlyingAmount); _deposit(); } /* @notice Returns total shares owned by this contract for depositing underlying into external Defi */ function _getTotalShares() internal view virtual returns (uint); function _getShares(uint _underlyingAmount, uint _totalUnderlying) internal view returns (uint) { /* calculate shares to withdraw w = amount of underlying to withdraw U = total redeemable underlying s = shares to withdraw P = total shares deposited into external liquidity pool w / U = s / P s = w / U * P */ if (_totalUnderlying > 0) { uint totalShares = _getTotalShares(); return _underlyingAmount.mul(totalShares) / _totalUnderlying; } return 0; } function _withdraw(uint _shares) internal virtual; /* @notice Withdraw undelying token to vault @param _underlyingAmount Amount of underlying token to withdraw @dev Caller should implement guard against slippage */ function withdraw(uint _underlyingAmount) external override onlyAuthorized { require(_underlyingAmount > 0, "withdraw = 0"); uint totalUnderlying = _totalAssets(); require(_underlyingAmount <= totalUnderlying, "withdraw > total"); uint shares = _getShares(_underlyingAmount, totalUnderlying); if (shares > 0) { _withdraw(shares); } // transfer underlying token to vault /* WARNING: Here we are transferring all funds in this contract. This operation is safe under 2 conditions: 1. This contract does not hold any funds at rest. 2. Vault does not allow user to withdraw excess > _underlyingAmount */ uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { _decreaseDebt(underlyingBal); } } function _withdrawAll() internal { uint totalShares = _getTotalShares(); if (totalShares > 0) { _withdraw(totalShares); } uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { IERC20(underlying).safeTransfer(vault, underlyingBal); totalDebt = 0; } } /* @notice Withdraw all underlying to vault @dev Caller should implement guard agains slippage */ function withdrawAll() external override onlyAuthorized { _withdrawAll(); } /* @notice Sell any staking rewards for underlying and then deposit undelying */ function harvest() external virtual override; /* @notice Increase total debt if profit > 0 and total assets <= max, otherwise transfers profit to vault. @dev Guard against manipulation of external price feed by checking that total assets is below factor of total debt */ function skim() external override onlyAuthorized { uint totalUnderlying = _totalAssets(); require(totalUnderlying > totalDebt, "total underlying < debt"); uint profit = totalUnderlying - totalDebt; // protect against price manipulation uint max = totalDebt.mul(delta) / DELTA_MIN; if (totalUnderlying <= max) { /* total underlying is within reasonable bounds, probaly no price manipulation occured. */ /* If we were to withdraw profit followed by deposit, this would increase the total debt roughly by the profit. Withdrawing consumes high gas, so here we omit it and directly increase debt, as if withdraw and deposit were called. */ totalDebt = totalDebt.add(profit); } else { /* Possible reasons for total underlying > max 1. total debt = 0 2. total underlying really did increase over max 3. price was manipulated */ uint shares = _getShares(profit, totalUnderlying); if (shares > 0) { uint balBefore = IERC20(underlying).balanceOf(address(this)); _withdraw(shares); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balAfter.sub(balBefore); if (diff > 0) { IERC20(underlying).safeTransfer(vault, diff); } } } } function exit() external virtual override; function sweep(address) external virtual override; } // File: contracts/interfaces/uniswap/Uniswap.sol interface Uniswap { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, 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); } // File: contracts/interfaces/curve/LiquidityGauge.sol // https://github.com/curvefi/curve-contract/blob/master/contracts/gauges/LiquidityGauge.vy interface LiquidityGauge { function deposit(uint) external; function balanceOf(address) external view returns (uint); function withdraw(uint) external; } // File: contracts/interfaces/curve/Minter.sol // https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy interface Minter { function mint(address) external; } // File: contracts/interfaces/curve/StableSwapGusd.sol interface StableSwapGusd { function get_virtual_price() external view returns (uint); /* 0 GUSD 1 3CRV */ function balances(uint index) external view returns (uint); } // File: contracts/interfaces/curve/StableSwap3Pool.sol interface StableSwap3Pool { function get_virtual_price() external view returns (uint); function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin( uint token_amount, int128 i, uint min_uamount ) external; function balances(uint index) external view returns (uint); } // File: contracts/interfaces/curve/DepositGusd.sol interface DepositGusd { /* 0 GUSD 1 DAI 2 USDC 3 USDT */ function add_liquidity(uint[4] memory amounts, uint min) external returns (uint); function remove_liquidity_one_coin( uint amount, int128 index, uint min ) external returns (uint); } // File: contracts/strategies/StrategyGusdV2.sol contract StrategyGusdV2 is StrategyERC20 { // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant GUSD = 0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd; address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // GUSD = 0 | DAI = 1 | USDC = 2 | USDT = 3 uint private immutable UNDERLYING_INDEX; // precision to convert 10 ** 18 to underlying decimals uint[4] private PRECISION_DIV = [1e16, 1, 1e12, 1e12]; // precision div of underlying token (used to save gas) uint private immutable PRECISION_DIV_UNDERLYING; // Curve // // StableSwap3Pool address private constant BASE_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // StableSwapGusd address private constant SWAP = 0x4f062658EaAF2C1ccf8C8e36D6824CDf41167956; // liquidity provider token (GUSD / 3CRV) address private constant LP = 0xD2967f45c4f384DEEa880F807Be904762a3DeA07; // DepositGusd address private constant DEPOSIT = 0x64448B78561690B70E17CBE8029a3e5c1bB7136e; // LiquidityGauge address private constant GAUGE = 0xC5cfaDA84E902aD92DD40194f0883ad49639b023; // Minter address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // CRV address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; constructor( address _controller, address _vault, address _underlying, uint _underlyingIndex ) public StrategyERC20(_controller, _vault, _underlying) { UNDERLYING_INDEX = _underlyingIndex; PRECISION_DIV_UNDERLYING = PRECISION_DIV[_underlyingIndex]; // These tokens are never held by this contract // so the risk of them getting stolen is minimal IERC20(CRV).safeApprove(UNISWAP, uint(-1)); } function _totalAssets() internal view override returns (uint) { uint lpBal = LiquidityGauge(GAUGE).balanceOf(address(this)); uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price(); return lpBal.mul(pricePerShare) / (PRECISION_DIV_UNDERLYING * 1e18); } /* @notice deposit token into curve */ function _depositIntoCurve(address _token, uint _index) private { // token to LP uint bal = IERC20(_token).balanceOf(address(this)); if (bal > 0) { IERC20(_token).safeApprove(DEPOSIT, 0); IERC20(_token).safeApprove(DEPOSIT, bal); // mint LP uint[4] memory amounts; amounts[_index] = bal; /* shares = underlying amount * precision div * 1e18 / price per share */ uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price(); uint shares = bal.mul(PRECISION_DIV[_index]).mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; DepositGusd(DEPOSIT).add_liquidity(amounts, min); } // stake into LiquidityGauge uint lpBal = IERC20(LP).balanceOf(address(this)); if (lpBal > 0) { IERC20(LP).safeApprove(GAUGE, 0); IERC20(LP).safeApprove(GAUGE, lpBal); LiquidityGauge(GAUGE).deposit(lpBal); } } /* @notice Deposits underlying to LiquidityGauge */ function _deposit() internal override { _depositIntoCurve(underlying, UNDERLYING_INDEX); } function _getTotalShares() internal view override returns (uint) { return LiquidityGauge(GAUGE).balanceOf(address(this)); } function _withdraw(uint _lpAmount) internal override { // withdraw LP from LiquidityGauge LiquidityGauge(GAUGE).withdraw(_lpAmount); // withdraw underlying // uint lpBal = IERC20(LP).balanceOf(address(this)); // remove liquidity IERC20(LP).safeApprove(DEPOSIT, 0); IERC20(LP).safeApprove(DEPOSIT, lpBal); /* underlying amount = (shares * price per shares) / (1e18 * precision div) */ uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price(); uint underlyingAmount = lpBal.mul(pricePerShare) / (PRECISION_DIV_UNDERLYING * 1e18); uint min = underlyingAmount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; // withdraw creates LP dust DepositGusd(DEPOSIT).remove_liquidity_one_coin( lpBal, int128(UNDERLYING_INDEX), min ); // Now we have underlying } /* @notice Returns address and index of token with lowest balance in Curve StableSwap */ function _getMostPremiumToken() internal view returns (address, uint) { // meta pool balances uint[2] memory balances; balances[0] = StableSwapGusd(SWAP).balances(0).mul(1e16); // GUSD balances[1] = StableSwapGusd(SWAP).balances(1); // 3CRV if (balances[0] <= balances[1]) { return (GUSD, 0); } else { // base pool balances uint[3] memory baseBalances; baseBalances[0] = StableSwap3Pool(BASE_POOL).balances(0); // DAI baseBalances[1] = StableSwap3Pool(BASE_POOL).balances(1).mul(1e12); // USDC baseBalances[2] = StableSwap3Pool(BASE_POOL).balances(2).mul(1e12); // USDT /* DAI 1 USDC 2 USDT 3 */ // DAI if ( baseBalances[0] <= baseBalances[1] && baseBalances[0] <= baseBalances[2] ) { return (DAI, 1); } // USDC if ( baseBalances[1] <= baseBalances[0] && baseBalances[1] <= baseBalances[2] ) { return (USDC, 2); } return (USDT, 3); } } /* @dev Uniswap fails with zero address so no check is necessary here */ function _swap( address _from, address _to, uint _amount ) private { // create dynamic array with 3 elements address[] memory path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; Uniswap(UNISWAP).swapExactTokensForTokens( _amount, 1, path, address(this), block.timestamp ); } function _claimRewards(address _token) private { // claim CRV Minter(MINTER).mint(GAUGE); uint crvBal = IERC20(CRV).balanceOf(address(this)); // Swap only if CRV >= 1, otherwise swap may fail for small amount of GUSD if (crvBal >= 1e18) { _swap(CRV, _token, crvBal); // Now this contract has token } } /* @notice Claim CRV and deposit most premium token into Curve */ function harvest() external override onlyAuthorized { (address token, uint index) = _getMostPremiumToken(); _claimRewards(token); uint bal = IERC20(token).balanceOf(address(this)); if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); IERC20(token).safeTransfer(treasury, fee); } _depositIntoCurve(token, index); } } /* @notice Exit strategy by harvesting CRV to underlying token and then withdrawing all underlying to vault @dev Must return all underlying token to vault @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { if (forceExit) { return; } _claimRewards(underlying); _withdrawAll(); } function sweep(address _token) external override onlyAdmin { require(_token != underlying, "protected token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } } // File: contracts/strategies/StrategyGusdDaiV2.sol contract StrategyGusdDaiV2 is StrategyGusdV2 { constructor(address _controller, address _vault) public StrategyGusdV2(_controller, _vault, DAI, 1) {} }
// protect against price manipulation/
function harvest() external virtual override; @notice Increase total debt if profit > 0 and total assets <= max, otherwise transfers profit to vault. @dev Guard against manipulation of external price feed by checking that total assets is below factor of total debt function skim() external override onlyAuthorized { uint totalUnderlying = _totalAssets(); require(totalUnderlying > totalDebt, "total underlying < debt"); uint profit = totalUnderlying - totalDebt; uint max = totalDebt.mul(delta) / DELTA_MIN; if (totalUnderlying <= max) { total underlying is within reasonable bounds, probaly no price manipulation occured. If we were to withdraw profit followed by deposit, this would increase the total debt roughly by the profit. Withdrawing consumes high gas, so here we omit it and directly increase debt, as if withdraw and deposit were called. totalDebt = totalDebt.add(profit); Possible reasons for total underlying > max 1. total debt = 0 2. total underlying really did increase over max 3. price was manipulated uint shares = _getShares(profit, totalUnderlying); if (shares > 0) { uint balBefore = IERC20(underlying).balanceOf(address(this)); _withdraw(shares); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balAfter.sub(balBefore); if (diff > 0) { IERC20(underlying).safeTransfer(vault, diff); } } } }
54,463
[ 1, 4625, 348, 7953, 560, 30, 368, 17151, 5314, 6205, 27029, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17895, 26923, 1435, 3903, 5024, 3849, 31, 203, 203, 565, 632, 20392, 657, 11908, 2078, 18202, 88, 309, 450, 7216, 405, 374, 471, 2078, 7176, 1648, 943, 16, 203, 5411, 3541, 29375, 450, 7216, 358, 9229, 18, 203, 565, 632, 5206, 22809, 5314, 27029, 434, 3903, 6205, 4746, 635, 6728, 716, 203, 540, 2078, 7176, 353, 5712, 5578, 434, 2078, 18202, 88, 203, 565, 445, 4343, 381, 1435, 3903, 3849, 1338, 15341, 288, 203, 3639, 2254, 2078, 14655, 6291, 273, 389, 4963, 10726, 5621, 203, 3639, 2583, 12, 4963, 14655, 6291, 405, 2078, 758, 23602, 16, 315, 4963, 6808, 411, 18202, 88, 8863, 203, 203, 3639, 2254, 450, 7216, 273, 2078, 14655, 6291, 300, 2078, 758, 23602, 31, 203, 203, 3639, 2254, 943, 273, 2078, 758, 23602, 18, 16411, 12, 9878, 13, 342, 2030, 48, 9833, 67, 6236, 31, 203, 3639, 309, 261, 4963, 14655, 6291, 1648, 943, 13, 288, 203, 5411, 2078, 6808, 353, 3470, 23589, 4972, 16, 3137, 3450, 1158, 6205, 203, 5411, 27029, 16206, 18, 203, 203, 5411, 971, 732, 4591, 358, 598, 9446, 450, 7216, 10860, 635, 443, 1724, 16, 333, 4102, 203, 5411, 10929, 326, 2078, 18202, 88, 23909, 715, 635, 326, 450, 7216, 18, 203, 203, 5411, 3423, 9446, 310, 25479, 3551, 16189, 16, 1427, 2674, 732, 14088, 518, 471, 203, 5411, 5122, 10929, 18202, 88, 16, 487, 309, 598, 9446, 471, 443, 1724, 4591, 2566, 18, 203, 5411, 2078, 758, 23602, 273, 2078, 758, 23602, 18, 1289, 12, 685, 7216, 1769, 203, 5411, 25433, 14000, 364, 2078, 6808, 405, 943, 203, 5411, 404, 18, 2078, 18202, 88, 273, 374, 203, 5411, 576, 18, 2078, 6808, 8654, 5061, 10929, 1879, 943, 203, 5411, 890, 18, 6205, 1703, 13441, 11799, 203, 5411, 2254, 24123, 273, 389, 588, 24051, 12, 685, 7216, 16, 2078, 14655, 6291, 1769, 203, 5411, 309, 261, 30720, 405, 374, 13, 288, 203, 7734, 2254, 324, 287, 4649, 273, 467, 654, 39, 3462, 12, 9341, 6291, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 7734, 389, 1918, 9446, 12, 30720, 1769, 203, 7734, 2254, 324, 287, 4436, 273, 467, 654, 39, 3462, 12, 9341, 6291, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 203, 7734, 2254, 3122, 273, 324, 287, 4436, 18, 1717, 12, 70, 287, 4649, 1769, 203, 7734, 309, 261, 5413, 405, 374, 13, 288, 203, 10792, 467, 654, 39, 3462, 12, 9341, 6291, 2934, 4626, 5912, 12, 26983, 16, 3122, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * Project RESERVED * Here you can see the code with comments * Enjoy :) **/ pragma solidity ^0.4.24; contract RESERVED { address owner; //address of contract creator address investor; //address of user who just invested money to the contract mapping (address => uint256) balances; //amount of investment for each address mapping (address => uint256) timestamp; //time from the last payment for each address mapping (address => uint16) rate; //rate for each address mapping (address => uint256) referrers; //structure for checking whether investor had referrer or not uint16 default_rate = 300; //default rate (minimal rate) for investors uint16 max_rate = 1000; //maximal possible rate uint256 eth = 1000000000000000000; //eth in wei uint256 jackpot = 0; //amount of jackpot uint256 random_number; //random number from 1 to 100 uint256 referrer_bonus; //amount of referrer bonus uint256 deposit; //amount of investment uint256 day = 86400; //seconds in 24 hours bytes msg_data; //referrer address //Store owner as a person created that contract constructor() public { owner = msg.sender;} //Function calls in the moment of investment function() external payable{ deposit = msg.value; //amount of investment investor = msg.sender; //address of investor msg_data = bytes(msg.data); //address of referrer owner.transfer(deposit / 10); //transfers 10% to the advertisement fund tryToWin(); //jackpot sendPayment(); //sends payment to investors updateRate(); //updates rates of investors depending on amount of investment upgradeReferrer(); //sends bonus to referrers and upgrates their rates, also increases the rate of referral } //Collects jackpot and sends it to lucky investor function tryToWin() internal{ random_number = uint(blockhash(block.number-1))%100 + 1; if (deposit >= (eth / 10) && random_number<(deposit/(eth / 10) + 1) && jackpot>0) { investor.transfer(jackpot); jackpot = deposit / 20; } else jackpot += deposit / 20; } //Sends payment to investor function sendPayment() internal{ if (balances[investor] != 0){ uint256 paymentAmount = balances[investor]*rate[investor]/10000*(now-timestamp[investor])/day; investor.transfer(paymentAmount); } timestamp[investor] = now; balances[investor] += deposit; } //Assigns a rate depending on the amount of the deposit function updateRate() internal{ require (balances[investor]>0); if (balances[investor]>=(10*eth) && rate[investor]<default_rate+75){ rate[investor]=default_rate+75; } else if (balances[investor]>=(5*eth) && rate[investor]<default_rate+50){ rate[investor]=default_rate+50; } else if (balances[investor]>=eth && rate[investor]<default_rate+25){ rate[investor]=default_rate+25; } else if (rate[investor]<default_rate){ rate[investor]=default_rate; } } //Sends bonus to referrers and upgrates their rates, also increases the rate of referral function upgradeReferrer() internal{ if(msg_data.length == 20 && referrers[investor] == 0) { address referrer = bytesToAddress(msg_data); if(referrer != investor && balances[referrer]>0){ referrers[investor] = 1; rate[investor] += 50; referrer_bonus = deposit * rate[referrer] / 10000; referrer.transfer(referrer_bonus); if(rate[referrer]<max_rate){ if (deposit >= 10*eth){ rate[referrer] = rate[referrer] + 100; } else if (deposit >= 3*eth){ rate[referrer] = rate[referrer] + 50; } else if (deposit >= eth / 2){ rate[referrer] = rate[referrer] + 25; } else if (deposit >= eth / 10){ rate[referrer] = rate[referrer] + 10; } } } } referrers[investor] = 1; //Protection from the writing referrer address with the next investment } //Transmits bytes to address function bytesToAddress(bytes source) internal pure returns(address) { uint result; uint mul = 1; for(uint i = 20; i > 0; i--) { result += uint8(source[i-1])*mul; mul = mul*256; } return address(result); } }
rate for each address
mapping (address => uint16) rate;
12,849,030
[ 1, 4625, 348, 7953, 560, 30, 4993, 364, 1517, 1758, 7010, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 261, 2867, 516, 2254, 2313, 13, 4993, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]