file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
./full_match/43113/0x9B21EB2E30D8320c3c1b8d8465284D78E58cB971/sources/contracts/PriceOracle/PriceOracleV1.sol
* @dev Checks if first Exp is less than second Exp./
function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { }
7,198,113
[ 1, 4081, 309, 1122, 7784, 353, 5242, 2353, 2205, 7784, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5242, 9516, 2966, 12, 2966, 3778, 2002, 16, 7784, 3778, 2145, 13, 2713, 16618, 1135, 261, 6430, 13, 288, 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 ]
./full_match/4/0x86755DB3A4474bDb53ED039D6Feb39528938B08c/sources/browser/DefiPortal.sol
param _additionalData require uint256 minReturn (uint256 minReturn) = abi.decode(_additionalData, (uint256)); IYearnToken yToken = IYearnToken(yTokenAddress); transfer underlying from sender _transferFromSenderAndApproveTo(IERC20(yTokenAddress), sharesAmount, yTokenAddress); mint yToken yToken.withdraw(sharesAmount); get underlying address address underlyingToken = yToken.token(); get received tokens uint256 received = IERC20(underlyingToken).balanceOf(address(this)); min return check require(received >= minReturn, "MIN_RETURN_FAIL"); send underlying to sender IERC20(underlyingToken).transfer(msg.sender, received); send remains if there is some remains _sendRemains(IERC20(yTokenAddress), msg.sender); return data tokensToReceive = new address[](1); tokensToReceive[0] = underlyingToken; amountsToReceive = new uint256[](1); amountsToReceive[0] = received;
function _YearnWithdraw( address yTokenAddress, uint256 sharesAmount, bytes memory _additionalData ) private returns( address[] memory tokensToReceive, uint256[] memory amountsToReceive ) { }
787,742
[ 1, 891, 389, 13996, 751, 2583, 225, 2254, 5034, 1131, 990, 261, 11890, 5034, 1131, 990, 13, 273, 24126, 18, 3922, 24899, 13996, 751, 16, 261, 11890, 5034, 10019, 467, 61, 73, 1303, 1345, 677, 1345, 273, 467, 61, 73, 1303, 1345, 12, 93, 1345, 1887, 1769, 225, 7412, 6808, 628, 5793, 389, 13866, 1265, 12021, 1876, 12053, 537, 774, 12, 45, 654, 39, 3462, 12, 93, 1345, 1887, 3631, 24123, 6275, 16, 677, 1345, 1887, 1769, 225, 312, 474, 677, 1345, 677, 1345, 18, 1918, 9446, 12, 30720, 6275, 1769, 225, 336, 6808, 1758, 1758, 6808, 1345, 273, 677, 1345, 18, 2316, 5621, 225, 336, 5079, 2430, 2254, 5034, 5079, 273, 467, 654, 39, 3462, 12, 9341, 6291, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 225, 1131, 327, 866, 2583, 12, 15213, 1545, 1131, 990, 16, 315, 6236, 67, 14033, 67, 12319, 8863, 225, 1366, 6808, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 225, 445, 389, 61, 73, 1303, 1190, 9446, 12, 203, 565, 1758, 677, 1345, 1887, 16, 203, 565, 2254, 5034, 24123, 6275, 16, 203, 565, 1731, 3778, 389, 13996, 751, 203, 225, 262, 203, 565, 3238, 203, 565, 1135, 12, 203, 565, 1758, 8526, 3778, 2430, 774, 11323, 16, 203, 565, 2254, 5034, 8526, 3778, 3844, 11634, 11323, 203, 565, 262, 203, 225, 288, 203, 225, 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 ]
./partial_match/1/0x032e28CF160b1f86197C3829edB4776FD796266b/sources/TYCOPY.sol
Anti-bot and anti-whale mappings and variables Seller Map Blacklist Map block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract TYCOPY is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0x000000000000000000000000000000000000dEaD); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 7200 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; mapping (address => uint256) private _holderFirstBuyTimestamp; mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public earlySellLiquidityFee; uint256 public earlySellMarketingFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; uint256 launchedAt; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("THANKS COPY", "TRADERS") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 24; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 66; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 0; uint256 totalSupply = 1 * 1e8 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; launchedAt = block.number; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.5%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 15 / 1000)/1e18, "Cannot set maxWallet lower than 1.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 40, "Must keep fees at 40% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 99, "Must keep fees at 99% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if (block.number <= (launchedAt + 1) && function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { 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 addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, deadAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: address(this).balance}(""); function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
4,419,982
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4352, 749, 1635, 22467, 1098, 1635, 1203, 1300, 434, 10191, 1284, 7459, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6835, 22153, 24875, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 1769, 203, 7010, 565, 1426, 3238, 7720, 1382, 31, 203, 7010, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 7010, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 7010, 565, 1426, 1071, 12423, 38, 321, 1526, 273, 638, 31, 203, 565, 2254, 5034, 1071, 12423, 38, 321, 13865, 273, 2371, 6976, 3974, 31, 203, 565, 2254, 5034, 1071, 1142, 48, 84, 38, 321, 950, 31, 203, 7010, 565, 2254, 5034, 1071, 11297, 38, 321, 13865, 273, 5196, 6824, 31, 203, 565, 2254, 5034, 1071, 1142, 25139, 48, 84, 38, 321, 950, 31, 203, 7010, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 565, 1426, 1071, 4237, 41, 20279, 55, 1165, 7731, 273, 638, 31, 203, 7010, 7010, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3759, 38, 2 ]
pragma solidity ^0.4.23; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer( address indexed _from, address indexed _to, uint256 _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received( address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } /** * @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; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } /** * @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; } } /** * @title CryptoArte * CryptoArte - a non-fungible token smart contract for * paintings from the www.cryptoarte.io collection */ contract CryptoArte is ERC721Token, Ownable { // Token id to painting image file hash mapping mapping (uint256 => uint256) public tokenIdToHash; constructor() ERC721Token("CryptoArte", "CARTE") public { } /** * @dev Mints a token to an address with a tokenURI and tokenHash. * @param _to address of the future owner of the token * @param _tokenId uint256 token ID (painting number) * @param _tokenURI string token metadata URI * @param _tokenHash uint256 token image Hash */ function mintTo(address _to, string _tokenURI, uint256 _tokenId, uint256 _tokenHash) public onlyOwner { _mint(_to, _tokenId); _setTokenURI(_tokenId, _tokenURI); tokenIdToHash[_tokenId] = _tokenHash; } /** * @dev Mints many tokens to an address with their tokenURIs and tokenHashes. * @param _to address of the future owner of the tokens * @param _tokenIds uint256 array of token IDs (painting numbers) * @param _tokenURIPrefix string prefix for token metadata URI * @param _tokenHashes uint256 array of token image Hashes */ function mintManyTo(address _to, string _tokenURIPrefix, uint256[] _tokenIds, uint256[] _tokenHashes) public onlyOwner { require(_tokenIds.length >= 1); require(_tokenIds.length == _tokenHashes.length); for (uint i = 0; i < _tokenIds.length; i++) { _mint(_to, _tokenIds[i]); _setTokenURI(_tokenIds[i], strConcat(_tokenURIPrefix, uint256Tostr(_tokenIds[i]))); tokenIdToHash[_tokenIds[i]] = _tokenHashes[i]; } } /** * @dev Updates tokenURI for tokenId - to be used to correct errors * @dev Throws if the tokenId does not exist * @param _tokenId uint256 token ID (painting number) * @param _tokenURI string token metadata URI */ function setTokenURI(string _tokenURI, uint256 _tokenId) public onlyOwner { _setTokenURI(_tokenId, _tokenURI); } /** * @dev Updates tokenHash for tokenId - to be used only to correct errors * @dev Throws if the tokenId does not exist * @param _tokenId uint256 token ID (painting number) * @param _tokenHash uint256 token image Hash */ function setTokenHash(uint256 _tokenHash, uint256 _tokenId) public onlyOwner { require(exists(_tokenId)); tokenIdToHash[_tokenId] = _tokenHash; } /** * @dev Contatenates two strings * @param _a string first (left) * @param _b string second (right) */ function strConcat(string _a, string _b) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i]; return string(bab); } /** * @dev Converts a uint256 to string * @param _i uint256 the uint to convert */ function uint256Tostr(uint256 _i) internal pure returns (string) { if (_i == 0) return "0"; uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0){ bstr[k--] = byte(48 + _i % 10); _i /= 10; } return string(bstr); } }
* @dev Updates tokenURI for tokenId - to be used to correct errors @dev Throws if the tokenId does not exist @param _tokenId uint256 token ID (painting number) @param _tokenURI string token metadata URI/
function setTokenURI(string _tokenURI, uint256 _tokenId) public onlyOwner { _setTokenURI(_tokenId, _tokenURI); }
5,730,114
[ 1, 5121, 1147, 3098, 364, 1147, 548, 300, 358, 506, 1399, 358, 3434, 1334, 225, 22435, 309, 326, 1147, 548, 1552, 486, 1005, 225, 389, 2316, 548, 2254, 5034, 1147, 1599, 261, 84, 1598, 310, 1300, 13, 225, 389, 2316, 3098, 533, 1147, 1982, 3699, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22629, 3098, 12, 1080, 389, 2316, 3098, 16, 2254, 5034, 389, 2316, 548, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 542, 1345, 3098, 24899, 2316, 548, 16, 389, 2316, 3098, 1769, 203, 565, 289, 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 ]
pragma solidity ^0.4.24; contract Register { //create a mapping to match an account to the ipfs data storage mapping(address => string) private users; //at the registration, any user gets an address with their ipfs hash. Store this transaction on the blockchain function addUserAddress (string memory _ipfsHashAccountdata) public { //check if the address is not existing in mapping require(bytes(users[msg.sender]).length == 0); //add ipfs hash value to account users[msg.sender] = _ipfsHashAccountdata; } //at the registration, any user gets an address with their ipfs hash. Store this transaction on the blockchain function editUser(string memory _ipfsHashAccountdata) public { //add ipfs hash value to account users[msg.sender] = _ipfsHashAccountdata; } //get ipfs hash matched to account function getPersonalIPFSHash() public view returns(string memory){ return users[msg.sender]; } //get ipfs hash matched to specific address function getPersonalIPFSHashForProvider(address patientAddress) public view returns(string memory){ return users[patientAddress]; } }
get ipfs hash matched to specific address
function getPersonalIPFSHashForProvider(address patientAddress) public view returns(string memory){ return users[patientAddress]; }
7,297,011
[ 1, 588, 2359, 2556, 1651, 4847, 358, 2923, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 29936, 287, 2579, 4931, 2310, 1290, 2249, 12, 2867, 18608, 1887, 13, 1071, 1476, 1135, 12, 1080, 3778, 15329, 203, 3639, 327, 3677, 63, 16330, 1979, 1887, 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 ]
./full_match/4/0x22e8dfE3A7c5d8e14562F906fb33bc9c8Ab18432/sources/contracts/ERC721.sol
Owner Mint AOZ to Specific users
function mintToFans(address to) public nonReentrant onlyOwner { uint supply = totalSupply(); if (supply < MAX_AOZS) { _safeMint(to, totalSupply()); } }
12,291,396
[ 1, 5541, 490, 474, 432, 51, 62, 358, 23043, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 774, 42, 634, 12, 2867, 358, 13, 1071, 1661, 426, 8230, 970, 1338, 5541, 288, 203, 3639, 2254, 14467, 273, 2078, 3088, 1283, 5621, 203, 3639, 309, 261, 2859, 1283, 411, 4552, 67, 20463, 62, 55, 13, 288, 203, 5411, 389, 4626, 49, 474, 12, 869, 16, 2078, 3088, 1283, 10663, 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 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping(address => mapping(address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract MintableToken is PausableToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract TokenImpl is MintableToken { string public name; string public symbol; // how many token units a buyer gets per ether uint256 public rate; uint256 public eth_decimal_num = 100000; // the target token ERC20Basic public targetToken; uint256 public exchangedNum; event Exchanged(address _owner, uint256 _value); function TokenImpl(string _name, string _symbol, uint256 _decimal_num) public { name = _name; symbol = _symbol; eth_decimal_num = _decimal_num; paused = true; } /** * @dev exchange tokens of _exchanger. */ function exchange(address _exchanger, uint256 _value) internal { require(canExchange()); uint256 _tokens = (_value.mul(rate)).div(eth_decimal_num); targetToken.transfer(_exchanger, _tokens); exchangedNum = exchangedNum.add(_value); Exchanged(_exchanger, _tokens); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (_to == address(this) || _to == owner) { exchange(msg.sender, _value); } return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool) { if (_to == address(this) || _to == owner) { exchange(msg.sender, _value); } return super.transfer(_to, _value); } function balanceOfTarget(address _owner) public view returns (uint256 targetBalance) { if (targetToken != address(0)) { return targetToken.balanceOf(_owner); } else { return 0; } } function canExchangeNum() public view returns (uint256) { if (canExchange()) { uint256 _tokens = targetToken.balanceOf(this); return (eth_decimal_num.mul(_tokens)).div(rate); } else { return 0; } } function updateTargetToken(address _target, uint256 _rate) onlyOwner public { rate = _rate; targetToken = ERC20Basic(_target); } function canExchange() public view returns (bool) { return targetToken != address(0) && rate > 0; } } contract Crowdsale is Pausable { using SafeMath for uint256; string public projectName; string public tokenName; string public tokenSymbol; // how many token units a buyer gets per ether uint256 public rate; // amount of raised money in wei, decimals is 5 uint256 public ethRaised; uint256 public eth_decimal_num = 100000; // cap of money in wei uint256 public cap; // The token being sold TokenImpl public token; // the target token ERC20Basic public targetToken; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value); event IncreaseCap(uint256 cap); event DecreaseCap(uint256 cap); function Crowdsale(string _projectName, string _tokenName, string _tokenSymbol, uint256 _cap) public { require(_cap > 0); projectName = _projectName; tokenName = _tokenName; tokenSymbol = _tokenSymbol; cap = _cap.mul(eth_decimal_num); token = createTokenContract(); } function newCrowdSale(string _projectName, string _tokenName, string _tokenSymbol, uint256 _cap) onlyOwner public { require(_cap > 0); projectName = _projectName; tokenName = _tokenName; tokenSymbol = _tokenSymbol; cap = _cap.mul(eth_decimal_num); ethRaised = 0; token.transferOwnership(owner); token = createTokenContract(); rate = 0; targetToken = ERC20Basic(0); } function createTokenContract() internal returns (TokenImpl) { return new TokenImpl(tokenName, tokenSymbol, eth_decimal_num); } // fallback function can be used to buy tokens function() external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) whenNotPaused public payable { require(beneficiary != address(0)); require(msg.value >= (0.00001 ether)); uint256 ethAmount = (msg.value.mul(eth_decimal_num)).div(1 ether); // update state ethRaised = ethRaised.add(ethAmount); require(ethRaised <= cap); token.mint(beneficiary, ethAmount); TokenPurchase(msg.sender, beneficiary, ethAmount); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { owner.transfer(msg.value); } // increase the amount of eth function increaseCap(uint256 _cap_inc) onlyOwner public { require(_cap_inc > 0); cap = cap.add(_cap_inc.mul(eth_decimal_num)); IncreaseCap(cap); } function decreaseCap(uint256 _cap_dec) onlyOwner public { require(_cap_dec > 0); cap = cap.sub(_cap_dec.mul(eth_decimal_num)); if (cap <= ethRaised) { cap = ethRaised; } DecreaseCap(cap); } function saleRatio() public view returns (uint256 ratio) { if (cap == 0) { return 0; } else { return ethRaised.mul(10000).div(cap); } } function balanceOf(address _owner) public view returns (uint256 balance) { return token.balanceOf(_owner); } function balanceOfTarget(address _owner) public view returns (uint256 targetBalance) { return token.balanceOfTarget(_owner); } function canExchangeNum() public view returns (uint256) { return token.canExchangeNum(); } function updateTargetToken(address _target, uint256 _rate) onlyOwner public { rate = _rate; targetToken = ERC20Basic(_target); token.updateTargetToken(_target, _rate); } /** * @dev called by the owner to transfer the target token to owner from this contact */ function releaseTargetToken(uint256 _value) onlyOwner public returns (bool) { if (targetToken != address(0)) { return targetToken.transfer(owner, _value); } else { return false; } } /** * @dev called by the owner to pause, triggers stopped state */ function pauseToken() onlyOwner public { token.pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpauseToken() onlyOwner public { token.unpause(); } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return ethRaised >= cap; } }
low level token purchase function update state
function buyTokens(address beneficiary) whenNotPaused public payable { require(beneficiary != address(0)); require(msg.value >= (0.00001 ether)); uint256 ethAmount = (msg.value.mul(eth_decimal_num)).div(1 ether); ethRaised = ethRaised.add(ethAmount); require(ethRaised <= cap); token.mint(beneficiary, ethAmount); TokenPurchase(msg.sender, beneficiary, ethAmount); forwardFunds(); }
13,132,025
[ 1, 821, 1801, 1147, 23701, 445, 1089, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 5157, 12, 2867, 27641, 74, 14463, 814, 13, 1347, 1248, 28590, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 261, 20, 18, 2787, 21, 225, 2437, 10019, 203, 203, 3639, 2254, 5034, 13750, 6275, 273, 261, 3576, 18, 1132, 18, 16411, 12, 546, 67, 12586, 67, 2107, 13, 2934, 2892, 12, 21, 225, 2437, 1769, 203, 203, 3639, 13750, 12649, 5918, 273, 13750, 12649, 5918, 18, 1289, 12, 546, 6275, 1769, 203, 3639, 2583, 12, 546, 12649, 5918, 1648, 3523, 1769, 203, 203, 3639, 1147, 18, 81, 474, 12, 70, 4009, 74, 14463, 814, 16, 13750, 6275, 1769, 203, 3639, 3155, 23164, 12, 3576, 18, 15330, 16, 27641, 74, 14463, 814, 16, 13750, 6275, 1769, 203, 203, 3639, 5104, 42, 19156, 5621, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-07-16 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.6; /** * @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); } 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); } } } } /* * @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; } } /** * @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); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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); } /** * @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, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } /** * @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"); } } } /** * @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); } /** * @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; } } /** * @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()); } } } interface IController { function getClusterAmountFromEth(uint256 _ethAmount, address _cluster) external view returns (uint256); function addClusterToRegister(address indexAddr) external; function getDHVPrice(address _cluster) external view returns (uint256); function getUnderlyingsInfo(address _cluster, uint256 _ethAmount) external view returns ( uint256[] memory, uint256[] memory, uint256 ); function getUnderlyingsAmountsFromClusterAmount(uint256 _clusterAmount, address _clusterAddress) external view returns (uint256[] memory); function getEthAmountFromUnderlyingsAmounts(uint256[] memory _underlyingsAmounts, address _cluster) external view returns (uint256); function adapters(address _cluster) external view returns (address); function dhvTokenInstance() external view returns (address); function getDepositComission(address _cluster, uint256 _ethValue) external view returns (uint256); function getRedeemComission(address _cluster, uint256 _ethValue) external view returns (uint256); function getClusterPrice(address _cluster) external view returns (uint256); } interface IDexAdapter { function swapETHToUnderlying(address underlying) external payable; function swapUndelyingsToETH(uint256[] memory underlyingAmounts, address[] memory underlyings) external; function swapTokenToToken( uint256 _amountToSwap, address _tokenToSwap, address _tokenToReceive ) external returns (uint256); function getUnderlyingAmount( uint256 _amount, address _tokenToSwap, address _tokenToReceive ) external view returns (uint256); function getPath(address _tokenToSwap, address _tokenToReceive) external view returns (address[] memory); function getTokensPrices(address[] memory _tokens) external view returns (uint256[] memory); function getEthPrice() external view returns (uint256); function getDHVPrice(address _dhvToken) external view returns (uint256); } interface IClusterToken { function assemble(bool coverDhvWithEth) external payable returns (uint256); function disassemble(uint256 indexAmount, bool coverDhvWithEth) external payable; function withdrawToAccumulation( address[] calldata _tokens, uint256[] calldata _amounts, uint256 _clusterAmount ) external; function refundFromAccumulation( address[] calldata _tokens, uint256[] calldata _amounts, uint256 _clusterAmount ) external; function optimizeProportion(uint256[] memory updatedShares) external returns (uint256[] memory debt); function getUnderlyingShares() external view returns (uint256[] calldata); function getUnderlyings() external view returns (address[] calldata); function getUnderlyingBalance(address _underlying) external view returns (uint256); function getUnderlyingsAmountsFromClusterAmount(uint256 _clusterAmount) external view returns (uint256[] calldata); function clusterTokenLock() external view returns (uint256); function clusterLock(address _token) external view returns (uint256); function controllerChange(address) external; } interface IERC20Extend { /** * @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 Returns the amound of token's decimals. */ function decimals() external view returns (uint8); /** * @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); } /// @title Cluster Token Contract /// @author Anna Korunska, Pavlo Horbonos, Philipp Taratuta, Svyatoslav Delukin /// @notice Cluster Token is a ERC-20 token representing a DeHive cluster of DeFi assets contract ClusterToken is ERC20Pausable, AccessControl, IClusterToken { using SafeERC20 for IERC20; bytes32 public constant FARMER_ROLE = keccak256("FARMER_ROLE"); bytes32 public constant DELEGATE_ROLE = keccak256("DELEGATE_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /// @notice Address of Controller smart contract. address public clusterControllerAddress; /// @notice Address of treasury. address internal treasuryAddress; /// @notice Instance of the DHV token instance IERC20 public dhvTokenInstance; /// @notice Hash id, serves as an additional identifier of the cluster. uint256 public clusterHashId; /// @notice lock period, during which user can't redeem or transfer cluster after assemble uint256 public cooldownPeriod; /// @notice List of tokens that cluster holds, called underlyings. /// @dev Order of addresses is important, as it corresponds with the order in underlyingsShares. address[] public underlyings; /// @notice List of shares, multiplied by 10 ** 6 /// @dev Order of addresses is important, as it corresponds with the order of tokens in underlyings. uint256[] public underlyingsShares; /// @notice Amount of cluster token locked uint256 public override clusterTokenLock; /// @notice timestamp, before which user can't redeem or transfer cluster. /// @dev userAddress => uint. mapping(address => uint256) public cooldownTimestamps; mapping(address => uint256) public override clusterLock; /// @notice Event emitted on each successful deposit for cluster in ETH. /// @param clusterAddress Address of cluster deposited upon. /// @param buyer Address of user depositing (user who bought token). /// @param ethDeposited Amount of ETH deposited in exchange of cluster. /// @param clusterAmountBought Amount of cluster bought for given amount of ETH. event ClusterAssembledInETH(address clusterAddress, address buyer, uint256 ethDeposited, uint256 clusterAmountBought); /// @notice Event emitted on each successful cluster redeeming for ETH. /// @param clusterAddress Address of cluster redeemed. /// @param redeemer Address of user performing the redeem. /// @param clusterAmountRedeemed Amount of cluster redeemed by user. event ClusterDisassembledInETH(address clusterAddress, address redeemer, uint256 clusterAmountRedeemed); /// @notice Event emitted on each successful deposit for cluster in ETH. /// @param clusterAddress Address of cluster deposited upon. /// @param buyer Address of user depositing (user who bought token). /// @param clusterAmountBought Amount of cluster bought for given amount of ETH. event ClusterAssembled(address clusterAddress, address buyer, uint256 clusterAmountBought); /// @notice Event emitted on each successful cluster redeeming for ETH. /// @param clusterAddress Address of cluster redeemed. /// @param redeemer Address of user performing the redeem. /// @param clusterAmountRedeemed Amount of cluster redeemed by user. event ClusterDisassembled(address clusterAddress, address redeemer, uint256 clusterAmountRedeemed); /// @notice Checks that lock period on redeeming or transfering cluster is over. modifier checkCooldownPeriod() { require(cooldownTimestamps[_msgSender()] <= block.timestamp, "Cooldown in progress"); _; } /// @notice Checks admin role. modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Unauthorized"); _; } /// @notice Checks farmer role. modifier onlyFarmer() { require(hasRole(FARMER_ROLE, _msgSender()), "Unauthorized"); _; } /// @notice Checks delegate role. modifier onlyDelegate() { require(hasRole(DELEGATE_ROLE, _msgSender()), "Unauthorized"); _; } /// @notice Checks minter role. modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "Unauthorized"); _; } /// @notice Performs initial setup. /// @param _clusterControllerAddress Address of the Controller SC. /// @param _underlyings List of tokens to be recorded in underlyings. /// @param _underlyingsShares List of shares to be recorded in underlyingsShares. /// @param _name Name of the ERC-20 token. /// @param _symbol Symbol of the ERC-20 token. /// @param _hashId cluster hash identifier. constructor( address _clusterControllerAddress, address _treasury, address[] memory _underlyings, uint256[] memory _underlyingsShares, string memory _name, string memory _symbol, uint256 _hashId ) ERC20(_name, _symbol) { require(_clusterControllerAddress != address(0), "dev: Controller zero address"); require(_treasury != address(0), "dev: Treasury zero address"); require(_underlyings.length == _underlyingsShares.length, "dev: Arrays' lengths must be equal"); for (uint256 i = 0; i < _underlyings.length; i++) { require(_underlyings[i] != address(0), "dev: Underlying zero address"); require(_underlyingsShares[i] > 0, "dev: Share equals zero"); } _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(FARMER_ROLE, _msgSender()); _setupRole(DELEGATE_ROLE, _msgSender()); underlyings = _underlyings; underlyingsShares = _underlyingsShares; clusterHashId = _hashId; clusterControllerAddress = _clusterControllerAddress; treasuryAddress = _treasury; dhvTokenInstance = IERC20(IController(_clusterControllerAddress).dhvTokenInstance()); } receive() external payable {} /********** * ADMIN INTERFACE **********/ /// @notice Function that allows contract owner to update cooldown period on cluster redeeming and transfering. /// @param _cooldownPeriod New lock period. function setCooldownPeriod(uint256 _cooldownPeriod) external onlyAdmin { cooldownPeriod = _cooldownPeriod; } /// @notice Function pauses assemble, dissamble, transfers. function pause() external onlyAdmin { _pause(); } /// @notice Function unpauses assemble, dissamble, transfers. function unpause() external onlyAdmin { _unpause(); } /// @notice Controller ownership transfer. function controllerChange(address _controller) external override { require(_msgSender() == clusterControllerAddress, "COntroller only"); clusterControllerAddress = _controller; } /********** * USER'S INTERFACE **********/ /// @notice Function that allows depositing ETH and purchase respective amount of cluster. /// @dev Can only be called when token is not paused. /// @param coverDhvWithEth Should DHV to cover commission be purchased during the call, /// rather then transferred from the caller's address. /// @return Amount of cluster purchased. function assemble(bool coverDhvWithEth) external payable override whenNotPaused returns (uint256) { require(msg.value > 0, "No ether sent"); uint256 _ethCommission = IController(clusterControllerAddress).getDepositComission(address(this), msg.value); uint256 ethAmount = msg.value - _coverCommission(_ethCommission, coverDhvWithEth); uint256 balanceBefore = address(this).balance; uint256 denominator = _swapEthToUnderlyings(ethAmount); uint256 balanceAfter = address(this).balance; if (balanceBefore - balanceAfter < ethAmount) { uint256 dust = ethAmount - (balanceBefore - balanceAfter); _payInEth(dust); ethAmount -= (dust); } uint256 clusterAmount = (ethAmount * 10**18) / denominator; cooldownTimestamps[_msgSender()] = block.timestamp + cooldownPeriod; _mint(_msgSender(), clusterAmount); emit ClusterAssembledInETH(address(this), _msgSender(), ethAmount, clusterAmount); return clusterAmount; } /// @notice Function that allows disassembling cluster and receiving respective amount of ETH. /// @dev Can only be called when token is not paused. /// @param _clusterAmount Amount of cluster to be redeemed, e.g. exchanged to ETH equivalent. /// @param coverDhvWithEth Should DHV to cover commission be purchased during the call, /// rather then transferred from the caller's address. function disassemble(uint256 _clusterAmount, bool coverDhvWithEth) external payable override whenNotPaused checkCooldownPeriod { require(_clusterAmount > 0 && _clusterAmount <= balanceOf(_msgSender()), "Not enough cluster"); IERC20(address(this)).safeTransferFrom(_msgSender(), address(this), _clusterAmount); uint256[] memory underlyingAmounts = getUnderlyingsAmountsFromClusterAmount(_clusterAmount); uint256 balanceBefore = address(this).balance; _swapUnderlyingsToEth(underlyingAmounts); uint256 balanceAfter = address(this).balance; uint256 ethEstimated = balanceAfter - balanceBefore; uint256 _ethCommission = IController(clusterControllerAddress).getRedeemComission(address(this), ethEstimated); uint256 ethAmount = ethEstimated - _coverCommission(_ethCommission, coverDhvWithEth); _payInEth(ethAmount); _burn(address(this), _clusterAmount); emit ClusterDisassembledInETH(address(this), _msgSender(), _clusterAmount); } /// @dev Standard ERC20 transfer function, overriden in order to check lock period. function transfer(address recipient, uint256 amount) public override checkCooldownPeriod returns (bool) { return super.transfer(recipient, amount); } /// @dev Standard ERC20 transferFrom function, overriden in order to check lock period. function transferFrom( address sender, address recipient, uint256 amount ) public override checkCooldownPeriod returns (bool) { return super.transferFrom(sender, recipient, amount); } /********** * FARMER AND DELEGATE INTERFACE **********/ /// @notice Mints tokens for the contract with minter role. /// @notice requires approved amounts of underlyings /// @param _clusterAmount Cluster token amount to be minted. function mint(uint256 _clusterAmount) external onlyMinter { uint256[] memory underlyingAmounts = getUnderlyingsAmountsFromClusterAmount(_clusterAmount); for (uint256 i = 0; i < underlyingAmounts.length; i++) { IERC20(underlyings[i]).safeTransferFrom(_msgSender(), address(this), underlyingAmounts[i]); } _mint(_msgSender(), _clusterAmount); emit ClusterAssembled(address(this), _msgSender(), _clusterAmount); } /// @notice Mints tokens for the account. Sets cooldown /// @notice requires approved amounts of underlyings /// @param _account Account to be minted for. /// @param _clusterAmount Cluster token amount to be minted. function mintFor(address _account, uint256 _clusterAmount) external onlyMinter { uint256[] memory underlyingAmounts = getUnderlyingsAmountsFromClusterAmount(_clusterAmount); for (uint256 i = 0; i < underlyingAmounts.length; i++) { IERC20(underlyings[i]).safeTransferFrom(_msgSender(), address(this), underlyingAmounts[i]); } cooldownTimestamps[_account] = block.timestamp + cooldownPeriod; _mint(_account, _clusterAmount); emit ClusterAssembled(address(this), _account, _clusterAmount); } /// @notice Burns cluster tokens after the trade. /// @notice requires underlyings to be present /// @param _clusterAmount Cluster token amount to be minted. function burn(uint256 _clusterAmount) external onlyMinter { uint256[] memory underlyingAmounts = getUnderlyingsAmountsFromClusterAmount(_clusterAmount); for (uint256 i = 0; i < underlyingAmounts.length; i++) { IERC20(underlyings[i]).safeTransfer(_msgSender(), underlyingAmounts[i]); } _burn(address(this), _clusterAmount); emit ClusterDisassembled(address(this), _msgSender(), _clusterAmount); } /// @notice Withdraw tokens of cluster for staking. /// @param _tokens List of tokens to be transferred. /// @param _amounts Amounts of tokens to be transferred. function withdrawToAccumulation( address[] memory _tokens, uint256[] memory _amounts, uint256 _clusterAmount ) external override onlyFarmer { require(_tokens.length == _amounts.length, "Wrong array"); for (uint256 i = 0; i < _tokens.length; i++) { IERC20(_tokens[i]).safeTransfer(_msgSender(), _amounts[i]); clusterLock[_tokens[i]] += _amounts[i]; } clusterTokenLock += _clusterAmount; } /// @notice Refund tokens of cluster from staking. /// @param _tokens List of tokens to be transferred. /// @param _amounts Amounts of tokens to be transferred. function refundFromAccumulation( address[] memory _tokens, uint256[] memory _amounts, uint256 _clusterAmount ) external override onlyFarmer { require(_tokens.length == _amounts.length, "Wrong array"); for (uint256 i = 0; i < _tokens.length; i++) { IERC20(_tokens[i]).safeTransferFrom(_msgSender(), address(this), _amounts[i]); clusterLock[_tokens[i]] -= _amounts[i]; } clusterTokenLock -= _clusterAmount; } /// @notice Interface for optimizer for the correction of the underlyings proportion. /// @param updatedShares New weights. function optimizeProportion(uint256[] memory updatedShares) external override onlyDelegate returns (uint256[] memory debt) { require(updatedShares.length == underlyingsShares.length, "Wrong array"); debt = new uint256[](underlyings.length); uint256 clusterTokenLockMemo = clusterTokenLock; uint256[] memory curSharesAmounts = getUnderlyingsAmountsFromClusterAmount(totalSupply() - clusterTokenLockMemo); underlyingsShares = updatedShares; uint256[] memory newSharesAmounts = getUnderlyingsAmountsFromClusterAmount(totalSupply() - clusterTokenLockMemo); uint256[] memory newLock = getUnderlyingsAmountsFromClusterAmount(clusterTokenLockMemo); for (uint256 i = 0; i < underlyings.length; i++) { address tkn = underlyings[i]; if (curSharesAmounts[i] > newSharesAmounts[i]) { IERC20(tkn).safeTransfer(_msgSender(), curSharesAmounts[i] - newSharesAmounts[i]); } else if (curSharesAmounts[i] < newSharesAmounts[i]) { IERC20(tkn).safeTransferFrom(_msgSender(), address(this), newSharesAmounts[i] - curSharesAmounts[i]); } if (newLock[i] > clusterLock[tkn]) { debt[i] = newLock[i] - clusterLock[tkn]; } else { debt[i] = 0; } clusterLock[tkn] = newLock[i]; } } /********** * VIEW INTERFACE **********/ /// @notice Get list of underlyings for cluster. /// @return underlyings array. function getUnderlyings() public view override returns (address[] memory) { return underlyings; } /// @notice Get list of underlyings shares for cluster. /// @return underlyingsShares array. function getUnderlyingShares() public view override returns (uint256[] memory) { return underlyingsShares; } /// @notice Calculates amounts of underlyings over the amount of cluster. /// @param _clusterAmount Amount of cluster to calculate underlyings from. /// @return Array, which contains amounts of underlyings. function getUnderlyingsAmountsFromClusterAmount(uint256 _clusterAmount) public view override returns (uint256[] memory) { uint256 totalCluster = IERC20(address(this)).totalSupply(); uint256 clusterShare = (_clusterAmount * 10**18) / totalCluster; uint256[] memory underlyingsAmount = new uint256[](underlyings.length); for (uint256 i = 0; i < underlyings.length; i++) { uint256 underlyingAmount = getUnderlyingBalance(underlyings[i]); underlyingsAmount[i] = (underlyingAmount * clusterShare) / 10**18; } return underlyingsAmount; } /// @notice Calculates amount of underlying including locked assets. /// @param _underlying Underlying address. /// @return Array, which contains amounts of underlyings. function getUnderlyingBalance(address _underlying) public view override returns (uint256) { return IERC20(_underlying).balanceOf(address(this)) + clusterLock[_underlying]; } /********** * INTERNAL HELPERS AND PRICE CALCULATIONS **********/ /// @notice Sends ether to sender for redeeming cluster in ETH. /// @dev Reverts if transaction failed. /// @param ethAmount Amount of ether to be sent. function _payInEth(uint256 ethAmount) private { (bool success, ) = _msgSender().call{value: ethAmount}(""); require(success, "ETH transfer failed"); } /// @notice Covers commission, necessary for cluster deposit or redeem. /// @param _ethCommission Commission in ETH to be covered. /// @param coverDhvWithEth Should DHV to cover commission be purchased during the call, /// rather then transferred from the caller's address. /// @return Amount of Ether, spent on commission. function _coverCommission(uint256 _ethCommission, bool coverDhvWithEth) internal returns (uint256) { if (_ethCommission != 0) { if (coverDhvWithEth) { (bool success, ) = treasuryAddress.call{value: _ethCommission}(""); require(success, "Eth transfer failed"); return _ethCommission; } else { uint256 _dhvCommission = (_ethCommission * 10**18) / IController(clusterControllerAddress).getDHVPrice(address(this)); dhvTokenInstance.safeTransferFrom(_msgSender(), treasuryAddress, _dhvCommission); return 0; } } return 0; } /// @notice Allows to swap collected funds into underlyings through the appropriate adapter. /// @param _ethAmount Eth amount to be splitted among underlyings. function _swapEthToUnderlyings(uint256 _ethAmount) internal returns (uint256) { address adapter = IController(clusterControllerAddress).adapters(address(this)); (uint256[] memory underlyingsAmount, uint256[] memory ethPortion, uint256 clusterPrice) = IController(clusterControllerAddress) .getUnderlyingsInfo(address(this), _ethAmount); for (uint256 i = 0; i < underlyings.length; i++) { if (IERC20(underlyings[i]).balanceOf(treasuryAddress) >= underlyingsAmount[i]) { IERC20(underlyings[i]).safeTransferFrom(treasuryAddress, address(this), underlyingsAmount[i]); (bool sent, ) = treasuryAddress.call{value: ethPortion[i]}(""); require(sent, "ETH transfer failed"); } else { IDexAdapter(adapter).swapETHToUnderlying{value: ethPortion[i]}(underlyings[i]); } } return clusterPrice; } /// @notice Swaps underlyings tokens into ETH. /// @param _underlyingsAmounts Array of underlying tokens amounts. function _swapUnderlyingsToEth(uint256[] memory _underlyingsAmounts) internal { address adapter = IController(clusterControllerAddress).adapters(address(this)); for (uint256 i = 0; i < _underlyingsAmounts.length; i++) { IERC20(underlyings[i]).safeApprove(adapter, 0); IERC20(underlyings[i]).safeApprove(adapter, _underlyingsAmounts[i]); } IDexAdapter(adapter).swapUndelyingsToETH(_underlyingsAmounts, underlyings); } }
@dev Standard ERC20 transferFrom function, overriden in order to check lock period.
function transferFrom( address sender, address recipient, uint256 amount ) public override checkCooldownPeriod returns (bool) { return super.transferFrom(sender, recipient, amount); }
7,865,740
[ 1, 8336, 4232, 39, 3462, 7412, 1265, 445, 16, 31736, 316, 1353, 358, 866, 2176, 3879, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 1071, 3849, 866, 39, 1371, 2378, 5027, 1135, 261, 6430, 13, 288, 203, 3639, 327, 2240, 18, 13866, 1265, 12, 15330, 16, 8027, 16, 3844, 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 ]
pragma solidity >=0.4.21 <0.6.0; import "../node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; contract StarNotary is ERC721 { struct Star { string name; } // Add a name and a symbol for your starNotary tokens string public name = "Abdulaziz Token"; string public symbol = "AZIZ"; // mapping(uint256 => Star) public tokenIdToStarInfo; mapping(uint256 => uint256) public starsForSale; //mapping between address and owned starts mapping(address => uint256[]) ownedTokens; // Mapping from token ID to index of the owner token list mapping(uint256 => uint256) private ownedTokensIndex; function createStar(string memory _name, uint256 _tokenId) public { Star memory newStar = Star(_name); tokenIdToStarInfo[_tokenId] = newStar; _mint(msg.sender, _tokenId); } // Add a function lookUptokenIdToStarInfo, that looks up the stars using the Token ID, and then returns the name of the star. function lookUptokenIdToStarInfo(uint256 _tokenId) public view returns (string memory starName){ Star memory lookupStar = tokenIdToStarInfo[_tokenId]; starName = lookupStar.name; return starName; } // function putStarUpForSale(uint256 _tokenId, uint256 _price) public { require(ownerOf(_tokenId) == msg.sender); starsForSale[_tokenId] = _price; } function buyStar(uint256 _tokenId) public payable { require(starsForSale[_tokenId] > 0); uint256 starCost = starsForSale[_tokenId]; address starOwner1 = ownerOf(_tokenId); uint160 starOwner2 = uint160(starOwner1); address payable starOwner = address(starOwner2); require(msg.value >= starCost); // _removeTokenFrom(starOwner, _tokenId); // _addTokenTo(msg.sender, _tokenId); _transferFrom(starOwner, msg.sender, _tokenId); starOwner.transfer(starCost); if(msg.value > starCost) { msg.sender.transfer(msg.value - starCost); } starsForSale[_tokenId] = 0; } // Add a function called exchangeStars, so 2 users can exchange their star tokens... //Do not worry about the price, just write code to exchange stars between users. function exchangeStars(uint256 _tokenId1, uint256 _tokenId2) public{ require(msg.sender == ownerOf(_tokenId1)); address owner2 = ownerOf(_tokenId2); //require(owner2 != address(0)); // putStarUpForSale(_tokenId1,0); _transferFrom(msg.sender, owner2, _tokenId1); _transferFrom(owner2, msg.sender, _tokenId2); } // Write a function to Transfer a Star. The function should transfer a star from the address of the caller. // The function should accept 2 arguments, the address to transfer the star to, and the token ID of the star. // function transferStar(address _to, uint256 _tokenId) public { require(msg.sender == ownerOf(_tokenId)); transferFrom(msg.sender, _to, _tokenId); } }
Mapping from token ID to index of the owner token list
mapping(uint256 => uint256) private ownedTokensIndex;
6,369,812
[ 1, 3233, 628, 1147, 1599, 358, 770, 434, 326, 3410, 1147, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 16199, 5157, 1016, 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 ]
pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "../DInterest.sol"; import "./FractionalDeposit.sol"; import "./FractionalDepositFactory.sol"; // OpenZeppelin contract modified to support cloned contracts contract ClonedReentrancyGuard { bool internal _notEntered; /** * @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(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } contract ZeroCouponBond is ERC20, ClonedReentrancyGuard, IERC721Receiver { using SafeERC20 for ERC20; bool public initialized; DInterest public pool; FractionalDepositFactory public fractionalDepositFactory; ERC20 public stablecoin; uint256 public maturationTimestamp; string public name; string public symbol; uint8 public decimals; event Mint( address indexed sender, address indexed fractionalDepositAddress, uint256 amount ); event RedeemFractionalDepositShares( address indexed sender, address indexed fractionalDepositAddress, uint256 fundingID ); event RedeemStablecoin(address indexed sender, uint256 amount); function init( address _pool, address _fractionalDepositFactory, uint256 _maturationTimestamp, string calldata _tokenName, string calldata _tokenSymbol ) external { require(!initialized, "ZeroCouponBond: initialized"); initialized = true; _notEntered = true; pool = DInterest(_pool); fractionalDepositFactory = FractionalDepositFactory( _fractionalDepositFactory ); stablecoin = pool.stablecoin(); maturationTimestamp = _maturationTimestamp; name = _tokenName; symbol = _tokenSymbol; // set decimals to be the same as the underlying stablecoin decimals = ERC20Detailed(address(pool.stablecoin())).decimals(); // infinite approval to fractional deposit factory to save gas during minting with NFT pool.depositNFT().setApprovalForAll(_fractionalDepositFactory, true); fractionalDepositFactory.mph().approve( _fractionalDepositFactory, uint256(-1) ); } function mintWithDepositNFT( uint256 nftID, string calldata fractionalDepositName, string calldata fractionalDepositSymbol ) external nonReentrant returns ( uint256 zeroCouponBondsAmount, FractionalDeposit fractionalDeposit ) { // ensure the deposit's maturation time is on or before that of the ZCB DInterest.Deposit memory depositStruct = pool.getDeposit(nftID); uint256 depositMaturationTimestamp = depositStruct.maturationTimestamp; require( depositMaturationTimestamp <= maturationTimestamp, "ZeroCouponBonds: maturation too late" ); // transfer MPH from `msg.sender` MPHToken mph = fractionalDepositFactory.mph(); mph.transferFrom( msg.sender, address(this), depositStruct.mintMPHAmount ); // transfer deposit NFT from `msg.sender` NFT depositNFT = pool.depositNFT(); depositNFT.safeTransferFrom(msg.sender, address(this), nftID); // call fractionalDepositFactory to create fractional deposit using NFT fractionalDeposit = fractionalDepositFactory.createFractionalDeposit( address(pool), nftID, fractionalDepositName, fractionalDepositSymbol ); fractionalDeposit.transferOwnership(msg.sender); // mint zero coupon bonds to `msg.sender` zeroCouponBondsAmount = fractionalDeposit.totalSupply(); _mint(msg.sender, zeroCouponBondsAmount); emit Mint( msg.sender, address(fractionalDeposit), zeroCouponBondsAmount ); } function redeemFractionalDepositShares( address fractionalDepositAddress, uint256 fundingID ) external nonReentrant { FractionalDeposit fractionalDeposit = FractionalDeposit(fractionalDepositAddress); uint256 balance = fractionalDeposit.balanceOf(address(this)); fractionalDeposit.redeemShares(balance, fundingID); emit RedeemFractionalDepositShares( msg.sender, fractionalDepositAddress, fundingID ); } function redeemStablecoin(uint256 amount) external nonReentrant returns (uint256 actualRedeemedAmount) { require(now >= maturationTimestamp, "ZeroCouponBond: not mature"); uint256 stablecoinBalance = stablecoin.balanceOf(address(this)); actualRedeemedAmount = amount > stablecoinBalance ? stablecoinBalance : amount; // burn `actualRedeemedAmount` zero coupon bonds from `msg.sender` _burn(msg.sender, actualRedeemedAmount); // transfer `actualRedeemedAmount` stablecoins to `msg.sender` stablecoin.safeTransfer(msg.sender, actualRedeemedAmount); emit RedeemStablecoin(msg.sender, actualRedeemedAmount); } /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data ) public returns (bytes4) { return this.onERC721Received.selector; } }
burn `actualRedeemedAmount` zero coupon bonds from `msg.sender` transfer `actualRedeemedAmount` stablecoins to `msg.sender`
function redeemStablecoin(uint256 amount) external nonReentrant returns (uint256 actualRedeemedAmount) { require(now >= maturationTimestamp, "ZeroCouponBond: not mature"); uint256 stablecoinBalance = stablecoin.balanceOf(address(this)); actualRedeemedAmount = amount > stablecoinBalance ? stablecoinBalance : amount; _burn(msg.sender, actualRedeemedAmount); stablecoin.safeTransfer(msg.sender, actualRedeemedAmount); emit RedeemStablecoin(msg.sender, actualRedeemedAmount); }
919,442
[ 1, 70, 321, 1375, 18672, 426, 24903, 329, 6275, 68, 3634, 16174, 15692, 628, 1375, 3576, 18, 15330, 68, 7412, 1375, 18672, 426, 24903, 329, 6275, 68, 14114, 71, 9896, 358, 1375, 3576, 18, 15330, 68, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 24903, 30915, 12645, 12, 11890, 5034, 3844, 13, 203, 3639, 3903, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1135, 261, 11890, 5034, 3214, 426, 24903, 329, 6275, 13, 203, 565, 288, 203, 3639, 2583, 12, 3338, 1545, 4834, 872, 4921, 16, 315, 7170, 22744, 9807, 30, 486, 312, 1231, 8863, 203, 203, 3639, 2254, 5034, 14114, 12645, 13937, 273, 14114, 12645, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 3214, 426, 24903, 329, 6275, 273, 3844, 405, 14114, 12645, 13937, 203, 5411, 692, 14114, 12645, 13937, 203, 5411, 294, 3844, 31, 203, 203, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 3214, 426, 24903, 329, 6275, 1769, 203, 203, 3639, 14114, 12645, 18, 4626, 5912, 12, 3576, 18, 15330, 16, 3214, 426, 24903, 329, 6275, 1769, 203, 203, 3639, 3626, 868, 24903, 30915, 12645, 12, 3576, 18, 15330, 16, 3214, 426, 24903, 329, 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 ]
pragma solidity ^0.4.23; contract DEX_token { // constructor //set the total number of tokens //Read the total number of tokens string public name = "Osun Token"; string public symbol = "OSUN"; string public standard = "Osun Token v1.0"; uint256 public totalSupply; event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; // it is convenvtion in solidity to use a n _ infront of vairables local to functions. global variables like totalSupply do not start with _. constructor(uint256 _initialSupply) public { balanceOf[msg.sender] = _initialSupply; totalSupply = _initialSupply; // allocate the intial supply } //Transfer function - allows token to be transfered between users //exception if account doesnt have enough //transfer event function transfer(address _to, uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value, "Insufficient funds, revert"); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; //emit Transfer event emit Transfer(msg.sender, _to, _value); return true; } //Transferfrom //fire transfer event //require authorization from _from address function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= balanceOf[_from], "insufficient balance"); require(_value <= allowance[_from][msg.sender], "insufficient allowance"); //change the balance balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } /* if (balanceOf[msg.sender] >= _value && allowed[_from][msg.sender]){ balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; //emit transfter event emit Transfer(msg.sender, _to, _value); return true; } else {return "Cannot complete withdraw due to insufficient funds";} } */ function approve(address _spender, uint256 _value) public returns (bool succes) { //allowance allowance[msg.sender][_spender] = _value; //Approval event emit Approval(msg.sender, _spender, _value); return true; } // function allowance(address _owner, address _spender) public view returns (uint256 remaining) { // } }
allocate the intial supply
constructor(uint256 _initialSupply) public { balanceOf[msg.sender] = _initialSupply; totalSupply = _initialSupply; }
12,924,475
[ 1, 16247, 326, 509, 649, 14467, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 11890, 5034, 389, 6769, 3088, 1283, 13, 1071, 288, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 389, 6769, 3088, 1283, 31, 203, 3639, 2078, 3088, 1283, 273, 389, 6769, 3088, 1283, 31, 203, 565, 289, 27699, 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 ]
pragma solidity ^0.4.23; contract Ownable { //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- address public owner; //-------------------------------------------------------------------------- // // Events // //-------------------------------------------------------------------------- event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred ( address indexed previousOwner, address indexed newOwner ); //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- constructor() public { owner = msg.sender; } //-------------------------------------------------------------------------- // // Modifiers // //-------------------------------------------------------------------------- modifier onlyOwner() { require(msg.sender == owner); _; } //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if(a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ERC20Basic { //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); //-------------------------------------------------------------------------- // // Events // //-------------------------------------------------------------------------- event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- 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); //-------------------------------------------------------------------------- // // Events // //-------------------------------------------------------------------------- event Approval ( address indexed owner, address indexed spender, uint256 value ); } contract TokenDestructible is Ownable { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- constructor() public payable { } //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- function destroy(address[] tokens) onlyOwner public { for (uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } selfdestruct(owner); } } contract BasicToken is ERC20Basic { using SafeMath for uint256; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- mapping(address => uint256) balances; uint256 totalSupply_; //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- mapping (address => mapping (address => uint256)) internal allowed; //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- function transferFrom(address _from,address _to,uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender,uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner,address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender,uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender,uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if(_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract BurnableToken is BasicToken { //-------------------------------------------------------------------------- // // Events // //-------------------------------------------------------------------------- event Burn(address indexed burner, uint256 value); //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract StandardBurnableToken is BurnableToken, StandardToken { //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } } contract TrinoToken is StandardBurnableToken,TokenDestructible { //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- string public name = "TRINO"; string public symbol = "TIO"; uint public decimals = 18; uint256 public INITIAL_SUPPLY = 3750000000 * (10 ** decimals); // 3 750 000 000 //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- constructor() public { owner = msg.sender; totalSupply_ = INITIAL_SUPPLY; balances[owner] = INITIAL_SUPPLY; } }
-------------------------------------------------------------------------- Public Methods---------------------------------------------------------------------------------------------------------------------------------------------------- Events--------------------------------------------------------------------------
{ 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); }
12,545,526
[ 1, 5802, 15392, 202, 4782, 13063, 5802, 28253, 553, 202, 3783, 5802, 15392, 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 ]
[ 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 ]
[ 1, 95, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 11013, 951, 12, 2867, 10354, 13, 1071, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 1769, 203, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 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 ]
./full_match/4/0x05F5230b57E7D1d96B7ECC3975e447955a690b85/sources/BondingCurveFactory_flat.sol
* @return bool: If the transition condition has been met. I.e Are there enough tokens to transition the token into a uniswap market. @return bool: If the token has transitioned. This can only be set by the market transition contract./
function getTokenStatus() external view returns(bool, bool) { return ( transitionConditionsMet, transitionCompleated ); }
651,431
[ 1, 2463, 1426, 30, 971, 326, 6007, 2269, 711, 2118, 5100, 18, 467, 18, 73, 12520, 1915, 540, 7304, 2430, 358, 6007, 326, 1147, 1368, 279, 640, 291, 91, 438, 13667, 18, 327, 1426, 30, 971, 326, 1147, 711, 6007, 329, 18, 1220, 848, 1338, 506, 444, 635, 326, 540, 13667, 6007, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9162, 1482, 1435, 3903, 1476, 1135, 12, 6430, 16, 1426, 13, 288, 203, 3639, 327, 261, 203, 5411, 6007, 8545, 12244, 16, 203, 5411, 6007, 799, 1802, 690, 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 ]
pragma solidity ^0.4.8; import "./SafeMath.sol"; import "./PeaceRelay.sol"; import "./RLP.sol"; contract ETCLocking is SafeMath { using RLP for RLP.RLPItem; using RLP for RLP.Iterator; using RLP for bytes; // Public variables of the token string public version = 'v0.1'; uint public totalSupply; bytes4 public BURN_FUNCTION_SIG = 0xfcd3533c; mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; PeaceRelay public ETHRelay; address etcTokenAddr; //maybe rename to EthLockingContract struct Transaction { uint gasPrice; uint gasLimit; address to; uint value; bytes data; } struct Log { address sender; address etcAddr; uint value; } event Locked(address indexed from, address indexed ethAddr, uint value); event Unlocked(address indexed to, uint value); function ETCLocking(address peaceRelayAddr, address _etcTokenAddr) { totalSupply = 0; ETHRelay = PeaceRelay(peaceRelayAddr); etcTokenAddr = _etcTokenAddr; } function unlock(bytes32 blockHash, bytes rlpTxStack, uint[] txIndex, bytes txPrefix, bytes rlpTransaction, bytes rlpRecStack, uint[] recIndex, bytes recPrefix, bytes rlpReceipt) returns (bool success) { if (ETHRelay.checkReceiptProof(blockHash, rlpRecStack, recIndex, recPrefix, rlpReceipt)) { Log memory log = getReceiptDetails(rlpReceipt); if (ETHRelay.checkTxProof(blockHash, rlpTxStack, txIndex, txPrefix, rlpTransaction)) { Transaction memory tx = getTransactionDetails(rlpTransaction); assert (getSig(tx.data) == BURN_FUNCTION_SIG); assert (tx.to == etcTokenAddr); totalSupply = safeSub(totalSupply, log.value); log.etcAddr.transfer(log.value); assert(totalSupply == this.balance); Unlocked(log.etcAddr, log.value); return true; } return false; } } function lock(address ethAddr) payable returns (bool success) { // Note: This will never throw, as there is a max amount of tokens on a chain totalSupply = safeAdd(totalSupply, msg.value); Locked(msg.sender, ethAddr, msg.value); return true; } // HELPER FUNCTIONS function getSig(bytes b) constant returns (bytes4 functionSig) { if (b.length < 32) throw; uint tmp = 0; for (uint i=0; i < 4; i++) tmp = tmp*(2**8)+uint8(b[i]); return bytes4(tmp); } //rlpTransaction is a value at the bottom of the transaction trie. function getReceiptDetails(bytes rlpReceipt) constant internal returns (Log memory l) { RLP.RLPItem[] memory receipt = rlpReceipt.toRLPItem().toList(); RLP.RLPItem[] memory logs = receipt[3].toList(); RLP.RLPItem[] memory log = logs[0].toList(); RLP.RLPItem[] memory logValue = log[1].toList(); l.sender = address(logValue[1].toUint()); l.etcAddr = address(logValue[2].toUint()); l.value = logValue[3].toUint(); } //rlpTransaction is a value at the bottom of the transaction trie. function testGetReceiptDetails(bytes rlpReceipt) constant returns (address, address, uint) { RLP.RLPItem[] memory receipt = rlpReceipt.toRLPItem().toList(); RLP.RLPItem[] memory logs = receipt[3].toList(); RLP.RLPItem[] memory log = logs[0].toList(); RLP.RLPItem[] memory logValue = log[1].toList(); return (address(logValue[1].toUint()), address(logValue[2].toUint()), logValue[3].toUint()); } //rlpTransaction is a value at the bottom of the transaction trie. function getTransactionDetails(bytes rlpTransaction) constant internal returns (Transaction memory tx) { RLP.RLPItem[] memory list = rlpTransaction.toRLPItem().toList(); tx.gasPrice = list[1].toUint(); tx.gasLimit = list[2].toUint(); tx.to = address(list[3].toUint()); //Ugly hard coding for now. Can only parse burn transactions. tx.data = new bytes(68); for (uint i = 0; i < 68; i++) { tx.data[i] = rlpTransaction[rlpTransaction.length - 135 + i]; } return tx; } //rlpTransaction is a value at the bottom of the transaction trie. function testGetTransactionDetails(bytes rlpTransaction) constant returns (uint, uint, address, bytes) { Transaction memory tx; RLP.RLPItem[] memory list = rlpTransaction.toRLPItem().toList(); tx.gasPrice = list[1].toUint(); tx.gasLimit = list[2].toUint(); tx.to = address(list[3].toUint()); //Ugly hard coding for now. Can only parse burn transactions. tx.data = new bytes(68); for (uint i = 0; i < 68; i++) { tx.data[i] = rlpTransaction[rlpTransaction.length - 135 + i]; } return (tx.gasPrice, tx.gasLimit, tx.to, tx.data); } }
rlpTransaction is a value at the bottom of the transaction trie.Ugly hard coding for now. Can only parse burn transactions.
function getTransactionDetails(bytes rlpTransaction) constant internal returns (Transaction memory tx) { RLP.RLPItem[] memory list = rlpTransaction.toRLPItem().toList(); tx.gasPrice = list[1].toUint(); tx.gasLimit = list[2].toUint(); tx.to = address(list[3].toUint()); tx.data = new bytes(68); for (uint i = 0; i < 68; i++) { tx.data[i] = rlpTransaction[rlpTransaction.length - 135 + i]; } return tx; }
2,545,553
[ 1, 1321, 84, 3342, 353, 279, 460, 622, 326, 5469, 434, 326, 2492, 19080, 18, 57, 75, 715, 7877, 14848, 364, 2037, 18, 4480, 1338, 1109, 18305, 8938, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 15674, 3790, 12, 3890, 30717, 3342, 13, 5381, 2713, 1135, 261, 3342, 3778, 2229, 13, 288, 203, 565, 534, 14461, 18, 54, 48, 1102, 874, 8526, 3778, 666, 273, 30717, 3342, 18, 869, 54, 48, 1102, 874, 7675, 869, 682, 5621, 203, 565, 2229, 18, 31604, 5147, 273, 666, 63, 21, 8009, 869, 5487, 5621, 203, 565, 2229, 18, 31604, 3039, 273, 666, 63, 22, 8009, 869, 5487, 5621, 203, 565, 2229, 18, 869, 273, 1758, 12, 1098, 63, 23, 8009, 869, 5487, 10663, 203, 565, 2229, 18, 892, 273, 394, 1731, 12, 9470, 1769, 203, 565, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 23797, 31, 277, 27245, 288, 203, 1377, 2229, 18, 892, 63, 77, 65, 273, 30717, 3342, 63, 1321, 84, 3342, 18, 2469, 300, 404, 4763, 397, 277, 15533, 203, 565, 289, 203, 565, 327, 2229, 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 ]
/** *Submitted for verification at hecoinfo.com on 2021-02-04 */ pragma solidity =0.6.6; interface ISwapMining { function swap(address account, address input, address output, uint256 amount) external returns (bool); } contract Ownable { address private _owner; constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } function isOwner(address account) public view returns (bool) { return account == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } modifier onlyOwner() { require(isOwner(msg.sender), "Ownable: caller is not the owner"); _; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } contract MdexRouter is IMdexRouter, Ownable { using SafeMath for uint256; address public immutable override factory; address public immutable override WHT; address public override swapMining; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'MdexRouter: EXPIRED'); _; } constructor(address _factory, address _WHT) public { factory = _factory; WHT = _WHT; } receive() external payable { assert(msg.sender == WHT); // only accept HT via fallback from the WHT contract } function pairFor(address tokenA, address tokenB) public view returns (address pair){ pair = IMdexFactory(factory).pairFor(tokenA, tokenB); } function setSwapMining(address _swapMininng) public onlyOwner { swapMining = _swapMininng; } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IMdexFactory(factory).getPair(tokenA, tokenB) == address(0)) { IMdexFactory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = IMdexFactory(factory).getReserves(tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = IMdexFactory(factory).quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'MdexRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = IMdexFactory(factory).quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'MdexRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = pairFor(tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IMdexPair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WHT, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = pairFor(token, WHT); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWHT(WHT).deposit{value : amountETH}(); assert(IWHT(WHT).transfer(pair, amountETH)); liquidity = IMdexPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = pairFor(tokenA, tokenB); IMdexPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IMdexPair(pair).burn(to); (address token0,) = IMdexFactory(factory).sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'MdexRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'MdexRouter: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WHT, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWHT(WHT).withdraw(amountETH); TransferHelper.safeTransferETH(to, 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 virtual override returns (uint amountA, uint amountB) { address pair = pairFor(tokenA, tokenB); uint value = approveMax ? uint(- 1) : liquidity; IMdexPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = pairFor(token, WHT); uint value = approveMax ? uint(- 1) : liquidity; IMdexPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WHT, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWHT(WHT).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = pairFor(token, WHT); uint value = approveMax ? uint(- 1) : liquidity; IMdexPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = IMdexFactory(factory).sortTokens(input, output); uint amountOut = amounts[i + 1]; if (swapMining != address(0)) { ISwapMining(swapMining).swap(msg.sender, input, output, amountOut); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? pairFor(output, path[i + 2]) : _to; IMdexPair(pairFor(input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = IMdexFactory(factory).getAmountsOut(amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'MdexRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = IMdexFactory(factory).getAmountsIn(amountOut, path); require(amounts[0] <= amountInMax, 'MdexRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WHT, 'MdexRouter: INVALID_PATH'); amounts = IMdexFactory(factory).getAmountsOut(msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'MdexRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWHT(WHT).deposit{value : amounts[0]}(); assert(IWHT(WHT).transfer(pairFor(path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WHT, 'MdexRouter: INVALID_PATH'); amounts = IMdexFactory(factory).getAmountsIn(amountOut, path); require(amounts[0] <= amountInMax, 'MdexRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWHT(WHT).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WHT, 'MdexRouter: INVALID_PATH'); amounts = IMdexFactory(factory).getAmountsOut(amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'MdexRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWHT(WHT).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WHT, 'MdexRouter: INVALID_PATH'); amounts = IMdexFactory(factory).getAmountsIn(amountOut, path); require(amounts[0] <= msg.value, 'MdexRouter: EXCESSIVE_INPUT_AMOUNT'); IWHT(WHT).deposit{value : amounts[0]}(); assert(IWHT(WHT).transfer(pairFor(path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = IMdexFactory(factory).sortTokens(input, output); IMdexPair pair = IMdexPair(pairFor(input, output)); uint amountInput; uint amountOutput; {// scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = IMdexFactory(factory).getAmountOut(amountInput, reserveInput, reserveOutput); } if (swapMining != address(0)) { ISwapMining(swapMining).swap(msg.sender, input, output, amountOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? pairFor(output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'MdexRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WHT, 'MdexRouter: INVALID_PATH'); uint amountIn = msg.value; IWHT(WHT).deposit{value : amountIn}(); assert(IWHT(WHT).transfer(pairFor(path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'MdexRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WHT, 'MdexRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, pairFor(path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WHT).balanceOf(address(this)); require(amountOut >= amountOutMin, 'MdexRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWHT(WHT).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) public view override returns (uint256 amountB) { return IMdexFactory(factory).quote(amountA, reserveA, reserveB); } function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) public view override returns (uint256 amountOut){ return IMdexFactory(factory).getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) public view override returns (uint256 amountIn){ return IMdexFactory(factory).getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint256 amountIn, address[] memory path) public view override returns (uint256[] memory amounts){ return IMdexFactory(factory).getAmountsOut(amountIn, path); } function getAmountsIn(uint256 amountOut, address[] memory path) public view override returns (uint256[] memory amounts){ return IMdexFactory(factory).getAmountsIn(amountOut, path); } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { uint256 constant WAD = 10 ** 18; uint256 constant RAY = 10 ** 27; function wad() public pure returns (uint256) { return WAD; } function ray() public pure returns (uint256) { return RAY; } 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) { // 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 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) { // 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 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; } 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; } function sqrt(uint256 a) internal pure returns (uint256 b) { if (a > 3) { b = a; uint256 x = a / 2 + 1; while (x < b) { b = x; x = (a / x + x) / 2; } } else if (a != 0) { b = 1; } } function wmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / WAD; } function wmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), WAD / 2) / WAD; } function rmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / RAY; } function rmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), RAY / 2) / RAY; } function wdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, WAD), b); } function wdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, WAD), b / 2) / b; } function rdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, RAY), b); } function rdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, RAY), b / 2) / b; } function wpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = WAD; while (n > 0) { if (n % 2 != 0) { result = wmul(result, x); } x = wmul(x, x); n /= 2; } return result; } function rpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = RAY; while (n > 0) { if (n % 2 != 0) { result = rmul(result, x); } x = rmul(x, x); n /= 2; } return result; } } // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value : value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
refund dust eth, if any
function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WHT, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = pairFor(token, WHT); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); assert(IWHT(WHT).transfer(pair, amountETH)); liquidity = IMdexPair(pair).mint(to); if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); }
12,884,550
[ 1, 1734, 1074, 302, 641, 13750, 16, 309, 1281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 48, 18988, 24237, 1584, 44, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 3844, 1345, 25683, 16, 203, 3639, 2254, 3844, 1345, 2930, 16, 203, 3639, 2254, 3844, 1584, 44, 2930, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 14096, 203, 565, 262, 3903, 5024, 3849, 8843, 429, 3387, 12, 22097, 1369, 13, 1135, 261, 11890, 3844, 1345, 16, 2254, 3844, 1584, 44, 16, 2254, 4501, 372, 24237, 13, 288, 203, 3639, 261, 8949, 1345, 16, 3844, 1584, 44, 13, 273, 389, 1289, 48, 18988, 24237, 12, 203, 5411, 1147, 16, 203, 5411, 678, 5062, 16, 203, 5411, 3844, 1345, 25683, 16, 203, 5411, 1234, 18, 1132, 16, 203, 5411, 3844, 1345, 2930, 16, 203, 5411, 3844, 1584, 44, 2930, 203, 3639, 11272, 203, 3639, 1758, 3082, 273, 3082, 1290, 12, 2316, 16, 678, 5062, 1769, 203, 3639, 12279, 2276, 18, 4626, 5912, 1265, 12, 2316, 16, 1234, 18, 15330, 16, 3082, 16, 3844, 1345, 1769, 203, 3639, 1815, 12, 45, 59, 5062, 12, 59, 5062, 2934, 13866, 12, 6017, 16, 3844, 1584, 44, 10019, 203, 3639, 4501, 372, 24237, 273, 6246, 561, 4154, 12, 6017, 2934, 81, 474, 12, 869, 1769, 203, 3639, 309, 261, 3576, 18, 1132, 405, 3844, 1584, 44, 13, 12279, 2276, 18, 4626, 5912, 1584, 44, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 300, 3844, 1584, 44, 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 ]
pragma solidity ^0.4.13; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; bool public teamStakesFrozen = true; mapping(address => uint256) balances; address public owner; function BasicToken() public { owner = msg.sender; } modifier notFrozen() { require(msg.sender != owner || (msg.sender == owner && !teamStakesFrozen)); _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public notFrozen returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public notFrozen returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public notFrozen returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract RI is StandardToken { string public constant name = "Fundaria Stake"; string public constant symbol = "RI"; uint8 public constant decimals = 0; } contract Sale is RI { using SafeMath for uint; /********** * Common * **********/ // THIS IS KEY VARIABLE AND DEFINED ACCORDING TO VALUE OF PLANNED COSTS ON THE PAGE https://business.fundaria.com uint public poolCapUSD = 1002750; // 1002750 initially // USD per 1 ether, added 10% aproximatelly to secure from wrong low price. We need add 10% of Stakes to supply to cover such price. uint public usdPerEther = 350; uint public supplyCap; // Current total supply cap according to lastStakePriceUSCents and poolCapUSD uint public businessPlannedPeriodDuration = 365 days; // total period planned for business activity 365 days uint public businessPlannedPeriodEndTimestamp; uint public teamCap; // team Stakes capacity uint8 public teamShare = 45; // share for team uint public distributedTeamStakes; // distributed Stakes to team uint public contractCreatedTimestamp; // when this contract was created address public pool = 0x1882464533072e9fCd8C6D3c5c5b588548B95296; // initial pool wallet address mapping (address=>bool) public rejectedInvestmentWithdrawals; uint public allowedAmountToTransferToPool; // this amount is increased when investor rejects to withdraw his/her investment uint public allowedAmountTransferedToPoolTotal; // sum of all allowedAmountToTransferToPool used uint public investmentGuidesRewardsWithdrawn; // total amount of rewards wei withdrawn by Guides /********** * Bounty * **********/ uint public distributedBountyStakes; // bounty advisors Stakes distributed total uint public bountyCap; // bounty advisors Stakes capacity uint8 public bountyShare = 7; // share for bounty /*********** * Sale * ***********/ address supplier = 0x0000000000000000000000000000000000000000; // address of Stakes initial supplier (abstract) // data to store invested wei value & Stakes for Investor struct saleData { uint stakes; // how many Stakes where recieved by this Investor total uint invested; // how much wei this Investor invested total uint bonusStakes; // how many bonus Stakes where recieved by this Investor uint guideReward; // Investment Guide reward amount address guide; // address of Investment Guide } mapping (address=>saleData) public saleStat; // invested value + Stakes data for every Investor uint public saleStartTimestamp = 1511373600; // regular Stakes sale start date uint public saleEndTimestamp = 1513965600; uint public distributedSaleStakes; // distributed stakes to all Investors uint public totalInvested; //how many invested total uint public totalWithdrawn; //how many withdrawn total uint public saleCap; // regular sale Stakes capacity uint8 public saleShare = 45; // share for regular sale uint public lastStakePriceUSCents; // Stake price in U.S. cents is determined according to current timestamp (the further - the higher price) uint[] public targetPrice; bool public priceIsFrozen = false; // stop increasing the price temporary (in case of low demand. Can be called only after saleEndTimestamp) /************************************ * Bonus Stakes & Investment Guides * ************************************/ // data to store Investment Guide reward struct guideData { bool registered; // is this Investment Guide registered uint accumulatedPotentialReward; // how many reward wei are potentially available uint rewardToWithdraw; // availabe reward to withdraw now uint periodicallyWithdrawnReward; // how much reward wei where withdrawn by this Investment Guide already } mapping (address=>guideData) public guidesStat; // mapping of Investment Guides datas uint public bonusCap; // max amount of bonus Stakes availabe uint public distributedBonusStakes; // how many bonus Stakes are already distributed uint public bonusShare = 3; // share of bonus Stakes in supplyCap uint8 public guideInvestmentAttractedShareToPay = 10; // reward for the Investment Guide /* WANT TO EARN ON STAKES SALE ? BECOME INVESTMENT GUIDE AND RECIEVE 10% OF ATTRACTED INVESTMENT ! INTRODUCE YOURSELF ON [email protected] & GIVE YOUR WALLET ADDRESS */ /********************************************* * To Pool transfers & Investment withdrawal * *********************************************/ uint8 public financePeriodsCount = 12; // How many finance periods in planned period uint[] public financePeriodsTimestamps; // Supportive array for searching current finance period uint public transferedToPool; // how much wei transfered to pool already /* EVENTS */ event StakesSale(address to, uint weiInvested, uint stakesRecieved, uint teamStakesRecieved, uint stake_price_us_cents); event BountyDistributed(address to, uint bountyStakes); event TransferedToPool(uint weiAmount, uint8 currentFinancialPeriodNo); event InvestmentWithdrawn(address to, uint withdrawnWeiAmount, uint stakesBurned, uint8 remainedFullFinancialPeriods); event UsdPerEtherChanged(uint oldUsdPerEther, uint newUsdPerEther); event BonusDistributed(address to, uint bonusStakes, address guide, uint accumulatedPotentialReward); event PoolCapChanged(uint oldCapUSD, uint newCapUSD); event RegisterGuide(address investmentGuide); event TargetPriceChanged(uint8 N, uint oldTargetPrice, uint newTargetPrice); event InvestmentGuideWithdrawReward(address investmentGuide, uint withdrawnRewardWei); modifier onlyOwner() { require(msg.sender==owner); _; } /** * @dev Determine duration of finance period, fill array with finance periods timestamps, * set businessPlannedPeriodEndTimestamp and contractCreatedTimestamp, */ function Sale() public { uint financePeriodDuration = businessPlannedPeriodDuration/financePeriodsCount; // quantity of seconds in chosen finance period // making array with timestamps of every finance period end date financePeriodsTimestamps.push(saleEndTimestamp); // first finance period is whole sale period for(uint8 i=1; i<=financePeriodsCount; i++) { financePeriodsTimestamps.push(saleEndTimestamp+financePeriodDuration*i); } businessPlannedPeriodEndTimestamp = saleEndTimestamp+businessPlannedPeriodDuration; contractCreatedTimestamp = now; targetPrice.push(1); // Initial Stake price mark in U.S. cents (1 cent = $0.01) targetPrice.push(10); // price mark at the sale period start timestamp targetPrice.push(100); // price mark at the sale period end timestamp targetPrice.push(1000); // price mark at hte end of business planned period balances[supplier] = 0; // nullify Stakes formal supplier balance } /** * @dev How many investment remained? Maximum investment is poolCapUSD * @return remainingInvestment in wei */ function remainingInvestment() public view returns(uint) { return poolCapUSD.div(usdPerEther).mul(1 ether).sub(totalInvested); } /** * @dev Dynamically set caps */ function setCaps() internal { // remaining Stakes are determined only from remainingInvestment saleCap = distributedSaleStakes+stakeForWei(remainingInvestment()); // max available Stakes for sale including already distributed supplyCap = saleCap.mul(100).div(saleShare); // max available Stakes for supplying teamCap = supplyCap.mul(teamShare).div(100); // max available team Stakes bonusCap = supplyCap.mul(bonusShare).div(100); // max available Stakes for bonus bountyCap = supplyCap.sub(saleCap).sub(teamCap).sub(bonusCap); // max available Stakes for bounty } /** * @dev Dynamically set the price of Stake in USD cents, which depends on current timestamp (price grows with time) */ function setStakePriceUSCents() internal { uint targetPriceFrom; uint targetPriceTo; uint startTimestamp; uint endTimestamp; // set price for pre sale period if(now < saleStartTimestamp) { targetPriceFrom = targetPrice[0]; targetPriceTo = targetPrice[1]; startTimestamp = contractCreatedTimestamp; endTimestamp = saleStartTimestamp; // set price for sale period } else if(now >= saleStartTimestamp && now < saleEndTimestamp) { targetPriceFrom = targetPrice[1]; targetPriceTo = targetPrice[2]; startTimestamp = saleStartTimestamp; endTimestamp = saleEndTimestamp; // set price for post sale period } else if(now >= saleEndTimestamp && now < businessPlannedPeriodEndTimestamp) { targetPriceFrom = targetPrice[2]; targetPriceTo = targetPrice[3]; startTimestamp = saleEndTimestamp; endTimestamp = businessPlannedPeriodEndTimestamp; } lastStakePriceUSCents = targetPriceFrom + ((now-startTimestamp)*(targetPriceTo-targetPriceFrom))/(endTimestamp-startTimestamp); } /** * @dev Recieve wei and process Stakes sale */ function() payable public { require(msg.sender != address(0)); require(msg.value > 0); // process only requests with wei require(now < businessPlannedPeriodEndTimestamp); // no later then at the end of planned period processSale(); } /** * @dev Process Stakes sale */ function processSale() internal { if(!priceIsFrozen) { // refresh price only if price is not frozen setStakePriceUSCents(); } setCaps(); uint teamStakes; // Stakes for the team according to teamShare uint saleStakes; // Stakes for the Sale uint weiInvested; // weiInvested now by this Investor uint trySaleStakes = stakeForWei(msg.value); // try to get this quantity of Stakes if(trySaleStakes > 1) { uint tryDistribute = distributedSaleStakes+trySaleStakes; // try to distribute this tryStakes if(tryDistribute <= saleCap) { // saleCap not reached saleStakes = trySaleStakes; // all tryStakes can be sold weiInvested = msg.value; // all current wei are accepted } else { saleStakes = saleCap-distributedSaleStakes; // only remnant of Stakes are available weiInvested = weiForStake(saleStakes); // wei for available remnant of Stakes } teamStakes = (saleStakes*teamShare).div(saleShare); // part of Stakes for a team if(saleStakes > 0) { balances[owner] += teamStakes; // rewarding team according to teamShare totalSupply += teamStakes; // supplying team Stakes distributedTeamStakes += teamStakes; // saving distributed team Stakes saleSupply(msg.sender, saleStakes, weiInvested); // process saleSupply if(saleStat[msg.sender].guide != address(0)) { // we have Investment Guide to reward and distribute bonus Stakes distributeBonusStakes(msg.sender, saleStakes, weiInvested); } } if(tryDistribute > saleCap) { msg.sender.transfer(msg.value-weiInvested); // return remnant } } else { msg.sender.transfer(msg.value); // return incorrect wei } } /** * @dev Transfer Stakes from owner balance to buyer balance & saving data to saleStat storage * @param _to is address of buyer * @param _stakes is quantity of Stakes transfered * @param _wei is value invested */ function saleSupply(address _to, uint _stakes, uint _wei) internal { require(_stakes > 0); balances[_to] += _stakes; // supply sold Stakes directly to buyer totalSupply += _stakes; distributedSaleStakes += _stakes; totalInvested = totalInvested.add(_wei); // adding to total investment // saving stat saleStat[_to].stakes += _stakes; // stating Stakes bought saleStat[_to].invested = saleStat[_to].invested.add(_wei); // stating wei invested Transfer(supplier, _to, _stakes); } /** * @dev Set new owner * @param new_owner new owner */ function setNewOwner(address new_owner) public onlyOwner { owner = new_owner; } /** * @dev Set new ether price in USD. Should be changed when price grow-fall 5%-10% * @param new_usd_per_ether new price */ function setUsdPerEther(uint new_usd_per_ether) public onlyOwner { UsdPerEtherChanged(usdPerEther, new_usd_per_ether); usdPerEther = new_usd_per_ether; } /** * @dev Set address of wallet where investment will be transfered for further using in business transactions * @param _pool new address of the Pool */ function setPoolAddress(address _pool) public onlyOwner { pool = _pool; } /** * @dev Change Pool capacity in USD * @param new_pool_cap_usd new Pool cap in $ */ function setPoolCapUSD(uint new_pool_cap_usd) public onlyOwner { PoolCapChanged(poolCapUSD, new_pool_cap_usd); poolCapUSD = new_pool_cap_usd; } /** * @dev Register Investment Guide * @param investment_guide address of Investment Guide */ function registerGuide(address investment_guide) public onlyOwner { guidesStat[investment_guide].registered = true; RegisterGuide(investment_guide); } /** * @dev Stop increasing price dynamically. Set it as static temporary. */ function freezePrice() public onlyOwner { priceIsFrozen = true; } /** * @dev Continue increasing price dynamically (the standard, usual algorithm). */ function unfreezePrice() public onlyOwner { priceIsFrozen = false; // this means that price is unfrozen } /** * @dev Ability to tune dynamic price changing with time. */ function setTargetPrice(uint8 n, uint stake_price_us_cents) public onlyOwner { TargetPriceChanged(n, targetPrice[n], stake_price_us_cents); targetPrice[n] = stake_price_us_cents; } /** * @dev Get and set address of Investment Guide and distribute bonus Stakes and Guide reward * @param key address of Investment Guide */ function getBonusStakesPermanently(address key) public { require(guidesStat[key].registered); require(saleStat[msg.sender].guide == address(0)); // Investment Guide is not applied yet for this Investor saleStat[msg.sender].guide = key; // apply Inv. Guide if(saleStat[msg.sender].invested > 0) { // we have invested value, process distribution of bonus Stakes and rewarding a Guide distributeBonusStakes(msg.sender, saleStat[msg.sender].stakes, saleStat[msg.sender].invested); } } /** * @dev Distribute bonus Stakes to Investor according to bonusShare * @param _to to which Investor to distribute * @param added_stakes how many Stakes are added by this Investor * @param added_wei how much wei are invested by this Investor * @return wei quantity */ function distributeBonusStakes(address _to, uint added_stakes, uint added_wei) internal { uint added_bonus_stakes = (added_stakes*((bonusShare*100).div(saleShare)))/100; // how many bonus Stakes to add require(distributedBonusStakes+added_bonus_stakes <= bonusCap); // check is bonus cap is not overflowed uint added_potential_reward = (added_wei*guideInvestmentAttractedShareToPay)/100; // reward for the Guide if(!rejectedInvestmentWithdrawals[_to]) { guidesStat[saleStat[_to].guide].accumulatedPotentialReward += added_potential_reward; // save potential reward for the Guide } else { guidesStat[saleStat[_to].guide].rewardToWithdraw += added_potential_reward; // let linked Investment Guide to withdraw all this reward } saleStat[_to].guideReward += added_potential_reward; // add guideReward wei value for stat saleStat[_to].bonusStakes += added_bonus_stakes; // add bonusStakes for stat balances[_to] += added_bonus_stakes; // transfer bonus Stakes distributedBonusStakes += added_bonus_stakes; // save bonus Stakes distribution totalSupply += added_bonus_stakes; // increase totalSupply BonusDistributed(_to, added_bonus_stakes, saleStat[_to].guide, added_potential_reward); } /** * @dev Get current finance period number * @return current finance period number */ function currentFinancePeriod() internal view returns(uint8) { uint8 current_finance_period = 0; for(uint8 i=0; i <= financePeriodsCount; i++) { current_finance_period = i; if(now<financePeriodsTimestamps[i]) { break; } } return current_finance_period; } /** * @dev Show how much wei can withdraw Investment Guide * @param _guide address of registered guide * @return wei quantity */ function guideRewardToWithdraw(address _guide) public view returns(uint) { // reward to withdraw depends on current finance period and do not include potentially withdraw amount of investment return (guidesStat[_guide].accumulatedPotentialReward*(currentFinancePeriod()+1))/(financePeriodsCount+1) + guidesStat[_guide].rewardToWithdraw - guidesStat[_guide].periodicallyWithdrawnReward; } /* weiForStake & stakeForWei functions sometimes show not correct translated value from dapp interface (view) because lastStakePriceUSCents sometimes temporary outdated (in view mode) but it doesn't mean that execution itself is not correct */ /** * @dev Translate wei to Stakes * @param input_wei is wei to translate into stakes, * @return Stakes quantity */ function stakeForWei(uint input_wei) public view returns(uint) { return ((input_wei*usdPerEther*100)/1 ether)/lastStakePriceUSCents; } /** * @dev Translate Stakes to wei * @param input_stake is stakes to translate into wei * @return wei quantity */ function weiForStake(uint input_stake) public view returns(uint) { return (input_stake*lastStakePriceUSCents*1 ether)/(usdPerEther*100); } /** * @dev Transfer wei from this contract to pool wallet partially only, * 1) for funding promotion of Stakes sale * 2) according to share (finance_periods_last + current_finance_period) / business_planned_period */ function transferToPool() public onlyOwner { uint max_available; // max_available funds for transfering to pool uint amountToTransfer; // amount to transfer to pool // search end timestamp of current financial period for(uint8 i=0; i <= financePeriodsCount; i++) { // found end timestamp of current financial period OR now is later then business planned end date (transfer wei remnant) if(now < financePeriodsTimestamps[i] || (i == financePeriodsCount && now > financePeriodsTimestamps[i])) { // avaialbe only part of total value of total invested funds with substracted total allowed amount transfered max_available = ((i+1)*(totalInvested+totalWithdrawn-allowedAmountTransferedToPoolTotal))/(financePeriodsCount+1); // not all max_available funds are transfered at the moment OR we have allowed amount to transfer if(max_available > transferedToPool-allowedAmountTransferedToPoolTotal || allowedAmountToTransferToPool > 0) { if(allowedAmountToTransferToPool > 0) { // we have allowed by Investor (rejected to withdraw) amount amountToTransfer = allowedAmountToTransferToPool; // to transfer this allowed amount allowedAmountTransferedToPoolTotal += allowedAmountToTransferToPool; // add allowed amount to total allowed amount allowedAmountToTransferToPool = 0; } else { amountToTransfer = max_available-transferedToPool; // only remained amount is available to transfer } if(amountToTransfer > this.balance) { // remained amount to transfer more then current balance amountToTransfer = this.balance; // correct amount to transfer } transferedToPool += amountToTransfer; // increase transfered to pool amount pool.transfer(amountToTransfer); TransferedToPool(amountToTransfer, i+1); } allowedAmountToTransferToPool=0; break; } } } /** * @dev Investor can withdraw part of his/her investment. * A size of this part depends on how many financial periods last and how many remained. * Investor gives back all stakes which he/she got for his/her investment. */ function withdrawInvestment() public { require(!rejectedInvestmentWithdrawals[msg.sender]); // this Investor not rejected to withdraw their investment require(saleStat[msg.sender].stakes > 0); require(balances[msg.sender] >= saleStat[msg.sender].stakes+saleStat[msg.sender].bonusStakes); // Investor has needed stakes to return uint remained; // all investment which are available to withdraw by all Investors uint to_withdraw; // available funds to withdraw for this particular Investor for(uint8 i=0; i < financePeriodsCount; i++) { // last fin. period is not available if(now<financePeriodsTimestamps[i]) { // find end timestamp of current financial period remained = totalInvested - ((i+1)*totalInvested)/(financePeriodsCount+1); // remained investment to withdraw by all Investors to_withdraw = (saleStat[msg.sender].invested*remained)/totalInvested; // investment to withdraw by this Investor uint sale_stakes_to_burn = saleStat[msg.sender].stakes+saleStat[msg.sender].bonusStakes; // returning all Stakes saved in saleStat[msg.sender] uint team_stakes_to_burn = (saleStat[msg.sender].stakes*teamShare)/saleShare; // appropriate issued team Stakes are also burned balances[owner] = balances[owner].sub(team_stakes_to_burn); // burn appropriate team Stakes distributedTeamStakes -= team_stakes_to_burn; // remove team Stakes from distribution balances[msg.sender] = balances[msg.sender].sub(sale_stakes_to_burn); // burn stakes got for invested wei totalInvested = totalInvested.sub(to_withdraw); // decrease invested total value totalSupply = totalSupply.sub(sale_stakes_to_burn).sub(team_stakes_to_burn); // totalSupply is decreased distributedSaleStakes -= saleStat[msg.sender].stakes; if(saleStat[msg.sender].guide != address(0)) { // we have Guide and bonusStakes // potential reward for the Guide is decreased proportionally guidesStat[saleStat[msg.sender].guide].accumulatedPotentialReward -= (saleStat[msg.sender].guideReward - ((i+1)*saleStat[msg.sender].guideReward)/(financePeriodsCount+1)); distributedBonusStakes -= saleStat[msg.sender].bonusStakes; saleStat[msg.sender].bonusStakes = 0; saleStat[msg.sender].guideReward = 0; } saleStat[msg.sender].stakes = 0; // nullify Stakes recieved value saleStat[msg.sender].invested = 0; // nullify wei invested value totalWithdrawn += to_withdraw; msg.sender.transfer(to_withdraw); // witdraw investment InvestmentWithdrawn(msg.sender, to_withdraw, sale_stakes_to_burn, financePeriodsCount-i); break; } } } /** * @dev Investor rejects withdraw investment. This lets Investment Guide withdraw all his/her reward related to this Investor */ function rejectInvestmentWithdrawal() public { rejectedInvestmentWithdrawals[msg.sender] = true; address guide = saleStat[msg.sender].guide; if(guide != address(0)) { // Inv. Guide exists if(saleStat[msg.sender].guideReward >= guidesStat[guide].periodicallyWithdrawnReward) { // already withdrawed less then to withdraw for this Investor uint remainedRewardToWithdraw = saleStat[msg.sender].guideReward-guidesStat[guide].periodicallyWithdrawnReward; guidesStat[guide].periodicallyWithdrawnReward = 0; // withdrawn reward is counted as withdrawn of this Investor reward if(guidesStat[guide].accumulatedPotentialReward >= remainedRewardToWithdraw) { // we have enough potential reward guidesStat[guide].accumulatedPotentialReward -= remainedRewardToWithdraw; // decrease potential reward guidesStat[guide].rewardToWithdraw += remainedRewardToWithdraw; // increase total amount to withdraw right now } else { guidesStat[guide].accumulatedPotentialReward = 0; // something wrong so nullify } } else { // substract current Investor's reward from periodically withdrawn reward to remove it from withdrawned guidesStat[guide].periodicallyWithdrawnReward -= saleStat[msg.sender].guideReward; // we have enough potential reward - all ok if(guidesStat[guide].accumulatedPotentialReward >= saleStat[msg.sender].guideReward) { // we do not count this Investor guideReward in potential reward guidesStat[guide].accumulatedPotentialReward -= saleStat[msg.sender].guideReward; guidesStat[guide].rewardToWithdraw += saleStat[msg.sender].guideReward; // increase total amount to withdraw right now } else { guidesStat[guide].accumulatedPotentialReward = 0; // something wrong so nullify } } } allowedAmountToTransferToPool += saleStat[msg.sender].invested; } /** * @dev Distribute bounty rewards for bounty tasks * @param _to is address of bounty hunter * @param _stakes is quantity of Stakes transfered */ function distributeBounty(address _to, uint _stakes) public onlyOwner { require(distributedBountyStakes+_stakes <= bountyCap); // no more then maximum capacity can be distributed balances[_to] = balances[_to].add(_stakes); // to totalSupply += _stakes; distributedBountyStakes += _stakes; // adding to total bounty distributed BountyDistributed(_to, _stakes); } /** * @dev Unfreeze team Stakes. Only after excessed Stakes have burned. */ function unFreeze() public onlyOwner { // only after planned period if(now > businessPlannedPeriodEndTimestamp) { teamStakesFrozen = false; // make team stakes available for transfering } } }
/* @dev Translate wei to Stakes @param input_wei is wei to translate into stakes, @return Stakes quantity/
function stakeForWei(uint input_wei) public view returns(uint) { return ((input_wei*usdPerEther*100)/1 ether)/lastStakePriceUSCents; }
14,117,076
[ 1, 19, 225, 16820, 732, 77, 358, 934, 3223, 225, 810, 67, 1814, 77, 353, 732, 77, 358, 4204, 1368, 384, 3223, 16, 327, 934, 3223, 10457, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 384, 911, 1290, 3218, 77, 12, 11890, 810, 67, 1814, 77, 13, 1071, 1476, 1135, 12, 11890, 13, 288, 203, 1377, 327, 14015, 2630, 67, 1814, 77, 14, 407, 72, 2173, 41, 1136, 14, 6625, 13176, 21, 225, 2437, 13176, 2722, 510, 911, 5147, 57, 2312, 4877, 31, 377, 203, 565, 289, 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 ]
./partial_match/1/0xb0c37D51270C5F1d566A33e1f991a3a2DFA15632/sources/JE.sol
1.8% from total supply maxWallet
maxWallet = 18000000 * 1e18;
15,960,157
[ 1, 21, 18, 28, 9, 628, 2078, 14467, 943, 16936, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 943, 16936, 273, 6549, 9449, 380, 404, 73, 2643, 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 ]
/** * Submitted for verification at Etherscan.io on 2017-07-05 * @note: represents a non-standard ERC20 token that contains a * transferFrom function that does not return bool */ pragma solidity 0.5.12; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public; event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint256 size) { require(msg.data.length >= size + 4, "Payload attack"); _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC202 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public; function approve(address spender, uint256 value) public; event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC202 { mapping(address => mapping(address => uint256)) public allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) { uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require( (_value != 0) && (allowed[msg.sender][_spender] == 0), "Invalid approval" ); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 value); event MintFinished(); bool public mintingFinished = false; uint256 public totalSupply = 0; /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused, "NOT PAUSED"); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused, "PAUSED"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } /** * Pausable token * * Simple ERC20 Token example, with pausable token creation **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused { super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused { super.transferFrom(_from, _to, _value); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a time has passed */ contract TokenTimelock { // ERC20 basic token contract being held ERC20Basic token; // beneficiary of tokens after they are released address beneficiary; // timestamp where token release is enabled uint256 releaseTime; constructor(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @dev beneficiary claims tokens held by time lock */ function claim() public { require(msg.sender == beneficiary); require(now >= releaseTime); uint256 amount = token.balanceOf(address(this)); require(amount > 0); token.transfer(beneficiary, amount); } } /** * @title OMGToken * @dev Omise Go Token contract */ contract OMGToken is PausableToken, MintableToken { using SafeMath for uint256; string public name = "OMGToken"; string public symbol = "OMG"; uint256 public decimals = 18; /** * @dev mint timelocked tokens */ function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime) public onlyOwner returns (TokenTimelock) { TokenTimelock timelock = new TokenTimelock(this, _to, _releaseTime); mint(address(timelock), _amount); return timelock; } }
* @title Basic token @dev Basic version of StandardToken, with no allowances./
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; modifier onlyPayloadSize(uint256 size) { require(msg.data.length >= size + 4, "Payload attack"); _; } function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
977,607
[ 1, 8252, 1147, 225, 7651, 1177, 434, 8263, 1345, 16, 598, 1158, 1699, 6872, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7651, 1345, 353, 4232, 39, 3462, 8252, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 324, 26488, 31, 203, 203, 225, 9606, 1338, 6110, 1225, 12, 11890, 5034, 963, 13, 288, 203, 565, 2583, 12, 3576, 18, 892, 18, 2469, 1545, 963, 397, 1059, 16, 315, 6110, 13843, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 203, 565, 1071, 203, 565, 1338, 6110, 1225, 12, 22, 380, 3847, 13, 203, 225, 288, 203, 565, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 565, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 565, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 225, 289, 203, 203, 225, 445, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 1476, 1135, 261, 11890, 5034, 11013, 13, 288, 203, 565, 327, 324, 26488, 63, 67, 8443, 15533, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.1; // Contract for buying and selling apratments or houses contract ApartmentContract { // Counts number of contracts, also used for contract ID uint256 public count = 0; // Contract has 3 states // Active - means still paying // Finished - means paid total sum // Cancelled - means buyer cancelled the contract enum Status {Cancelled, Finished, Active} // Apartment contract struct Apartment { uint256 id; string name; uint256 totalSum; uint256 paidSum; address payable seller; address payable buyer; Status status; } // Map of contracts // Key - Contract ID // Value - Contract information mapping(uint256 => Apartment) public apartments; // Event is called when a new contract created event ContractCreated( uint256 id, string name, uint256 totalSum, uint256 paidSum, address seller, address buyer, Status status ); // Event is called when a payment is transfered event ContractPayed( uint256 id, string name, uint256 totalSum, uint256 paidSum, address seller, Status status ); // Event is called when contract is finished (fully paid) event ContractFinished(uint256 id, string name, Status status); // Event is called when buyer cancels the contract event ContractCancelled(uint256 id, string name, Status status); // Constructor when the contract is first created // The contract "Test contract" is for tests constructor() public { createContract( "Test contract", 5, 0x090ec50a3f1184251E1041E5310F0f324FBD908E ); } // Function to create a new contract // _name - address of apartment or house // _totalSum - total sum in ether // _seller - address of seller function createContract( string memory _name, uint256 _totalSum, address payable _seller ) public { count++; apartments[count] = Apartment( count, _name, _totalSum, 0, _seller, msg.sender, Status.Active ); emit ContractCreated( count, _name, _totalSum, 0, _seller, msg.sender, Status.Active ); } // Function for paying to seller // _id - contract ID // The function is payable and the amount is transfered to seller and logged in paidSum function addPayment(uint256 _id) public payable { require(_id <= count); require(apartments[_id].status == Status.Active); apartments[_id].paidSum += msg.value; apartments[_id].seller.transfer(msg.value); if (apartments[_id].paidSum >= apartments[_id].totalSum) setFinished(_id); emit ContractPayed( _id, apartments[_id].name, apartments[_id].totalSum, apartments[_id].paidSum, apartments[_id].seller, apartments[_id].status ); } // Function to get the paid amount // _id - contract ID function getPaidSum(uint256 _id) public view returns (uint256) { return apartments[_id].paidSum; } // Function to get how much left to pay for the apartment or house // _id - contract ID function getDifference(uint256 _id) public view returns (uint256) { return apartments[_id].totalSum - apartments[_id].paidSum; } // Function to check if contract is active // _id - contract ID function isActive(uint256 _id) public view returns (bool) { return apartments[_id].status == Status.Active; } // Function to get contract status // _id - contract ID function getStatus(uint256 _id) public view returns (Status) { return apartments[_id].status; } // Function to cancel the contract and make it un-payable, only buyer can cancel it and only when it is active // _id - contract ID function setCancelled(uint256 _id) public { require(apartments[_id].status == Status.Active); require(apartments[_id].buyer == msg.sender); apartments[_id].status = Status.Cancelled; emit ContractCancelled( _id, apartments[_id].name, apartments[_id].status ); } // Function finish the contract and make it un-payable // It is private and can be called only from the function addPayment // _id - contract ID function setFinished(uint256 _id) private { apartments[_id].status = Status.Finished; emit ContractFinished( _id, apartments[_id].name, apartments[_id].status ); } }
Constructor when the contract is first created The contract "Test contract" is for tests
constructor() public { createContract( "Test contract", 5, 0x090ec50a3f1184251E1041E5310F0f324FBD908E ); }
13,009,991
[ 1, 6293, 1347, 326, 6835, 353, 1122, 2522, 1021, 6835, 315, 4709, 6835, 6, 353, 364, 7434, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 752, 8924, 12, 203, 5411, 315, 4709, 6835, 3113, 203, 5411, 1381, 16, 203, 5411, 374, 92, 5908, 20, 557, 3361, 69, 23, 74, 2499, 5193, 2947, 21, 41, 2163, 9803, 41, 8643, 2163, 42, 20, 74, 1578, 24, 42, 18096, 29, 6840, 41, 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 ]
./full_match/4/0x61b92a7F45711e38BAA3b97c1897de970904D6e2/sources/B20.sol
solhint-disable-line no-empty-blocks
ERC20Capped(cap) {}
687,328
[ 1, 18281, 11317, 17, 8394, 17, 1369, 1158, 17, 5531, 17, 7996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 4232, 39, 3462, 4664, 1845, 12, 5909, 13, 2618, 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 ]
./full_match/80001/0x42dbBd5ae373FEA2FC320F62d44C058522Bb3758/sources/contracts/MemecoinMatic.flatten.sol
* @dev Allows address with granted MINTER_ROLE to mint a number of coins @param _account Address where will minted coins appear @param _amount Amount of coins to mint/
function mint(address _account, uint256 _amount) external override { revert("ERROR_CHILD_TOKEN_DOES_NOT_ALLOW_DIRECT_MINTING"); }
9,441,013
[ 1, 19132, 1758, 598, 17578, 6989, 2560, 67, 16256, 358, 312, 474, 279, 1300, 434, 276, 9896, 225, 389, 4631, 5267, 1625, 903, 312, 474, 329, 276, 9896, 9788, 225, 389, 8949, 16811, 434, 276, 9896, 358, 312, 474, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 312, 474, 12, 2867, 389, 4631, 16, 2254, 5034, 389, 8949, 13, 203, 565, 3903, 203, 565, 3849, 203, 225, 288, 203, 565, 15226, 2932, 3589, 67, 27043, 67, 8412, 67, 3191, 3991, 67, 4400, 67, 13511, 67, 17541, 67, 49, 3217, 1360, 8863, 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 ]
pragma solidity 0.5.10; import "../interfaces/IBlockRewardAuRa.sol"; import "../interfaces/IERC677.sol"; import "../interfaces/IStakingAuRa.sol"; import "../interfaces/IValidatorSetAuRa.sol"; import "../upgradeability/UpgradeableOwned.sol"; import "../libs/SafeMath.sol"; /// @dev Implements staking and withdrawal logic. contract StakingAuRaBase is UpgradeableOwned, IStakingAuRa { using SafeMath for uint256; // =============================================== Storage ======================================================== // WARNING: since this contract is upgradeable, do not remove // existing storage variables, do not change their order, // and do not change their types! address[] internal _pools; address[] internal _poolsInactive; address[] internal _poolsToBeElected; address[] internal _poolsToBeRemoved; uint256[] internal _poolsLikelihood; uint256 internal _poolsLikelihoodSum; mapping(address => address[]) internal _poolDelegators; mapping(address => address[]) internal _poolDelegatorsInactive; mapping(address => address[]) internal _stakerPools; mapping(address => mapping(address => uint256)) internal _stakerPoolsIndexes; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _stakeAmountByEpoch; mapping(address => uint256) internal _stakeInitial; // Reserved storage space to allow for layout changes in the future. uint256[24] private ______gapForInternal; /// @dev The limit of the minimum candidate stake (CANDIDATE_MIN_STAKE). uint256 public candidateMinStake; /// @dev The limit of the minimum delegator stake (DELEGATOR_MIN_STAKE). uint256 public delegatorMinStake; /// @dev The snapshot of tokens amount staked into the specified pool by the specified delegator /// before the specified staking epoch. Used by the `claimReward` function. /// The first parameter is the pool staking address, the second one is delegator's address, /// the third one is staking epoch number. mapping(address => mapping(address => mapping(uint256 => uint256))) public delegatorStakeSnapshot; /// @dev The current amount of staking tokens/coins ordered for withdrawal from the specified /// pool by the specified staker. Used by the `orderWithdraw`, `claimOrderedWithdraw` and other functions. /// The first parameter is the pool staking address, the second one is the staker address. mapping(address => mapping(address => uint256)) public orderedWithdrawAmount; /// @dev The current total amount of staking tokens/coins ordered for withdrawal from /// the specified pool by all of its stakers. Pool staking address is accepted as a parameter. mapping(address => uint256) public orderedWithdrawAmountTotal; /// @dev The number of the staking epoch during which the specified staker ordered /// the latest withdraw from the specified pool. Used by the `claimOrderedWithdraw` function /// to allow the ordered amount to be claimed only in future staking epochs. The first parameter /// is the pool staking address, the second one is the staker address. mapping(address => mapping(address => uint256)) public orderWithdrawEpoch; /// @dev The delegator's index in the array returned by the `poolDelegators` getter. /// Used by the `_removePoolDelegator` internal function. The first parameter is a pool staking address. /// The second parameter is delegator's address. /// If the value is zero, it may mean the array doesn't contain the delegator. /// Check if the delegator is in the array using the `poolDelegators` getter. mapping(address => mapping(address => uint256)) public poolDelegatorIndex; /// @dev The delegator's index in the `poolDelegatorsInactive` array. /// Used by the `_removePoolDelegatorInactive` internal function. /// A delegator is considered inactive if they have withdrawn their stake from /// the specified pool but haven't yet claimed an ordered amount. /// The first parameter is a pool staking address. The second parameter is delegator's address. mapping(address => mapping(address => uint256)) public poolDelegatorInactiveIndex; /// @dev The pool's index in the array returned by the `getPoolsInactive` getter. /// Used by the `_removePoolInactive` internal function. The pool staking address is accepted as a parameter. mapping(address => uint256) public poolInactiveIndex; /// @dev The pool's index in the array returned by the `getPools` getter. /// Used by the `_removePool` internal function. A pool staking address is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `isPoolActive` getter. mapping(address => uint256) public poolIndex; /// @dev The pool's index in the array returned by the `getPoolsToBeElected` getter. /// Used by the `_deletePoolToBeElected` and `_isPoolToBeElected` internal functions. /// The pool staking address is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `getPoolsToBeElected` getter. mapping(address => uint256) public poolToBeElectedIndex; /// @dev The pool's index in the array returned by the `getPoolsToBeRemoved` getter. /// Used by the `_deletePoolToBeRemoved` internal function. /// The pool staking address is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `getPoolsToBeRemoved` getter. mapping(address => uint256) public poolToBeRemovedIndex; /// @dev A boolean flag indicating whether the reward was already taken /// from the specified pool by the specified staker for the specified staking epoch. /// The first parameter is the pool staking address, the second one is staker's address, /// the third one is staking epoch number. mapping(address => mapping(address => mapping(uint256 => bool))) public rewardWasTaken; /// @dev The amount of tokens currently staked into the specified pool by the specified /// staker. Doesn't include the amount ordered for withdrawal. /// The first parameter is the pool staking address, the second one is the staker address. mapping(address => mapping(address => uint256)) public stakeAmount; /// @dev The number of staking epoch before which the specified delegator placed their first /// stake into the specified pool. If this is equal to zero, it means the delegator never /// staked into the specified pool. The first parameter is the pool staking address, /// the second one is delegator's address. mapping(address => mapping(address => uint256)) public stakeFirstEpoch; /// @dev The number of staking epoch before which the specified delegator withdrew their stake /// from the specified pool. If this is equal to zero and `stakeFirstEpoch` is not zero, that means /// the delegator still has some stake in the specified pool. The first parameter is the pool /// staking address, the second one is delegator's address. mapping(address => mapping(address => uint256)) public stakeLastEpoch; /// @dev The duration period (in blocks) at the end of staking epoch during which /// participants are not allowed to stake/withdraw/order/claim their staking tokens/coins. uint256 public stakeWithdrawDisallowPeriod; /// @dev The serial number of the current staking epoch. uint256 public stakingEpoch; /// @dev The duration of a staking epoch in blocks. uint256 public stakingEpochDuration; /// @dev The number of the first block of the current staking epoch. uint256 public stakingEpochStartBlock; /// @dev Returns the total amount of staking tokens/coins currently staked into the specified pool. /// Doesn't include the amount ordered for withdrawal. /// The pool staking address is accepted as a parameter. mapping(address => uint256) public stakeAmountTotal; /// @dev The address of the `ValidatorSetAuRa` contract. IValidatorSetAuRa public validatorSetContract; /// @dev The block number of the last change in this contract. /// Can be used by Staking DApp. uint256 public lastChangeBlock; // Reserved storage space to allow for layout changes in the future. uint256[24] private ______gapForPublic; // ============================================== Constants ======================================================= /// @dev The max number of candidates (including validators). This limit was determined through stress testing. uint256 public constant MAX_CANDIDATES = 3000; // ================================================ Events ======================================================== /// @dev Emitted by `_addPoolActive` internal function to signal that /// the specified staking address created a new pool. /// @param poolStakingAddress The staking address of newly added pool. event AddedPool(address indexed poolStakingAddress); /// @dev Emitted by the `claimOrderedWithdraw` function to signal the staker withdrew the specified /// amount of requested tokens/coins from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress The pool from which the `staker` withdrew the `amount`. /// @param staker The address of the staker that withdrew the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the claim was made. /// @param amount The withdrawal amount. event ClaimedOrderedWithdrawal( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount ); /// @dev Emitted by the `moveStake` function to signal the staker moved the specified /// amount of stake from one pool to another during the specified staking epoch. /// @param fromPoolStakingAddress The pool from which the `staker` moved the stake. /// @param toPoolStakingAddress The destination pool where the `staker` moved the stake. /// @param staker The address of the staker who moved the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the `amount` was moved. /// @param amount The stake amount which was moved. event MovedStake( address fromPoolStakingAddress, address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount ); /// @dev Emitted by the `orderWithdraw` function to signal the staker ordered the withdrawal of the /// specified amount of their stake from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress The pool from which the `staker` ordered a withdrawal of the `amount`. /// @param staker The address of the staker that ordered the withdrawal of the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the order was made. /// @param amount The ordered withdrawal amount. Can be either positive or negative. /// See the `orderWithdraw` function. event OrderedWithdrawal( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, int256 amount ); /// @dev Emitted by the `stake` function to signal the staker placed a stake of the specified /// amount for the specified pool during the specified staking epoch. /// @param toPoolStakingAddress The pool in which the `staker` placed the stake. /// @param staker The address of the staker that placed the stake. /// @param stakingEpoch The serial number of the staking epoch during which the stake was made. /// @param amount The stake amount. event PlacedStake( address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount ); /// @dev Emitted by `_removePool` internal function to signal that /// a pool with the specified staking address was removed. /// @param poolStakingAddress The staking address of removed pool. event RemovedPool(address indexed poolStakingAddress); /// @dev Emitted by the `withdraw` function to signal the staker withdrew the specified /// amount of a stake from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress The pool from which the `staker` withdrew the `amount`. /// @param staker The address of staker that withdrew the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the withdrawal was made. /// @param amount The withdrawal amount. event WithdrewStake( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount ); // ============================================== Modifiers ======================================================= /// @dev Ensures the transaction gas price is not zero. modifier gasPriceIsValid() { require(tx.gasprice != 0); _; } /// @dev Ensures the caller is the BlockRewardAuRa contract address. modifier onlyBlockRewardContract() { require(msg.sender == validatorSetContract.blockRewardContract()); _; } /// @dev Ensures the `initialize` function was called before. modifier onlyInitialized { require(isInitialized()); _; } /// @dev Ensures the caller is the ValidatorSetAuRa contract address. modifier onlyValidatorSetContract() { require(msg.sender == address(validatorSetContract)); _; } // =============================================== Setters ======================================================== /// @dev Fallback function. Prevents direct sending native coins to this contract. function () payable external { revert(); } /// @dev Adds a new candidate's pool to the list of active pools (see the `getPools` getter) and /// moves the specified amount of staking tokens/coins from the candidate's staking address /// to the candidate's pool. A participant calls this function using their staking address when /// they want to create a pool. This is a wrapper for the `stake` function. /// @param _amount The amount of tokens to be staked. Ignored when staking in native coins /// because `msg.value` is used in that case. /// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address /// (msg.sender). This address cannot be equal to `msg.sender`. function addPool(uint256 _amount, address _miningAddress) external payable { _addPool(_amount, msg.sender, _miningAddress, false); } /// @dev Adds the `unremovable validator` to either the `poolsToBeElected` or the `poolsToBeRemoved` array /// depending on their own stake in their own pool when they become removable. This allows the /// `ValidatorSetAuRa.newValidatorSet` function to recognize the unremovable validator as a regular removable pool. /// Called by the `ValidatorSet.clearUnremovableValidator` function. /// @param _unremovableStakingAddress The staking address of the unremovable validator. function clearUnremovableValidator(address _unremovableStakingAddress) external onlyValidatorSetContract { require(_unremovableStakingAddress != address(0)); if (stakeAmount[_unremovableStakingAddress][_unremovableStakingAddress] != 0) { _addPoolToBeElected(_unremovableStakingAddress); _setLikelihood(_unremovableStakingAddress); } else { _addPoolToBeRemoved(_unremovableStakingAddress); } } /// @dev Increments the serial number of the current staking epoch. /// Called by the `ValidatorSetAuRa.newValidatorSet` at the last block of the finished staking epoch. function incrementStakingEpoch() external onlyValidatorSetContract { stakingEpoch++; } /// @dev Initializes the network parameters. /// Can only be called by the constructor of the `InitializerAuRa` contract or owner. /// @param _validatorSetContract The address of the `ValidatorSetAuRa` contract. /// @param _initialStakingAddresses The array of initial validators' staking addresses. /// @param _delegatorMinStake The minimum allowed amount of delegator stake in Wei. /// @param _candidateMinStake The minimum allowed amount of candidate/validator stake in Wei. /// @param _stakingEpochDuration The duration of a staking epoch in blocks /// (e.g., 120954 = 1 week for 5-seconds blocks in AuRa). /// @param _stakingEpochStartBlock The number of the first block of initial staking epoch /// (must be zero if the network is starting from genesis block). /// @param _stakeWithdrawDisallowPeriod The duration period (in blocks) at the end of a staking epoch /// during which participants cannot stake/withdraw/order/claim their staking tokens/coins /// (e.g., 4320 = 6 hours for 5-seconds blocks in AuRa). function initialize( address _validatorSetContract, address[] calldata _initialStakingAddresses, uint256 _delegatorMinStake, uint256 _candidateMinStake, uint256 _stakingEpochDuration, uint256 _stakingEpochStartBlock, uint256 _stakeWithdrawDisallowPeriod ) external { require(_validatorSetContract != address(0)); require(_initialStakingAddresses.length > 0); require(_delegatorMinStake != 0); require(_candidateMinStake != 0); require(_stakingEpochDuration != 0); require(_stakingEpochDuration > _stakeWithdrawDisallowPeriod); require(_stakeWithdrawDisallowPeriod != 0); require(_getCurrentBlockNumber() == 0 || msg.sender == _admin()); require(!isInitialized()); // initialization can only be done once validatorSetContract = IValidatorSetAuRa(_validatorSetContract); address unremovableStakingAddress = validatorSetContract.unremovableValidator(); for (uint256 i = 0; i < _initialStakingAddresses.length; i++) { require(_initialStakingAddresses[i] != address(0)); _addPoolActive(_initialStakingAddresses[i], false); if (_initialStakingAddresses[i] != unremovableStakingAddress) { _addPoolToBeRemoved(_initialStakingAddresses[i]); } } delegatorMinStake = _delegatorMinStake; candidateMinStake = _candidateMinStake; stakingEpochDuration = _stakingEpochDuration; stakingEpochStartBlock = _stakingEpochStartBlock; stakeWithdrawDisallowPeriod = _stakeWithdrawDisallowPeriod; lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Makes initial validator stakes. Can only be called by the owner /// before the network starts (after `initialize` is called but before `stakingEpochStartBlock`). /// Cannot be called more than once and cannot be called when starting from genesis. /// Requires `StakingAuRa` contract balance to be equal to the `_totalAmount`. /// @param _totalAmount The initial validator total stake amount (for all initial validators). function initialValidatorStake(uint256 _totalAmount) external onlyOwner { uint256 currentBlock = _getCurrentBlockNumber(); require(stakingEpoch == 0); require(currentBlock < stakingEpochStartBlock); require(_thisBalance() == _totalAmount); require(_totalAmount % _pools.length == 0); uint256 stakingAmount = _totalAmount.div(_pools.length); uint256 stakingEpochStartBlock_ = stakingEpochStartBlock; // Temporarily set `stakingEpochStartBlock` to the current block number // to avoid revert in the `_stake` function stakingEpochStartBlock = currentBlock; for (uint256 i = 0; i < _pools.length; i++) { address stakingAddress = _pools[i]; require(stakeAmount[stakingAddress][stakingAddress] == 0); _stake(stakingAddress, stakingAddress, stakingAmount); _stakeInitial[stakingAddress] = stakingAmount; } // Restore `stakingEpochStartBlock` value stakingEpochStartBlock = stakingEpochStartBlock_; } /// @dev Removes a specified pool from the `pools` array (a list of active pools which can be retrieved by the /// `getPools` getter). Called by the `ValidatorSetAuRa._removeMaliciousValidator` internal function /// when a pool must be removed by the algorithm. /// @param _stakingAddress The staking address of the pool to be removed. function removePool(address _stakingAddress) external onlyValidatorSetContract { _removePool(_stakingAddress); } /// @dev Removes pools which are in the `_poolsToBeRemoved` internal array from the `pools` array. /// Called by the `ValidatorSetAuRa.newValidatorSet` function when a pool must be removed by the algorithm. function removePools() external onlyValidatorSetContract { address[] memory poolsToRemove = _poolsToBeRemoved; for (uint256 i = 0; i < poolsToRemove.length; i++) { _removePool(poolsToRemove[i]); } } /// @dev Removes the candidate's or validator's pool from the `pools` array (a list of active pools which /// can be retrieved by the `getPools` getter). When a candidate or validator wants to remove their pool, /// they should call this function from their staking address. A validator cannot remove their pool while /// they are an `unremovable validator`. function removeMyPool() external gasPriceIsValid onlyInitialized { address stakingAddress = msg.sender; address miningAddress = validatorSetContract.miningByStakingAddress(stakingAddress); // initial validator cannot remove their pool during the initial staking epoch require(stakingEpoch > 0 || !validatorSetContract.isValidator(miningAddress)); require(stakingAddress != validatorSetContract.unremovableValidator()); _removePool(stakingAddress); } /// @dev Sets the number of the first block in the upcoming staking epoch. /// Called by the `ValidatorSetAuRa.newValidatorSet` function at the last block of a staking epoch. /// @param _blockNumber The number of the very first block in the upcoming staking epoch. function setStakingEpochStartBlock(uint256 _blockNumber) external onlyValidatorSetContract { stakingEpochStartBlock = _blockNumber; } /// @dev Moves staking tokens/coins from one pool to another. A staker calls this function when they want /// to move their tokens/coins from one pool to another without withdrawing their tokens/coins. /// @param _fromPoolStakingAddress The staking address of the source pool. /// @param _toPoolStakingAddress The staking address of the target pool. /// @param _amount The amount of staking tokens/coins to be moved. The amount cannot exceed the value returned /// by the `maxWithdrawAllowed` getter. function moveStake( address _fromPoolStakingAddress, address _toPoolStakingAddress, uint256 _amount ) external { require(_fromPoolStakingAddress != _toPoolStakingAddress); address staker = msg.sender; _withdraw(_fromPoolStakingAddress, staker, _amount); _stake(_toPoolStakingAddress, staker, _amount); emit MovedStake(_fromPoolStakingAddress, _toPoolStakingAddress, staker, stakingEpoch, _amount); } /// @dev Moves the specified amount of staking tokens/coins from the staker's address to the staking address of /// the specified pool. Actually, the amount is stored in a balance of this StakingAuRa contract. /// A staker calls this function when they want to make a stake into a pool. /// @param _toPoolStakingAddress The staking address of the pool where the tokens should be staked. /// @param _amount The amount of tokens to be staked. Ignored when staking in native coins /// because `msg.value` is used instead. function stake(address _toPoolStakingAddress, uint256 _amount) external payable { _stake(_toPoolStakingAddress, _amount); } /// @dev Moves the specified amount of staking tokens/coins from the staking address of /// the specified pool to the staker's address. A staker calls this function when they want to withdraw /// their tokens/coins. /// @param _fromPoolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn. /// @param _amount The amount of tokens/coins to be withdrawn. The amount cannot exceed the value returned /// by the `maxWithdrawAllowed` getter. function withdraw(address _fromPoolStakingAddress, uint256 _amount) external { address payable staker = msg.sender; _withdraw(_fromPoolStakingAddress, staker, _amount); _sendWithdrawnStakeAmount(staker, _amount); emit WithdrewStake(_fromPoolStakingAddress, staker, stakingEpoch, _amount); } /// @dev Orders tokens/coins withdrawal from the staking address of the specified pool to the /// staker's address. The requested tokens/coins can be claimed after the current staking epoch is complete using /// the `claimOrderedWithdraw` function. /// @param _poolStakingAddress The staking address of the pool from which the amount will be withdrawn. /// @param _amount The amount to be withdrawn. A positive value means the staker wants to either set or /// increase their withdrawal amount. A negative value means the staker wants to decrease a /// withdrawal amount that was previously set. The amount cannot exceed the value returned by the /// `maxWithdrawOrderAllowed` getter. function orderWithdraw(address _poolStakingAddress, int256 _amount) external gasPriceIsValid onlyInitialized { require(_poolStakingAddress != address(0)); require(_amount != 0); address staker = msg.sender; require(_isWithdrawAllowed( validatorSetContract.miningByStakingAddress(_poolStakingAddress), staker != _poolStakingAddress )); uint256 newOrderedAmount = orderedWithdrawAmount[_poolStakingAddress][staker]; uint256 newOrderedAmountTotal = orderedWithdrawAmountTotal[_poolStakingAddress]; uint256 newStakeAmount = stakeAmount[_poolStakingAddress][staker]; uint256 newStakeAmountTotal = stakeAmountTotal[_poolStakingAddress]; if (_amount > 0) { uint256 amount = uint256(_amount); // How much can `staker` order for withdrawal from `_poolStakingAddress` at the moment? require(amount <= maxWithdrawOrderAllowed(_poolStakingAddress, staker)); newOrderedAmount = newOrderedAmount.add(amount); newOrderedAmountTotal = newOrderedAmountTotal.add(amount); newStakeAmount = newStakeAmount.sub(amount); newStakeAmountTotal = newStakeAmountTotal.sub(amount); orderWithdrawEpoch[_poolStakingAddress][staker] = stakingEpoch; } else { uint256 amount = uint256(-_amount); newOrderedAmount = newOrderedAmount.sub(amount); newOrderedAmountTotal = newOrderedAmountTotal.sub(amount); newStakeAmount = newStakeAmount.add(amount); newStakeAmountTotal = newStakeAmountTotal.add(amount); } orderedWithdrawAmount[_poolStakingAddress][staker] = newOrderedAmount; orderedWithdrawAmountTotal[_poolStakingAddress] = newOrderedAmountTotal; stakeAmount[_poolStakingAddress][staker] = newStakeAmount; stakeAmountTotal[_poolStakingAddress] = newStakeAmountTotal; if (staker == _poolStakingAddress) { // Initial validator cannot withdraw their initial stake require(newStakeAmount >= _stakeInitial[staker]); // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and `candidateMinStake` require(newStakeAmount == 0 || newStakeAmount >= candidateMinStake); address unremovableStakingAddress = validatorSetContract.unremovableValidator(); if (_amount > 0) { // if the validator orders the `_amount` for withdrawal if (newStakeAmount == 0 && _poolStakingAddress != unremovableStakingAddress) { // If the removable validator orders their entire stake, // mark their pool as `to be removed` _addPoolToBeRemoved(_poolStakingAddress); } } else { // If the validator wants to reduce withdrawal value, // add their pool as `active` if it hasn't already done _addPoolActive(_poolStakingAddress, _poolStakingAddress != unremovableStakingAddress); } } else { // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and `delegatorMinStake` require(newStakeAmount == 0 || newStakeAmount >= delegatorMinStake); if (_amount > 0) { // if the delegator orders the `_amount` for withdrawal if (newStakeAmount == 0) { // If the delegator orders their entire stake, // remove the delegator from delegator list of the pool _removePoolDelegator(_poolStakingAddress, staker); } } else { // If the delegator wants to reduce withdrawal value, // add them to delegator list of the pool if it hasn't already done _addPoolDelegator(_poolStakingAddress, staker); } // Remember stake movement to use it later in the `claimReward` function _snapshotDelegatorStake(_poolStakingAddress, staker); } _setLikelihood(_poolStakingAddress); emit OrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, _amount); } /// @dev Withdraws the staking tokens/coins from the specified pool ordered during the previous staking epochs with /// the `orderWithdraw` function. The ordered amount can be retrieved by the `orderedWithdrawAmount` getter. /// @param _poolStakingAddress The staking address of the pool from which the ordered tokens/coins are withdrawn. function claimOrderedWithdraw(address _poolStakingAddress) external { address payable staker = msg.sender; require(stakingEpoch > orderWithdrawEpoch[_poolStakingAddress][staker]); require(_isWithdrawAllowed( validatorSetContract.miningByStakingAddress(_poolStakingAddress), staker != _poolStakingAddress )); uint256 claimAmount = orderedWithdrawAmount[_poolStakingAddress][staker]; require(claimAmount != 0); orderedWithdrawAmount[_poolStakingAddress][staker] = 0; orderedWithdrawAmountTotal[_poolStakingAddress] = orderedWithdrawAmountTotal[_poolStakingAddress].sub(claimAmount); if (stakeAmount[_poolStakingAddress][staker] == 0) { _withdrawCheckPool(_poolStakingAddress, staker); } _sendWithdrawnStakeAmount(staker, claimAmount); emit ClaimedOrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, claimAmount); } /// @dev Sets (updates) the limit of the minimum candidate stake (CANDIDATE_MIN_STAKE). /// Can only be called by the `owner`. /// @param _minStake The value of a new limit in Wei. function setCandidateMinStake(uint256 _minStake) external onlyOwner onlyInitialized { candidateMinStake = _minStake; } /// @dev Sets (updates) the limit of the minimum delegator stake (DELEGATOR_MIN_STAKE). /// Can only be called by the `owner`. /// @param _minStake The value of a new limit in Wei. function setDelegatorMinStake(uint256 _minStake) external onlyOwner onlyInitialized { delegatorMinStake = _minStake; } // =============================================== Getters ======================================================== /// @dev Returns an array of the current active pools (the staking addresses of candidates and validators). /// The size of the array cannot exceed MAX_CANDIDATES. A pool can be added to this array with the `_addPoolActive` /// internal function which is called by the `stake` or `orderWithdraw` function. A pool is considered active /// if its address has at least the minimum stake and this stake is not ordered to be withdrawn. function getPools() external view returns(address[] memory) { return _pools; } /// @dev Returns an array of the current inactive pools (the staking addresses of former candidates). /// A pool can be added to this array with the `_addPoolInactive` internal function which is called /// by `_removePool`. A pool is considered inactive if it is banned for some reason, if its address /// has zero stake, or if its entire stake is ordered to be withdrawn. function getPoolsInactive() external view returns(address[] memory) { return _poolsInactive; } /// @dev Returns the array of stake amounts for each corresponding /// address in the `poolsToBeElected` array (see the `getPoolsToBeElected` getter) and a sum of these amounts. /// Used by the `ValidatorSetAuRa.newValidatorSet` function when randomly selecting new validators at the last /// block of a staking epoch. An array value is updated every time any staked amount is changed in this pool /// (see the `_setLikelihood` internal function). /// @return `uint256[] likelihoods` - The array of the coefficients. The array length is always equal to the length /// of the `poolsToBeElected` array. /// `uint256 sum` - The total sum of the amounts. function getPoolsLikelihood() external view returns(uint256[] memory likelihoods, uint256 sum) { return (_poolsLikelihood, _poolsLikelihoodSum); } /// @dev Returns the list of pools (their staking addresses) which will participate in a new validator set /// selection process in the `ValidatorSetAuRa.newValidatorSet` function. This is an array of pools /// which will be considered as candidates when forming a new validator set (at the last block of a staking epoch). /// This array is kept updated by the `_addPoolToBeElected` and `_deletePoolToBeElected` internal functions. function getPoolsToBeElected() external view returns(address[] memory) { return _poolsToBeElected; } /// @dev Returns the list of pools (their staking addresses) which will be removed by the /// `ValidatorSetAuRa.newValidatorSet` function from the active `pools` array (at the last block /// of a staking epoch). This array is kept updated by the `_addPoolToBeRemoved` /// and `_deletePoolToBeRemoved` internal functions. A pool is added to this array when the pool's /// address withdraws (or orders) all of its own staking tokens from the pool, inactivating the pool. function getPoolsToBeRemoved() external view returns(address[] memory) { return _poolsToBeRemoved; } /// @dev Returns the list of pools (staking addresses) into which the specified staker have ever staked. /// @param _staker The staker address (it can be a delegator or a pool staking address itself). /// @param _offset The index in the array at which the reading should start. Ignored if the `_length` is 0. /// @param _length The max number of items to return. function getStakerPools( address _staker, uint256 _offset, uint256 _length ) external view returns(address[] memory result) { address[] storage stakerPools = _stakerPools[_staker]; if (_length == 0) { return stakerPools; } uint256 maxLength = stakerPools.length.sub(_offset); result = new address[](_length > maxLength ? maxLength : _length); for (uint256 i = 0; i < result.length; i++) { result[i] = stakerPools[_offset + i]; } } /// @dev Returns the length of the list of pools into which the specified staker have ever staked. /// @param _staker The staker address (it can be a delegator or a pool staking address itself). function getStakerPoolsLength(address _staker) external view returns(uint256) { return _stakerPools[_staker].length; } /// @dev Determines whether staking/withdrawal operations are allowed at the moment. /// Used by all staking/withdrawal functions. function areStakeAndWithdrawAllowed() public view returns(bool) { uint256 currentBlock = _getCurrentBlockNumber(); if (currentBlock < stakingEpochStartBlock) return false; uint256 allowedDuration = stakingEpochDuration - stakeWithdrawDisallowPeriod; if (stakingEpochStartBlock == 0) allowedDuration++; return currentBlock - stakingEpochStartBlock < allowedDuration; } /// @dev Returns a boolean flag indicating if the `initialize` function has been called. function isInitialized() public view returns(bool) { return validatorSetContract != IValidatorSetAuRa(0); } /// @dev Returns a flag indicating whether a specified address is in the `pools` array. /// See the `getPools` getter. /// @param _stakingAddress The staking address of the pool. function isPoolActive(address _stakingAddress) public view returns(bool) { uint256 index = poolIndex[_stakingAddress]; return index < _pools.length && _pools[index] == _stakingAddress; } /// @dev Returns the maximum amount which can be withdrawn from the specified pool by the specified staker /// at the moment. Used by the `withdraw` and `moveStake` functions. /// @param _poolStakingAddress The pool staking address from which the withdrawal will be made. /// @param _staker The staker address that is going to withdraw. function maxWithdrawAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) { address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); bool isDelegator = _poolStakingAddress != _staker; if (!_isWithdrawAllowed(miningAddress, isDelegator)) { return 0; } uint256 canWithdraw = stakeAmount[_poolStakingAddress][_staker]; if (!isDelegator) { // Initial validator cannot withdraw their initial stake canWithdraw = canWithdraw.sub(_stakeInitial[_staker]); } if (!validatorSetContract.isValidatorOrPending(miningAddress)) { // The pool is not a validator and is not going to become one, // so the staker can only withdraw staked amount minus already // ordered amount return canWithdraw; } // The pool is a validator (active or pending), so the staker can only // withdraw staked amount minus already ordered amount but // no more than the amount staked during the current staking epoch uint256 stakedDuringEpoch = stakeAmountByCurrentEpoch(_poolStakingAddress, _staker); if (canWithdraw > stakedDuringEpoch) { canWithdraw = stakedDuringEpoch; } return canWithdraw; } /// @dev Returns the maximum amount which can be ordered to be withdrawn from the specified pool by the /// specified staker at the moment. Used by the `orderWithdraw` function. /// @param _poolStakingAddress The pool staking address from which the withdrawal will be ordered. /// @param _staker The staker address that is going to order the withdrawal. function maxWithdrawOrderAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) { address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); bool isDelegator = _poolStakingAddress != _staker; if (!_isWithdrawAllowed(miningAddress, isDelegator)) { return 0; } if (!validatorSetContract.isValidatorOrPending(miningAddress)) { // If the pool is a candidate (not an active validator and not pending one), // no one can order withdrawal from the `_poolStakingAddress`, but // anyone can withdraw immediately (see the `maxWithdrawAllowed` getter) return 0; } // If the pool is an active or pending validator, the staker can order withdrawal // up to their total staking amount minus an already ordered amount // minus an amount staked during the current staking epoch uint256 canOrder = stakeAmount[_poolStakingAddress][_staker]; if (!isDelegator) { // Initial validator cannot withdraw their initial stake canOrder = canOrder.sub(_stakeInitial[_staker]); } return canOrder.sub(stakeAmountByCurrentEpoch(_poolStakingAddress, _staker)); } /// @dev Returns an array of the current active delegators of the specified pool. /// A delegator is considered active if they have staked into the specified /// pool and their stake is not ordered to be withdrawn. /// @param _poolStakingAddress The pool staking address. function poolDelegators(address _poolStakingAddress) public view returns(address[] memory) { return _poolDelegators[_poolStakingAddress]; } /// @dev Returns an array of the current inactive delegators of the specified pool. /// A delegator is considered inactive if their entire stake is ordered to be withdrawn /// but not yet claimed. /// @param _poolStakingAddress The pool staking address. function poolDelegatorsInactive(address _poolStakingAddress) public view returns(address[] memory) { return _poolDelegatorsInactive[_poolStakingAddress]; } /// @dev Returns the amount of staking tokens/coins staked into the specified pool by the specified staker /// during the current staking epoch (see the `stakingEpoch` getter). /// Used by the `stake`, `withdraw`, and `orderWithdraw` functions. /// @param _poolStakingAddress The pool staking address. /// @param _staker The staker's address. function stakeAmountByCurrentEpoch(address _poolStakingAddress, address _staker) public view returns(uint256) { return _stakeAmountByEpoch[_poolStakingAddress][_staker][stakingEpoch]; } /// @dev Returns the number of the last block of the current staking epoch. function stakingEpochEndBlock() public view returns(uint256) { uint256 startBlock = stakingEpochStartBlock; return startBlock + stakingEpochDuration - (startBlock == 0 ? 0 : 1); } // ============================================== Internal ======================================================== /// @dev Adds the specified staking address to the array of active pools returned by /// the `getPools` getter. Used by the `stake`, `addPool`, and `orderWithdraw` functions. /// @param _stakingAddress The pool added to the array of active pools. /// @param _toBeElected The boolean flag which defines whether the specified address should be /// added simultaneously to the `poolsToBeElected` array. See the `getPoolsToBeElected` getter. function _addPoolActive(address _stakingAddress, bool _toBeElected) internal { if (!isPoolActive(_stakingAddress)) { poolIndex[_stakingAddress] = _pools.length; _pools.push(_stakingAddress); require(_pools.length <= _getMaxCandidates()); emit AddedPool(_stakingAddress); } _removePoolInactive(_stakingAddress); if (_toBeElected) { _addPoolToBeElected(_stakingAddress); } } /// @dev Adds the specified staking address to the array of inactive pools returned by /// the `getPoolsInactive` getter. Used by the `_removePool` internal function. /// @param _stakingAddress The pool added to the array of inactive pools. function _addPoolInactive(address _stakingAddress) internal { uint256 index = poolInactiveIndex[_stakingAddress]; uint256 length = _poolsInactive.length; if (index >= length || _poolsInactive[index] != _stakingAddress) { poolInactiveIndex[_stakingAddress] = length; _poolsInactive.push(_stakingAddress); } } /// @dev Adds the specified staking address to the array of pools returned by the `getPoolsToBeElected` /// getter. Used by the `_addPoolActive` internal function. See the `getPoolsToBeElected` getter. /// @param _stakingAddress The pool added to the `poolsToBeElected` array. function _addPoolToBeElected(address _stakingAddress) internal { uint256 index = poolToBeElectedIndex[_stakingAddress]; uint256 length = _poolsToBeElected.length; if (index >= length || _poolsToBeElected[index] != _stakingAddress) { poolToBeElectedIndex[_stakingAddress] = length; _poolsToBeElected.push(_stakingAddress); _poolsLikelihood.push(0); // assumes the likelihood is set with `_setLikelihood` function hereinafter } _deletePoolToBeRemoved(_stakingAddress); } /// @dev Adds the specified staking address to the array of pools returned by the `getPoolsToBeRemoved` /// getter. Used by withdrawal functions. See the `getPoolsToBeRemoved` getter. /// @param _stakingAddress The pool added to the `poolsToBeRemoved` array. function _addPoolToBeRemoved(address _stakingAddress) internal { uint256 index = poolToBeRemovedIndex[_stakingAddress]; uint256 length = _poolsToBeRemoved.length; if (index >= length || _poolsToBeRemoved[index] != _stakingAddress) { poolToBeRemovedIndex[_stakingAddress] = length; _poolsToBeRemoved.push(_stakingAddress); } _deletePoolToBeElected(_stakingAddress); } /// @dev Deletes the specified staking address from the array of pools returned by the /// `getPoolsToBeElected` getter. Used by the `_addPoolToBeRemoved` and `_removePool` internal functions. /// See the `getPoolsToBeElected` getter. /// @param _stakingAddress The pool deleted from the `poolsToBeElected` array. function _deletePoolToBeElected(address _stakingAddress) internal { if (_poolsToBeElected.length != _poolsLikelihood.length) return; uint256 indexToDelete = poolToBeElectedIndex[_stakingAddress]; if (_poolsToBeElected.length > indexToDelete && _poolsToBeElected[indexToDelete] == _stakingAddress) { if (_poolsLikelihoodSum >= _poolsLikelihood[indexToDelete]) { _poolsLikelihoodSum -= _poolsLikelihood[indexToDelete]; } else { _poolsLikelihoodSum = 0; } uint256 lastPoolIndex = _poolsToBeElected.length - 1; address lastPool = _poolsToBeElected[lastPoolIndex]; _poolsToBeElected[indexToDelete] = lastPool; _poolsLikelihood[indexToDelete] = _poolsLikelihood[lastPoolIndex]; poolToBeElectedIndex[lastPool] = indexToDelete; poolToBeElectedIndex[_stakingAddress] = 0; _poolsToBeElected.length--; _poolsLikelihood.length--; } } /// @dev Deletes the specified staking address from the array of pools returned by the /// `getPoolsToBeRemoved` getter. Used by the `_addPoolToBeElected` and `_removePool` internal functions. /// See the `getPoolsToBeRemoved` getter. /// @param _stakingAddress The pool deleted from the `poolsToBeRemoved` array. function _deletePoolToBeRemoved(address _stakingAddress) internal { uint256 indexToDelete = poolToBeRemovedIndex[_stakingAddress]; if (_poolsToBeRemoved.length > indexToDelete && _poolsToBeRemoved[indexToDelete] == _stakingAddress) { address lastPool = _poolsToBeRemoved[_poolsToBeRemoved.length - 1]; _poolsToBeRemoved[indexToDelete] = lastPool; poolToBeRemovedIndex[lastPool] = indexToDelete; poolToBeRemovedIndex[_stakingAddress] = 0; _poolsToBeRemoved.length--; } } /// @dev Removes the specified staking address from the array of active pools returned by /// the `getPools` getter. Used by the `removePool`, `removeMyPool`, and withdrawal functions. /// @param _stakingAddress The pool removed from the array of active pools. function _removePool(address _stakingAddress) internal { uint256 indexToRemove = poolIndex[_stakingAddress]; if (_pools.length > indexToRemove && _pools[indexToRemove] == _stakingAddress) { address lastPool = _pools[_pools.length - 1]; _pools[indexToRemove] = lastPool; poolIndex[lastPool] = indexToRemove; poolIndex[_stakingAddress] = 0; _pools.length--; emit RemovedPool(_stakingAddress); } if (_isPoolEmpty(_stakingAddress)) { _removePoolInactive(_stakingAddress); } else { _addPoolInactive(_stakingAddress); } _deletePoolToBeElected(_stakingAddress); _deletePoolToBeRemoved(_stakingAddress); lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Removes the specified staking address from the array of inactive pools returned by /// the `getPoolsInactive` getter. Used by withdrawal functions, by the `_addPoolActive` and /// `_removePool` internal functions. /// @param _stakingAddress The pool removed from the array of inactive pools. function _removePoolInactive(address _stakingAddress) internal { uint256 indexToRemove = poolInactiveIndex[_stakingAddress]; if (_poolsInactive.length > indexToRemove && _poolsInactive[indexToRemove] == _stakingAddress) { address lastPool = _poolsInactive[_poolsInactive.length - 1]; _poolsInactive[indexToRemove] = lastPool; poolInactiveIndex[lastPool] = indexToRemove; poolInactiveIndex[_stakingAddress] = 0; _poolsInactive.length--; } } /// @dev Used by `addPool` and `onTokenTransfer` functions. See their descriptions and code. /// @param _amount The amount of tokens to be staked. Ignored when staking in native coins /// because `msg.value` is used in that case. /// @param _stakingAddress The staking address of the new candidate. /// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address /// (msg.sender). This address cannot be equal to `_stakingAddress`. /// @param _byOnTokenTransfer A boolean flag defining whether this internal function is called /// by the `onTokenTransfer` function. function _addPool( uint256 _amount, address _stakingAddress, address _miningAddress, bool _byOnTokenTransfer ) internal { validatorSetContract.setStakingAddress(_miningAddress, _stakingAddress); if (_byOnTokenTransfer) { _stake(_stakingAddress, _stakingAddress, _amount); } else { _stake(_stakingAddress, _amount); } } /// @dev Adds the specified address to the array of the current active delegators of the specified pool. /// Used by the `stake` and `orderWithdraw` functions. See the `poolDelegators` getter. /// @param _poolStakingAddress The pool staking address. /// @param _delegator The delegator's address. function _addPoolDelegator(address _poolStakingAddress, address _delegator) internal { address[] storage delegators = _poolDelegators[_poolStakingAddress]; uint256 index = poolDelegatorIndex[_poolStakingAddress][_delegator]; uint256 length = delegators.length; if (index >= length || delegators[index] != _delegator) { poolDelegatorIndex[_poolStakingAddress][_delegator] = length; delegators.push(_delegator); } _removePoolDelegatorInactive(_poolStakingAddress, _delegator); } /// @dev Adds the specified address to the array of the current inactive delegators of the specified pool. /// Used by the `_removePoolDelegator` internal function. /// @param _poolStakingAddress The pool staking address. /// @param _delegator The delegator's address. function _addPoolDelegatorInactive(address _poolStakingAddress, address _delegator) internal { address[] storage delegators = _poolDelegatorsInactive[_poolStakingAddress]; uint256 index = poolDelegatorInactiveIndex[_poolStakingAddress][_delegator]; uint256 length = delegators.length; if (index >= length || delegators[index] != _delegator) { poolDelegatorInactiveIndex[_poolStakingAddress][_delegator] = length; delegators.push(_delegator); } } /// @dev Removes the specified address from the array of the current active delegators of the specified pool. /// Used by the withdrawal functions. See the `poolDelegators` getter. /// @param _poolStakingAddress The pool staking address. /// @param _delegator The delegator's address. function _removePoolDelegator(address _poolStakingAddress, address _delegator) internal { address[] storage delegators = _poolDelegators[_poolStakingAddress]; uint256 indexToRemove = poolDelegatorIndex[_poolStakingAddress][_delegator]; if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) { address lastDelegator = delegators[delegators.length - 1]; delegators[indexToRemove] = lastDelegator; poolDelegatorIndex[_poolStakingAddress][lastDelegator] = indexToRemove; poolDelegatorIndex[_poolStakingAddress][_delegator] = 0; delegators.length--; } if (orderedWithdrawAmount[_poolStakingAddress][_delegator] != 0) { _addPoolDelegatorInactive(_poolStakingAddress, _delegator); } else { _removePoolDelegatorInactive(_poolStakingAddress, _delegator); } } /// @dev Removes the specified address from the array of the inactive delegators of the specified pool. /// Used by the `_addPoolDelegator` and `_removePoolDelegator` internal functions. /// @param _poolStakingAddress The pool staking address. /// @param _delegator The delegator's address. function _removePoolDelegatorInactive(address _poolStakingAddress, address _delegator) internal { address[] storage delegators = _poolDelegatorsInactive[_poolStakingAddress]; uint256 indexToRemove = poolDelegatorInactiveIndex[_poolStakingAddress][_delegator]; if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) { address lastDelegator = delegators[delegators.length - 1]; delegators[indexToRemove] = lastDelegator; poolDelegatorInactiveIndex[_poolStakingAddress][lastDelegator] = indexToRemove; poolDelegatorInactiveIndex[_poolStakingAddress][_delegator] = 0; delegators.length--; } } function _sendWithdrawnStakeAmount(address payable _to, uint256 _amount) internal; /// @dev Calculates (updates) the probability of being selected as a validator for the specified pool /// and updates the total sum of probability coefficients. Actually, the probability is equal to the /// amount totally staked into the pool. See the `getPoolsLikelihood` getter. /// Used by the staking and withdrawal functions. /// @param _poolStakingAddress The address of the pool for which the probability coefficient must be updated. function _setLikelihood(address _poolStakingAddress) internal { lastChangeBlock = _getCurrentBlockNumber(); (bool isToBeElected, uint256 index) = _isPoolToBeElected(_poolStakingAddress); if (!isToBeElected) return; uint256 oldValue = _poolsLikelihood[index]; uint256 newValue = stakeAmountTotal[_poolStakingAddress]; _poolsLikelihood[index] = newValue; if (newValue >= oldValue) { _poolsLikelihoodSum = _poolsLikelihoodSum.add(newValue - oldValue); } else { _poolsLikelihoodSum = _poolsLikelihoodSum.sub(oldValue - newValue); } } /// @dev Makes a snapshot of the amount currently staked by the specified delegator /// into the specified pool (staking address). Used by the `orderWithdraw`, `_stake`, and `_withdraw` functions. /// @param _poolStakingAddress The staking address of the pool. /// @param _delegator The address of the delegator. function _snapshotDelegatorStake(address _poolStakingAddress, address _delegator) internal { uint256 nextStakingEpoch = stakingEpoch + 1; uint256 newAmount = stakeAmount[_poolStakingAddress][_delegator]; delegatorStakeSnapshot[_poolStakingAddress][_delegator][nextStakingEpoch] = (newAmount != 0) ? newAmount : uint256(-1); if (stakeFirstEpoch[_poolStakingAddress][_delegator] == 0) { stakeFirstEpoch[_poolStakingAddress][_delegator] = nextStakingEpoch; } stakeLastEpoch[_poolStakingAddress][_delegator] = (newAmount == 0) ? nextStakingEpoch : 0; } function _stake(address _toPoolStakingAddress, uint256 _amount) internal; /// @dev The internal function used by the `_stake` and `moveStake` functions. /// See the `stake` public function for more details. /// @param _poolStakingAddress The staking address of the pool where the tokens/coins should be staked. /// @param _staker The staker's address. /// @param _amount The amount of tokens/coins to be staked. function _stake( address _poolStakingAddress, address _staker, uint256 _amount ) internal gasPriceIsValid onlyInitialized { address poolMiningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); require(poolMiningAddress != address(0)); require(_poolStakingAddress != address(0)); require(_amount != 0); require(!validatorSetContract.isValidatorBanned(poolMiningAddress)); require(areStakeAndWithdrawAllowed()); uint256 newStakeAmount = stakeAmount[_poolStakingAddress][_staker].add(_amount); if (_staker == _poolStakingAddress) { // The staked amount must be at least CANDIDATE_MIN_STAKE require(newStakeAmount >= candidateMinStake); } else { // The staked amount must be at least DELEGATOR_MIN_STAKE require(newStakeAmount >= delegatorMinStake); // The delegator cannot stake into the pool of the candidate which hasn't self-staked. // Also, that candidate shouldn't want to withdraw all their funds. require(stakeAmount[_poolStakingAddress][_poolStakingAddress] != 0); } stakeAmount[_poolStakingAddress][_staker] = newStakeAmount; _stakeAmountByEpoch[_poolStakingAddress][_staker][stakingEpoch] = stakeAmountByCurrentEpoch(_poolStakingAddress, _staker).add(_amount); stakeAmountTotal[_poolStakingAddress] = stakeAmountTotal[_poolStakingAddress].add(_amount); if (_staker == _poolStakingAddress) { // `staker` places a stake for himself and becomes a candidate // Add `_poolStakingAddress` to the array of pools _addPoolActive(_poolStakingAddress, _poolStakingAddress != validatorSetContract.unremovableValidator()); } else { // Add `_staker` to the array of pool's delegators _addPoolDelegator(_poolStakingAddress, _staker); // Save amount value staked by the delegator _snapshotDelegatorStake(_poolStakingAddress, _staker); } _setLikelihood(_poolStakingAddress); // Remember that the `_staker` staked into `_poolStakingAddress` address[] storage stakerPools = _stakerPools[_staker]; uint256 index = _stakerPoolsIndexes[_staker][_poolStakingAddress]; if (index >= stakerPools.length || stakerPools[index] != _poolStakingAddress) { _stakerPoolsIndexes[_staker][_poolStakingAddress] = stakerPools.length; stakerPools.push(_poolStakingAddress); } emit PlacedStake(_poolStakingAddress, _staker, stakingEpoch, _amount); } /// @dev The internal function used by the `withdraw` and `moveStake` functions. /// See the `withdraw` public function for more details. /// @param _poolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn. /// @param _staker The staker's address. /// @param _amount The amount of the tokens/coins to be withdrawn. function _withdraw( address _poolStakingAddress, address _staker, uint256 _amount ) internal gasPriceIsValid onlyInitialized { require(_poolStakingAddress != address(0)); require(_amount != 0); // How much can `_staker` withdraw from `_poolStakingAddress` at the moment? require(_amount <= maxWithdrawAllowed(_poolStakingAddress, _staker)); uint256 newStakeAmount = stakeAmount[_poolStakingAddress][_staker].sub(_amount); // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and min allowed stake uint256 minAllowedStake; if (_poolStakingAddress == _staker) { require(newStakeAmount >= _stakeInitial[_staker]); // initial validator cannot withdraw their initial stake minAllowedStake = candidateMinStake; } else { minAllowedStake = delegatorMinStake; } require(newStakeAmount == 0 || newStakeAmount >= minAllowedStake); stakeAmount[_poolStakingAddress][_staker] = newStakeAmount; uint256 amountByEpoch = stakeAmountByCurrentEpoch(_poolStakingAddress, _staker); _stakeAmountByEpoch[_poolStakingAddress][_staker][stakingEpoch] = amountByEpoch >= _amount ? amountByEpoch - _amount : 0; stakeAmountTotal[_poolStakingAddress] = stakeAmountTotal[_poolStakingAddress].sub(_amount); if (newStakeAmount == 0) { _withdrawCheckPool(_poolStakingAddress, _staker); } if (_staker != _poolStakingAddress) { _snapshotDelegatorStake(_poolStakingAddress, _staker); } _setLikelihood(_poolStakingAddress); } /// @dev The internal function used by the `_withdraw` and `claimOrderedWithdraw` functions. /// Contains a common logic for these functions. /// @param _poolStakingAddress The staking address of the pool from which the tokens/coins are withdrawn. /// @param _staker The staker's address. function _withdrawCheckPool(address _poolStakingAddress, address _staker) internal { if (_staker == _poolStakingAddress) { address unremovableStakingAddress = validatorSetContract.unremovableValidator(); if (_poolStakingAddress != unremovableStakingAddress) { address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); if (validatorSetContract.isValidator(miningAddress)) { _addPoolToBeRemoved(_poolStakingAddress); } else { _removePool(_poolStakingAddress); } } } else { _removePoolDelegator(_poolStakingAddress, _staker); if (_isPoolEmpty(_poolStakingAddress)) { _removePoolInactive(_poolStakingAddress); } } } /// @dev Returns the current block number. Needed mostly for unit tests. function _getCurrentBlockNumber() internal view returns(uint256) { return block.number; } /// @dev The internal function used by the `claimReward` function and `getRewardAmount` getter. /// Finds the stake amount made by a specified delegator into a specified pool before a specified /// staking epoch. function _getDelegatorStake( uint256 _epoch, uint256 _firstEpoch, uint256 _prevDelegatorStake, address _poolStakingAddress, address _delegator ) internal view returns(uint256 delegatorStake) { while (true) { delegatorStake = delegatorStakeSnapshot[_poolStakingAddress][_delegator][_epoch]; if (delegatorStake != 0) { delegatorStake = (delegatorStake == uint256(-1)) ? 0 : delegatorStake; break; } else if (_epoch == _firstEpoch) { delegatorStake = _prevDelegatorStake; break; } _epoch--; } } /// @dev Returns the max number of candidates (including validators). See the MAX_CANDIDATES constant. /// Needed mostly for unit tests. function _getMaxCandidates() internal pure returns(uint256) { return MAX_CANDIDATES; } /// @dev Returns a boolean flag indicating whether the specified pool is fully empty /// (all stakes are withdrawn including ordered withdrawals). /// @param _poolStakingAddress The staking address of the pool function _isPoolEmpty(address _poolStakingAddress) internal view returns(bool) { return stakeAmountTotal[_poolStakingAddress] == 0 && orderedWithdrawAmountTotal[_poolStakingAddress] == 0; } /// @dev Determines if the specified pool is in the `poolsToBeElected` array. See the `getPoolsToBeElected` getter. /// Used by the `_setLikelihood` internal function. /// @param _stakingAddress The staking address of the pool. /// @return `bool toBeElected` - The boolean flag indicating whether the `_stakingAddress` is in the /// `poolsToBeElected` array. /// `uint256 index` - The position of the item in the `poolsToBeElected` array if `toBeElected` is `true`. function _isPoolToBeElected(address _stakingAddress) internal view returns(bool toBeElected, uint256 index) { index = poolToBeElectedIndex[_stakingAddress]; if (_poolsToBeElected.length > index && _poolsToBeElected[index] == _stakingAddress) { return (true, index); } return (false, 0); } /// @dev Returns `true` if withdrawal from the pool of the specified candidate/validator is allowed at the moment. /// Used by all withdrawal functions. /// @param _miningAddress The mining address of the validator's pool. /// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator. function _isWithdrawAllowed(address _miningAddress, bool _isDelegator) internal view returns(bool) { if (_isDelegator) { if (validatorSetContract.areDelegatorsBanned(_miningAddress)) { // The delegator cannot withdraw from the banned validator pool until the ban is expired return false; } } else { if (validatorSetContract.isValidatorBanned(_miningAddress)) { // The banned validator cannot withdraw from their pool until the ban is expired return false; } } if (!areStakeAndWithdrawAllowed()) { return false; } return true; } /// @dev Returns the balance of this contract in staking tokens or coins /// depending on implementation. function _thisBalance() internal view returns(uint256); }
@dev Returns the array of stake amounts for each corresponding address in the `poolsToBeElected` array (see the `getPoolsToBeElected` getter) and a sum of these amounts. Used by the `ValidatorSetAuRa.newValidatorSet` function when randomly selecting new validators at the last block of a staking epoch. An array value is updated every time any staked amount is changed in this pool (see the `_setLikelihood` internal function). @return `uint256[] likelihoods` - The array of the coefficients. The array length is always equal to the length of the `poolsToBeElected` array. `uint256 sum` - The total sum of the amounts.
function getPoolsLikelihood() external view returns(uint256[] memory likelihoods, uint256 sum) { return (_poolsLikelihood, _poolsLikelihoodSum); }
978,148
[ 1, 1356, 326, 526, 434, 384, 911, 30980, 364, 1517, 4656, 1758, 316, 326, 1375, 6011, 11634, 1919, 17817, 329, 68, 526, 261, 5946, 326, 1375, 588, 2864, 11634, 1919, 17817, 329, 68, 7060, 13, 471, 279, 2142, 434, 4259, 30980, 18, 10286, 635, 326, 1375, 5126, 694, 37, 89, 12649, 18, 2704, 5126, 694, 68, 445, 1347, 20153, 24674, 394, 11632, 622, 326, 1142, 1203, 434, 279, 384, 6159, 7632, 18, 1922, 526, 460, 353, 3526, 3614, 813, 1281, 384, 9477, 3844, 353, 3550, 316, 333, 2845, 261, 5946, 326, 1375, 67, 542, 30248, 11318, 68, 2713, 445, 2934, 327, 1375, 11890, 5034, 8526, 18067, 87, 68, 300, 1021, 526, 434, 326, 14229, 18, 1021, 526, 769, 353, 3712, 3959, 358, 326, 769, 434, 326, 1375, 6011, 11634, 1919, 17817, 329, 68, 526, 18, 1375, 11890, 5034, 2142, 68, 300, 1021, 2078, 2142, 434, 326, 30980, 18, 2, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
[ 1, 565, 445, 1689, 8192, 30248, 11318, 1435, 3903, 1476, 1135, 12, 11890, 5034, 8526, 3778, 18067, 87, 16, 2254, 5034, 2142, 13, 288, 203, 3639, 327, 261, 67, 27663, 30248, 11318, 16, 389, 27663, 30248, 11318, 3495, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/80001/0xD2c21633a243169A6b6E2688d9A9fC1A10809cD5/sources/_7i7o/tokengate/src/ERC721TGNT.sol
* @dev Burns or destroys an NFT with `_tokenId` Throws {NonExistentToken} when `_tokenId`is invalid (not minted) Emits a {Transfer} event, with msg.sender as `_from`, zero address as `_to`, and a zero padded uint256 as `_tokenId` @param _tokenId Id of the token to be burned/
function _burn(uint256 _tokenId) internal virtual { if (!_exists(_tokenId)) revert NonExistentTokenId(_tokenId); delete _owners[address(uint160(_tokenId))]; emit Transfer(msg.sender, address(0x0), uint256(uint160(_tokenId))); }
9,513,529
[ 1, 38, 321, 87, 578, 1570, 28599, 392, 423, 4464, 598, 1375, 67, 2316, 548, 68, 4202, 22435, 288, 3989, 4786, 319, 1345, 97, 1347, 1375, 67, 2316, 548, 68, 291, 2057, 261, 902, 312, 474, 329, 13, 4202, 7377, 1282, 279, 288, 5912, 97, 871, 16, 598, 1234, 18, 15330, 487, 1375, 67, 2080, 9191, 3634, 1758, 4202, 487, 1375, 67, 869, 9191, 471, 279, 3634, 14426, 2254, 5034, 487, 1375, 67, 2316, 548, 68, 282, 389, 2316, 548, 3124, 434, 326, 1147, 358, 506, 18305, 329, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 321, 12, 11890, 5034, 389, 2316, 548, 13, 2713, 5024, 288, 203, 3639, 309, 16051, 67, 1808, 24899, 2316, 548, 3719, 15226, 3858, 4786, 319, 1345, 548, 24899, 2316, 548, 1769, 203, 203, 3639, 1430, 389, 995, 414, 63, 2867, 12, 11890, 16874, 24899, 2316, 548, 3719, 15533, 203, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 1758, 12, 20, 92, 20, 3631, 2254, 5034, 12, 11890, 16874, 24899, 2316, 548, 3719, 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 ]
/* The MIT License (MIT) Copyright 2017 - 2018, Alchemy Limited, LLC and Smart Contract Solutions. 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. */ pragma solidity ^0.4.21; /** * Reference: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol * * @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) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* end SafeMath library */ /// @title Math operation when both numbers has decimal places. /// @notice Use this contract when both numbers has 18 decimal places. contract FixedMath { using SafeMath for uint; uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; uint constant internal DECIMALS = 18; uint constant internal DECMULT = 10 ** DECIMALS; /// @notice Multiplication. function fMul(uint x, uint y) internal pure returns (uint) { return (x.mul(y)).div(DECMULT); } /// @notice Division. function fDiv(uint numerator, uint divisor) internal pure returns (uint) { return (numerator.mul(DECMULT)).div(divisor); } /// @notice Square root. /// @dev Reference: https://stackoverflow.com/questions/3766020/binary-search-to-compute-square-root-java function fSqrt(uint n) internal pure returns (uint) { if (n == 0) { return 0; } uint z = n * n; require(z / n == n); uint high = fAdd(n, DECMULT); uint low = 0; while (fSub(high, low) > 1) { uint mid = fAdd(low, high) / 2; if (fSqr(mid) <= n) { low = mid; } else { high = mid; } } return low; } /// @notice Square. function fSqr(uint n) internal pure returns (uint) { return fMul(n, n); } /// @notice Add. function fAdd(uint x, uint y) internal pure returns (uint) { return x.add(y); } /// @notice Sub. function fSub(uint x, uint y) internal pure returns (uint) { return x.sub(y); } } /// @title A formula contract for converter contract Formula is FixedMath { /// @notice Trade in reserve(ETH/MET) and mint new smart tokens /// @param smartTokenSupply Total supply of smart token /// @param reserveTokensSent Amount of token sent by caller /// @param reserveTokenBalance Balance of reserve token in the contract /// @return Smart token minted function returnForMint(uint smartTokenSupply, uint reserveTokensSent, uint reserveTokenBalance) internal pure returns (uint) { uint s = smartTokenSupply; uint e = reserveTokensSent; uint r = reserveTokenBalance; /// smartToken for mint(T) = S * (sqrt(1 + E/R) - 1) /// DECMULT is same as 1 for values with 18 decimal places return ((fMul(s, (fSub(fSqrt(fAdd(DECMULT, fDiv(e, r))), DECMULT)))).mul(METDECMULT)).div(DECMULT); } /// @notice Redeem smart tokens, get back reserve(ETH/MET) token /// @param smartTokenSupply Total supply of smart token /// @param smartTokensSent Smart token sent /// @param reserveTokenBalance Balance of reserve token in the contract /// @return Reserve token redeemed function returnForRedemption(uint smartTokenSupply, uint smartTokensSent, uint reserveTokenBalance) internal pure returns (uint) { uint s = smartTokenSupply; uint t = smartTokensSent; uint r = reserveTokenBalance; /// reserveToken (E) = R * (1 - (1 - T/S)**2) /// DECMULT is same as 1 for values with 18 decimal places return ((fMul(r, (fSub(DECMULT, fSqr(fSub(DECMULT, fDiv(t, s))))))).mul(METDECMULT)).div(DECMULT); } } /// @title Pricer contract to calculate descending price during auction. contract Pricer { using SafeMath for uint; uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; uint public minimumPrice = 33*10**11; uint public minimumPriceInDailyAuction = 1; uint public tentimes; uint public hundredtimes; uint public thousandtimes; uint constant public MULTIPLIER = 1984320568*10**5; /// @notice Pricer constructor, calculate 10, 100 and 1000 times of 0.99. function initPricer() public { uint x = METDECMULT; uint i; /// Calculate 10 times of 0.99 for (i = 0; i < 10; i++) { x = x.mul(99).div(100); } tentimes = x; x = METDECMULT; /// Calculate 100 times of 0.99 using tentimes calculated above. /// tentimes has 18 decimal places and due to this METDECMLT is /// used as divisor. for (i = 0; i < 10; i++) { x = x.mul(tentimes).div(METDECMULT); } hundredtimes = x; x = METDECMULT; /// Calculate 1000 times of 0.99 using hundredtimes calculated above. /// hundredtimes has 18 decimal places and due to this METDECMULT is /// used as divisor. for (i = 0; i < 10; i++) { x = x.mul(hundredtimes).div(METDECMULT); } thousandtimes = x; } /// @notice Price of MET at nth minute out during operational auction /// @param initialPrice The starting price ie last purchase price /// @param _n The number of minutes passed since last purchase /// @return The resulting price function priceAt(uint initialPrice, uint _n) public view returns (uint price) { uint mult = METDECMULT; uint i; uint n = _n; /// If quotient of n/1000 is greater than 0 then calculate multiplier by /// multiplying thousandtimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/1000. if (n / 1000 > 0) { for (i = 0; i < n / 1000; i++) { mult = mult.mul(thousandtimes).div(METDECMULT); } n = n % 1000; } /// If quotient of n/100 is greater than 0 then calculate multiplier by /// multiplying hundredtimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/100. if (n / 100 > 0) { for (i = 0; i < n / 100; i++) { mult = mult.mul(hundredtimes).div(METDECMULT); } n = n % 100; } /// If quotient of n/10 is greater than 0 then calculate multiplier by /// multiplying tentimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/10. if (n / 10 > 0) { for (i = 0; i < n / 10; i++) { mult = mult.mul(tentimes).div(METDECMULT); } n = n % 10; } /// Calculate multiplier by multiplying 0.99 and mult, repeat it n times. for (i = 0; i < n; i++) { mult = mult.mul(99).div(100); } /// price is calculated as initialPrice multiplied by 0.99 and that too _n times. /// Here mult is METDECMULT multiplied by 0.99 and that too _n times. price = initialPrice.mul(mult).div(METDECMULT); if (price < minimumPriceInDailyAuction) { price = minimumPriceInDailyAuction; } } /// @notice Price of MET at nth minute during initial auction. /// @param lastPurchasePrice The price of MET in last transaction /// @param numTicks The number of minutes passed since last purchase /// @return The resulting price function priceAtInitialAuction(uint lastPurchasePrice, uint numTicks) public view returns (uint price) { /// Price will decrease linearly every minute by the factor of MULTIPLIER. /// If lastPurchasePrice is greater than decrease in price then calculated the price. /// Return minimumPrice, if calculated price is less than minimumPrice. /// If decrease in price is more than lastPurchasePrice then simply return the minimumPrice. if (lastPurchasePrice > MULTIPLIER.mul(numTicks)) { price = lastPurchasePrice.sub(MULTIPLIER.mul(numTicks)); } if (price < minimumPrice) { price = minimumPrice; } } } /// @dev Reference: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md /// @notice ERC20 standard interface interface ERC20 { function totalSupply() public constant returns (uint256); function balanceOf(address _owner) public constant returns (uint256); function allowance(address _owner, address _spender) public constant returns (uint256); event Transfer(address indexed _from, address indexed _to, uint256 _value); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function approve(address _spender, uint256 _value) public returns (bool); } /// @title Ownable contract Ownable { address public owner; event OwnershipChanged(address indexed prevOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @param _newOwner /// @return true/false function changeOwnership(address _newOwner) public onlyOwner returns (bool) { require(_newOwner != address(0)); require(_newOwner != owner); emit OwnershipChanged(owner, _newOwner); owner = _newOwner; return true; } } /// @title Owned contract Owned is Ownable { address public newOwner; /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @param _newOwner /// @return true/false function changeOwnership(address _newOwner) public onlyOwner returns (bool) { require(_newOwner != owner); newOwner = _newOwner; return true; } /// @notice Allows the new owner to accept ownership of the contract. /// @return true/false function acceptOwnership() public returns (bool) { require(msg.sender == newOwner); emit OwnershipChanged(owner, newOwner); owner = newOwner; return true; } } /// @title Mintable contract to allow minting and destroy. contract Mintable is Owned { using SafeMath for uint256; event Mint(address indexed _to, uint _value); event Destroy(address indexed _from, uint _value); event Transfer(address indexed _from, address indexed _to, uint256 _value); uint256 internal _totalSupply; mapping(address => uint256) internal _balanceOf; address public autonomousConverter; address public minter; ITokenPorter public tokenPorter; /// @notice init reference of other contract and initial supply /// @param _autonomousConverter /// @param _minter /// @param _initialSupply /// @param _decmult Decimal places function initMintable(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { require(autonomousConverter == 0x0 && _autonomousConverter != 0x0); require(minter == 0x0 && _minter != 0x0); autonomousConverter = _autonomousConverter; minter = _minter; _totalSupply = _initialSupply.mul(_decmult); _balanceOf[_autonomousConverter] = _totalSupply; } function totalSupply() public constant returns (uint256) { return _totalSupply; } function balanceOf(address _owner) public constant returns (uint256) { return _balanceOf[_owner]; } /// @notice set address of token porter /// @param _tokenPorter address of token porter function setTokenPorter(address _tokenPorter) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); tokenPorter = ITokenPorter(_tokenPorter); return true; } /// @notice allow minter and tokenPorter to mint token and assign to address /// @param _to /// @param _value Amount to be minted function mint(address _to, uint _value) public returns (bool) { require(msg.sender == minter || msg.sender == address(tokenPorter)); _balanceOf[_to] = _balanceOf[_to].add(_value); _totalSupply = _totalSupply.add(_value); emit Mint(_to, _value); emit Transfer(0x0, _to, _value); return true; } /// @notice allow autonomousConverter and tokenPorter to mint token and assign to address /// @param _from /// @param _value Amount to be destroyed function destroy(address _from, uint _value) public returns (bool) { require(msg.sender == autonomousConverter || msg.sender == address(tokenPorter)); _balanceOf[_from] = _balanceOf[_from].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Destroy(_from, _value); emit Transfer(_from, 0x0, _value); return true; } } /// @title Token contract contract Token is ERC20, Mintable { mapping(address => mapping(address => uint256)) internal _allowance; function initToken(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { initMintable(_autonomousConverter, _minter, _initialSupply, _decmult); } /// @notice Provide allowance information function allowance(address _owner, address _spender) public constant returns (uint256) { return _allowance[_owner][_spender]; } /// @notice Transfer tokens from sender to the provided address. /// @param _to Receiver of the tokens /// @param _value Amount of token /// @return true/false function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_to != minter); require(_to != address(this)); require(_to != autonomousConverter); Proceeds proceeds = Auctions(minter).proceeds(); require((_to != address(proceeds))); _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /// @notice Transfer tokens based on allowance. /// msg.sender must have allowance for spending the tokens from owner ie _from /// @param _from Owner of the tokens /// @param _to Receiver of the tokens /// @param _value Amount of tokens to transfer /// @return true/false function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_to != minter && _from != minter); require(_to != address(this) && _from != address(this)); Proceeds proceeds = Auctions(minter).proceeds(); require(_to != address(proceeds) && _from != address(proceeds)); //AC can accept MET via this function, needed for MetToEth conversion require(_from != autonomousConverter); require(_allowance[_from][msg.sender] >= _value); _balanceOf[_from] = _balanceOf[_from].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /// @notice Approve spender to spend the tokens ie approve allowance /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != address(this)); _allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /// @notice Transfer the tokens from sender to all the address provided in the array. /// @dev Left 160 bits are the recipient address and the right 96 bits are the token amount. /// @param bits array of uint /// @return true/false function multiTransfer(uint[] bits) public returns (bool) { for (uint i = 0; i < bits.length; i++) { address a = address(bits[i] >> 96); uint amount = bits[i] & ((1 << 96) - 1); if (!transfer(a, amount)) revert(); } return true; } /// @notice Increase allowance of spender /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approveMore(address _spender, uint256 _value) public returns (bool) { uint previous = _allowance[msg.sender][_spender]; uint newAllowance = previous.add(_value); _allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } /// @notice Decrease allowance of spender /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approveLess(address _spender, uint256 _value) public returns (bool) { uint previous = _allowance[msg.sender][_spender]; uint newAllowance = previous.sub(_value); _allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } } /// @title Smart tokens are an intermediate token generated during conversion of MET-ETH contract SmartToken is Mintable { uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; function initSmartToken(address _autonomousConverter, address _minter, uint _initialSupply) public onlyOwner { initMintable(_autonomousConverter, _minter, _initialSupply, METDECMULT); } } /// @title ERC20 token. Metronome token contract METToken is Token { string public constant name = "Metronome"; string public constant symbol = "MET"; uint8 public constant decimals = 18; bool public transferAllowed; function initMETToken(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { initToken(_autonomousConverter, _minter, _initialSupply, _decmult); } /// @notice Transferable modifier to allow transfer only after initial auction ended. modifier transferable() { require(transferAllowed); _; } function enableMETTransfers() public returns (bool) { require(!transferAllowed && Auctions(minter).isInitialAuctionEnded()); transferAllowed = true; return true; } /// @notice Transfer tokens from caller to another address /// @param _to address The address which you want to transfer to /// @param _value uint256 the amout of tokens to be transfered function transfer(address _to, uint256 _value) public transferable returns (bool) { return super.transfer(_to, _value); } /// @notice Transfer tokens from one address to another /// @param _from address The address from which you want to transfer /// @param _to address The address which you want to transfer to /// @param _value uint256 the amout of tokens to be transfered function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) { return super.transferFrom(_from, _to, _value); } /// @notice Transfer the token from sender to all the addresses provided in array. /// @dev Left 160 bits are the recipient address and the right 96 bits are the token amount. /// @param bits array of uint /// @return true/false function multiTransfer(uint[] bits) public transferable returns (bool) { return super.multiTransfer(bits); } mapping (address => bytes32) public roots; function setRoot(bytes32 data) public { roots[msg.sender] = data; } function getRoot(address addr) public view returns (bytes32) { return roots[addr]; } function rootsMatch(address a, address b) public view returns (bool) { return roots[a] == roots[b]; } /// @notice import MET tokens from another chain to this chain. /// @param _destinationChain destination chain name /// @param _addresses _addresses[0] is destMetronomeAddr and _addresses[1] is recipientAddr /// @param _extraData extra information for import /// @param _burnHashes _burnHashes[0] is previous burnHash, _burnHashes[1] is current burnHash /// @param _supplyOnAllChains MET supply on all supported chains /// @param _importData _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee /// _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, _importData[5] is _dailyMintable /// _importData[6] is _burnSequence, _importData[7] is _dailyAuctionStartTime /// @param _proof proof /// @return true/false function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool) { require(address(tokenPorter) != 0x0); return tokenPorter.importMET(_originChain, _destinationChain, _addresses, _extraData, _burnHashes, _supplyOnAllChains, _importData, _proof); } /// @notice export MET tokens from this chain to another chain. /// @param _destChain destination chain address /// @param _destMetronomeAddr address of Metronome contract on the destination chain /// where this MET will be imported. /// @param _destRecipAddr address of account on destination chain /// @param _amount amount /// @param _extraData extra information for future expansion /// @return true/false function export(bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool) { require(address(tokenPorter) != 0x0); return tokenPorter.export(msg.sender, _destChain, _destMetronomeAddr, _destRecipAddr, _amount, _fee, _extraData); } struct Sub { uint startTime; uint payPerWeek; uint lastWithdrawTime; } event LogSubscription(address indexed subscriber, address indexed subscribesTo); event LogCancelSubscription(address indexed subscriber, address indexed subscribesTo); mapping (address => mapping (address => Sub)) public subs; /// @notice subscribe for a weekly recurring payment /// @param _startTime Subscription start time. /// @param _payPerWeek weekly payment /// @param _recipient address of beneficiary /// @return true/false function subscribe(uint _startTime, uint _payPerWeek, address _recipient) public returns (bool) { require(_startTime >= block.timestamp); require(_payPerWeek != 0); require(_recipient != 0); subs[msg.sender][_recipient] = Sub(_startTime, _payPerWeek, _startTime); emit LogSubscription(msg.sender, _recipient); return true; } /// @notice cancel a subcription. /// @param _recipient address of beneficiary /// @return true/false function cancelSubscription(address _recipient) public returns (bool) { require(subs[msg.sender][_recipient].startTime != 0); require(subs[msg.sender][_recipient].payPerWeek != 0); subs[msg.sender][_recipient].startTime = 0; subs[msg.sender][_recipient].payPerWeek = 0; subs[msg.sender][_recipient].lastWithdrawTime = 0; emit LogCancelSubscription(msg.sender, _recipient); return true; } /// @notice get subcription details /// @param _owner /// @param _recipient /// @return startTime, payPerWeek, lastWithdrawTime function getSubscription(address _owner, address _recipient) public constant returns (uint startTime, uint payPerWeek, uint lastWithdrawTime) { Sub storage sub = subs[_owner][_recipient]; return ( sub.startTime, sub.payPerWeek, sub.lastWithdrawTime ); } /// @notice caller can withdraw the token from subscribers. /// @param _owner subcriber /// @return true/false function subWithdraw(address _owner) public transferable returns (bool) { require(subWithdrawFor(_owner, msg.sender)); return true; } /// @notice Allow callers to withdraw token in one go from all of its subscribers /// @param _owners array of address of subscribers /// @return number of successful transfer done function multiSubWithdraw(address[] _owners) public returns (uint) { uint n = 0; for (uint i=0; i < _owners.length; i++) { if (subWithdrawFor(_owners[i], msg.sender)) { n++; } } return n; } /// @notice Trigger MET token transfers for all pairs of subscribers and beneficiaries /// @dev address at i index in owners and recipients array is subcriber-beneficiary pair. /// @param _owners /// @param _recipients /// @return number of successful transfer done function multiSubWithdrawFor(address[] _owners, address[] _recipients) public returns (uint) { // owners and recipients need 1-to-1 mapping, must be same length require(_owners.length == _recipients.length); uint n = 0; for (uint i = 0; i < _owners.length; i++) { if (subWithdrawFor(_owners[i], _recipients[i])) { n++; } } return n; } function subWithdrawFor(address _from, address _to) internal returns (bool) { Sub storage sub = subs[_from][_to]; if (sub.startTime > 0 && sub.startTime < block.timestamp && sub.payPerWeek > 0) { uint weekElapsed = (now.sub(sub.lastWithdrawTime)).div(7 days); uint amount = weekElapsed.mul(sub.payPerWeek); if (weekElapsed > 0 && _balanceOf[_from] >= amount) { subs[_from][_to].lastWithdrawTime = block.timestamp; _balanceOf[_from] = _balanceOf[_from].sub(amount); _balanceOf[_to] = _balanceOf[_to].add(amount); emit Transfer(_from, _to, amount); return true; } } return false; } } /// @title Autonomous Converter contract for MET <=> ETH exchange contract AutonomousConverter is Formula, Owned { SmartToken public smartToken; METToken public reserveToken; Auctions public auctions; enum WhichToken { Eth, Met } bool internal initialized = false; event LogFundsIn(address indexed from, uint value); event ConvertEthToMet(address indexed from, uint eth, uint met); event ConvertMetToEth(address indexed from, uint eth, uint met); function init(address _reserveToken, address _smartToken, address _auctions) public onlyOwner payable { require(!initialized); auctions = Auctions(_auctions); reserveToken = METToken(_reserveToken); smartToken = SmartToken(_smartToken); initialized = true; } function handleFund() public payable { require(msg.sender == address(auctions.proceeds())); emit LogFundsIn(msg.sender, msg.value); } function getMetBalance() public view returns (uint) { return balanceOf(WhichToken.Met); } function getEthBalance() public view returns (uint) { return balanceOf(WhichToken.Eth); } /// @notice return the expected MET for ETH /// @param _depositAmount ETH. /// @return expected MET value for ETH function getMetForEthResult(uint _depositAmount) public view returns (uint256) { return convertingReturn(WhichToken.Eth, _depositAmount); } /// @notice return the expected ETH for MET /// @param _depositAmount MET. /// @return expected ETH value for MET function getEthForMetResult(uint _depositAmount) public view returns (uint256) { return convertingReturn(WhichToken.Met, _depositAmount); } /// @notice send ETH and get MET /// @param _mintReturn execute conversion only if return is equal or more than _mintReturn /// @return returnedMet MET retured after conversion function convertEthToMet(uint _mintReturn) public payable returns (uint returnedMet) { returnedMet = convert(WhichToken.Eth, _mintReturn, msg.value); emit ConvertEthToMet(msg.sender, msg.value, returnedMet); } /// @notice send MET and get ETH /// @dev Caller will be required to approve the AutonomousConverter to initiate the transfer /// @param _amount MET amount /// @param _mintReturn execute conversion only if return is equal or more than _mintReturn /// @return returnedEth ETh returned after conversion function convertMetToEth(uint _amount, uint _mintReturn) public returns (uint returnedEth) { returnedEth = convert(WhichToken.Met, _mintReturn, _amount); emit ConvertMetToEth(msg.sender, returnedEth, _amount); } function balanceOf(WhichToken which) internal view returns (uint) { if (which == WhichToken.Eth) return address(this).balance; if (which == WhichToken.Met) return reserveToken.balanceOf(this); revert(); } function convertingReturn(WhichToken whichFrom, uint _depositAmount) internal view returns (uint256) { WhichToken to = WhichToken.Met; if (whichFrom == WhichToken.Met) { to = WhichToken.Eth; } uint reserveTokenBalanceFrom = balanceOf(whichFrom).add(_depositAmount); uint mintRet = returnForMint(smartToken.totalSupply(), _depositAmount, reserveTokenBalanceFrom); uint newSmartTokenSupply = smartToken.totalSupply().add(mintRet); uint reserveTokenBalanceTo = balanceOf(to); return returnForRedemption( newSmartTokenSupply, mintRet, reserveTokenBalanceTo); } function convert(WhichToken whichFrom, uint _minReturn, uint amnt) internal returns (uint) { WhichToken to = WhichToken.Met; if (whichFrom == WhichToken.Met) { to = WhichToken.Eth; require(reserveToken.transferFrom(msg.sender, this, amnt)); } uint mintRet = mint(whichFrom, amnt, 1); return redeem(to, mintRet, _minReturn); } function mint(WhichToken which, uint _depositAmount, uint _minReturn) internal returns (uint256 amount) { require(_minReturn > 0); amount = mintingReturn(which, _depositAmount); require(amount >= _minReturn); require(smartToken.mint(msg.sender, amount)); } function mintingReturn(WhichToken which, uint _depositAmount) internal view returns (uint256) { uint256 smartTokenSupply = smartToken.totalSupply(); uint256 reserveBalance = balanceOf(which); return returnForMint(smartTokenSupply, _depositAmount, reserveBalance); } function redeem(WhichToken which, uint _amount, uint _minReturn) internal returns (uint redeemable) { require(_amount <= smartToken.balanceOf(msg.sender)); require(_minReturn > 0); redeemable = redemptionReturn(which, _amount); require(redeemable >= _minReturn); uint256 reserveBalance = balanceOf(which); require(reserveBalance >= redeemable); uint256 tokenSupply = smartToken.totalSupply(); require(_amount < tokenSupply); smartToken.destroy(msg.sender, _amount); if (which == WhichToken.Eth) { msg.sender.transfer(redeemable); } else { require(reserveToken.transfer(msg.sender, redeemable)); } } function redemptionReturn(WhichToken which, uint smartTokensSent) internal view returns (uint256) { uint smartTokenSupply = smartToken.totalSupply(); uint reserveTokenBalance = balanceOf(which); return returnForRedemption( smartTokenSupply, smartTokensSent, reserveTokenBalance); } } /// @title Proceeds contract contract Proceeds is Owned { using SafeMath for uint256; AutonomousConverter public autonomousConverter; Auctions public auctions; event LogProceedsIn(address indexed from, uint value); event LogClosedAuction(address indexed from, uint value); uint latestAuctionClosed; function initProceeds(address _autonomousConverter, address _auctions) public onlyOwner { require(address(auctions) == 0x0 && _auctions != 0x0); require(address(autonomousConverter) == 0x0 && _autonomousConverter != 0x0); autonomousConverter = AutonomousConverter(_autonomousConverter); auctions = Auctions(_auctions); } function handleFund() public payable { require(msg.sender == address(auctions)); emit LogProceedsIn(msg.sender, msg.value); } /// @notice Forward 0.25% of total ETH balance of proceeds to AutonomousConverter contract function closeAuction() public { uint lastPurchaseTick = auctions.lastPurchaseTick(); uint currentAuction = auctions.currentAuction(); uint val = ((address(this).balance).mul(25)).div(10000); if (val > 0 && (currentAuction > auctions.whichAuction(lastPurchaseTick)) && (latestAuctionClosed < currentAuction)) { latestAuctionClosed = currentAuction; autonomousConverter.handleFund.value(val)(); emit LogClosedAuction(msg.sender, val); } } } /// @title Auction contract. Send ETH to the contract address and buy MET. contract Auctions is Pricer, Owned { using SafeMath for uint256; METToken public token; Proceeds public proceeds; address[] public founders; mapping(address => TokenLocker) public tokenLockers; uint internal constant DAY_IN_SECONDS = 86400; uint internal constant DAY_IN_MINUTES = 1440; uint public genesisTime; uint public lastPurchaseTick; uint public lastPurchasePrice; uint public constant INITIAL_GLOBAL_DAILY_SUPPLY = 2880 * METDECMULT; uint public INITIAL_FOUNDER_SUPPLY = 1999999 * METDECMULT; uint public INITIAL_AC_SUPPLY = 1 * METDECMULT; uint public totalMigratedOut = 0; uint public totalMigratedIn = 0; uint public timeScale = 1; uint public constant INITIAL_SUPPLY = 10000000 * METDECMULT; uint public mintable = INITIAL_SUPPLY; uint public initialAuctionDuration = 7 days; uint public initialAuctionEndTime; uint public dailyAuctionStartTime; uint public constant DAILY_PURCHASE_LIMIT = 1000 ether; mapping (address => uint) internal purchaseInTheAuction; mapping (address => uint) internal lastPurchaseAuction; bool public minted; bool public initialized; uint public globalSupplyAfterPercentageLogic = 52598080 * METDECMULT; uint public constant AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS = 14791; bytes8 public chain = "ETH"; event LogAuctionFundsIn(address indexed sender, uint amount, uint tokens, uint purchasePrice, uint refund); function Auctions() public { mintable = INITIAL_SUPPLY - 2000000 * METDECMULT; } /// @notice Payable function to buy MET in descending price auction function () public payable running { require(msg.value > 0); uint amountForPurchase = msg.value; uint excessAmount; if (currentAuction() > whichAuction(lastPurchaseTick)) { proceeds.closeAuction(); restartAuction(); } if (isInitialAuctionEnded()) { require(now >= dailyAuctionStartTime); if (lastPurchaseAuction[msg.sender] < currentAuction()) { if (amountForPurchase > DAILY_PURCHASE_LIMIT) { excessAmount = amountForPurchase.sub(DAILY_PURCHASE_LIMIT); amountForPurchase = DAILY_PURCHASE_LIMIT; } purchaseInTheAuction[msg.sender] = msg.value; lastPurchaseAuction[msg.sender] = currentAuction(); } else { require(purchaseInTheAuction[msg.sender] < DAILY_PURCHASE_LIMIT); if (purchaseInTheAuction[msg.sender].add(amountForPurchase) > DAILY_PURCHASE_LIMIT) { excessAmount = (purchaseInTheAuction[msg.sender].add(amountForPurchase)).sub(DAILY_PURCHASE_LIMIT); amountForPurchase = amountForPurchase.sub(excessAmount); } purchaseInTheAuction[msg.sender] = purchaseInTheAuction[msg.sender].add(msg.value); } } uint _currentTick = currentTick(); uint weiPerToken; uint tokens; uint refund; (weiPerToken, tokens, refund) = calcPurchase(amountForPurchase, _currentTick); require(tokens > 0); if (now < initialAuctionEndTime && (token.totalSupply()).add(tokens) >= INITIAL_SUPPLY) { initialAuctionEndTime = now; dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = _currentTick; lastPurchasePrice = weiPerToken; assert(tokens <= mintable); mintable = mintable.sub(tokens); assert(refund <= amountForPurchase); uint ethForProceeds = amountForPurchase.sub(refund); proceeds.handleFund.value(ethForProceeds)(); require(token.mint(msg.sender, tokens)); refund = refund.add(excessAmount); if (refund > 0) { if (purchaseInTheAuction[msg.sender] > 0) { purchaseInTheAuction[msg.sender] = purchaseInTheAuction[msg.sender].sub(refund); } msg.sender.transfer(refund); } emit LogAuctionFundsIn(msg.sender, ethForProceeds, tokens, lastPurchasePrice, refund); } modifier running() { require(isRunning()); _; } function isRunning() public constant returns (bool) { return (block.timestamp >= genesisTime && genesisTime > 0); } /// @notice current tick(minute) of the metronome clock /// @return tick count function currentTick() public view returns(uint) { return whichTick(block.timestamp); } /// @notice current auction /// @return auction count function currentAuction() public view returns(uint) { return whichAuction(currentTick()); } /// @notice tick count at the timestamp t. /// @param t timestamp /// @return tick count function whichTick(uint t) public view returns(uint) { if (genesisTime > t) { revert(); } return (t - genesisTime) * timeScale / 1 minutes; } /// @notice Auction count at given the timestamp t /// @param t timestamp /// @return Auction count function whichAuction(uint t) public view returns(uint) { if (whichTick(dailyAuctionStartTime) > t) { return 0; } else { return ((t - whichTick(dailyAuctionStartTime)) / DAY_IN_MINUTES) + 1; } } /// @notice one single function telling everything about Metronome Auction function heartbeat() public view returns ( bytes8 _chain, address auctionAddr, address convertAddr, address tokenAddr, uint minting, uint totalMET, uint proceedsBal, uint currTick, uint currAuction, uint nextAuctionGMT, uint genesisGMT, uint currentAuctionPrice, uint _dailyMintable, uint _lastPurchasePrice) { _chain = chain; convertAddr = proceeds.autonomousConverter(); tokenAddr = token; auctionAddr = this; totalMET = token.totalSupply(); proceedsBal = address(proceeds).balance; currTick = currentTick(); currAuction = currentAuction(); if (currAuction == 0) { nextAuctionGMT = dailyAuctionStartTime; } else { nextAuctionGMT = (currAuction * DAY_IN_SECONDS) / timeScale + dailyAuctionStartTime; } genesisGMT = genesisTime; currentAuctionPrice = currentPrice(); _dailyMintable = dailyMintable(); minting = currentMintable(); _lastPurchasePrice = lastPurchasePrice; } /// @notice Skip Initialization and minting if we're not the OG Metronome /// @param _token MET token contract address /// @param _proceeds Address of Proceeds contract /// @param _genesisTime The block.timestamp when first auction started on OG chain /// @param _minimumPrice Nobody can buy tokens for less than this price /// @param _startingPrice Start price of MET when first auction starts /// @param _timeScale time scale factor for auction. will be always 1 in live environment /// @param _chain chain where this contract is being deployed /// @param _initialAuctionEndTime Initial Auction end time in ETH chain. function skipInitBecauseIAmNotOg(address _token, address _proceeds, uint _genesisTime, uint _minimumPrice, uint _startingPrice, uint _timeScale, bytes8 _chain, uint _initialAuctionEndTime) public onlyOwner returns (bool) { require(!minted); require(!initialized); require(_timeScale != 0); require(address(token) == 0x0 && _token != 0x0); require(address(proceeds) == 0x0 && _proceeds != 0x0); initPricer(); // minting substitute section token = METToken(_token); proceeds = Proceeds(_proceeds); INITIAL_FOUNDER_SUPPLY = 0; INITIAL_AC_SUPPLY = 0; mintable = 0; // // initial auction substitute section genesisTime = _genesisTime; initialAuctionEndTime = _initialAuctionEndTime; // if initialAuctionEndTime is midnight, then daily auction will start immediately // after initial auction. if (initialAuctionEndTime == (initialAuctionEndTime / 1 days) * 1 days) { dailyAuctionStartTime = initialAuctionEndTime; } else { dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = 0; if (_minimumPrice > 0) { minimumPrice = _minimumPrice; } timeScale = _timeScale; if (_startingPrice > 0) { lastPurchasePrice = _startingPrice * 1 ether; } else { lastPurchasePrice = 2 ether; } chain = _chain; minted = true; initialized = true; return true; } /// @notice Initialize Auctions parameters /// @param _startTime The block.timestamp when first auction starts /// @param _minimumPrice Nobody can buy tokens for less than this price /// @param _startingPrice Start price of MET when first auction starts /// @param _timeScale time scale factor for auction. will be always 1 in live environment function initAuctions(uint _startTime, uint _minimumPrice, uint _startingPrice, uint _timeScale) public onlyOwner returns (bool) { require(minted); require(!initialized); require(_timeScale != 0); initPricer(); if (_startTime > 0) { genesisTime = (_startTime / (1 minutes)) * (1 minutes) + 60; } else { genesisTime = block.timestamp + 60 - (block.timestamp % 60); } initialAuctionEndTime = genesisTime + initialAuctionDuration; // if initialAuctionEndTime is midnight, then daily auction will start immediately // after initial auction. if (initialAuctionEndTime == (initialAuctionEndTime / 1 days) * 1 days) { dailyAuctionStartTime = initialAuctionEndTime; } else { dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = 0; if (_minimumPrice > 0) { minimumPrice = _minimumPrice; } timeScale = _timeScale; if (_startingPrice > 0) { lastPurchasePrice = _startingPrice * 1 ether; } else { lastPurchasePrice = 2 ether; } for (uint i = 0; i < founders.length; i++) { TokenLocker tokenLocker = tokenLockers[founders[i]]; tokenLocker.lockTokenLocker(); } initialized = true; return true; } function createTokenLocker(address _founder, address _token) public onlyOwner { require(_token != 0x0); require(_founder != 0x0); founders.push(_founder); TokenLocker tokenLocker = new TokenLocker(address(this), _token); tokenLockers[_founder] = tokenLocker; tokenLocker.changeOwnership(_founder); } /// @notice Mint initial supply for founder and move to token locker /// @param _founders Left 160 bits are the founder address and the right 96 bits are the token amount. /// @param _token MET token contract address /// @param _proceeds Address of Proceeds contract function mintInitialSupply(uint[] _founders, address _token, address _proceeds, address _autonomousConverter) public onlyOwner returns (bool) { require(!minted); require(_founders.length != 0); require(address(token) == 0x0 && _token != 0x0); require(address(proceeds) == 0x0 && _proceeds != 0x0); require(_autonomousConverter != 0x0); token = METToken(_token); proceeds = Proceeds(_proceeds); // _founders will be minted into individual token lockers uint foundersTotal; for (uint i = 0; i < _founders.length; i++) { address addr = address(_founders[i] >> 96); require(addr != 0x0); uint amount = _founders[i] & ((1 << 96) - 1); require(amount > 0); TokenLocker tokenLocker = tokenLockers[addr]; require(token.mint(address(tokenLocker), amount)); tokenLocker.deposit(addr, amount); foundersTotal = foundersTotal.add(amount); } // reconcile minted total for founders require(foundersTotal == INITIAL_FOUNDER_SUPPLY); // mint a small amount to the AC require(token.mint(_autonomousConverter, INITIAL_AC_SUPPLY)); minted = true; return true; } /// @notice Suspend auction if not started yet function stopEverything() public onlyOwner { if (genesisTime < block.timestamp) { revert(); } genesisTime = genesisTime + 1000 years; initialAuctionEndTime = genesisTime; dailyAuctionStartTime = genesisTime; } /// @notice Return information about initial auction status. function isInitialAuctionEnded() public view returns (bool) { return (initialAuctionEndTime != 0 && (now >= initialAuctionEndTime || token.totalSupply() >= INITIAL_SUPPLY)); } /// @notice Global MET supply function globalMetSupply() public view returns (uint) { uint currAuc = currentAuction(); if (currAuc > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { return globalSupplyAfterPercentageLogic; } else { return INITIAL_SUPPLY.add(INITIAL_GLOBAL_DAILY_SUPPLY.mul(currAuc)); } } /// @notice Global MET daily supply. Daily supply is greater of 1) 2880 2)2% of then outstanding supply per year. /// @dev 2% logic will kicks in at 14792th auction. function globalDailySupply() public view returns (uint) { uint dailySupply = INITIAL_GLOBAL_DAILY_SUPPLY; uint thisAuction = currentAuction(); if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { uint lastAuctionPurchase = whichAuction(lastPurchaseTick); uint recentAuction = AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS + 1; if (lastAuctionPurchase > recentAuction) { recentAuction = lastAuctionPurchase; } uint totalAuctions = thisAuction - recentAuction; if (totalAuctions > 1) { // derived formula to find close to accurate daily supply when some auction missed. uint factor = 36525 + ((totalAuctions - 1) * 2); dailySupply = (globalSupplyAfterPercentageLogic.mul(2).mul(factor)).div(36525 ** 2); } else { dailySupply = globalSupplyAfterPercentageLogic.mul(2).div(36525); } if (dailySupply < INITIAL_GLOBAL_DAILY_SUPPLY) { dailySupply = INITIAL_GLOBAL_DAILY_SUPPLY; } } return dailySupply; } /// @notice Current price of MET in current auction /// @return weiPerToken function currentPrice() public constant returns (uint weiPerToken) { weiPerToken = calcPriceAt(currentTick()); } /// @notice Daily mintable MET in current auction function dailyMintable() public constant returns (uint) { return nextAuctionSupply(0); } /// @notice Total tokens on this chain function tokensOnThisChain() public view returns (uint) { uint totalSupply = token.totalSupply(); uint currMintable = currentMintable(); return totalSupply.add(currMintable); } /// @notice Current mintable MET in auction function currentMintable() public view returns (uint) { uint currMintable = mintable; uint currAuction = currentAuction(); uint totalAuctions = currAuction.sub(whichAuction(lastPurchaseTick)); if (totalAuctions > 0) { currMintable = mintable.add(nextAuctionSupply(totalAuctions)); } return currMintable; } /// @notice prepare auction when first import is done on a non ETH chain function prepareAuctionForNonOGChain() public { require(msg.sender == address(token.tokenPorter()) || msg.sender == address(token)); require(token.totalSupply() == 0); require(chain != "ETH"); lastPurchaseTick = currentTick(); } /// @notice Find out what the results would be of a prospective purchase /// @param _wei Amount of wei the purchaser will pay /// @param _timestamp Prospective purchase timestamp /// @return weiPerToken expected MET token rate /// @return tokens Expected token for a prospective purchase /// @return refund Wei refund the purchaser will get if amount is excess and MET supply is less function whatWouldPurchaseDo(uint _wei, uint _timestamp) public constant returns (uint weiPerToken, uint tokens, uint refund) { weiPerToken = calcPriceAt(whichTick(_timestamp)); uint calctokens = METDECMULT.mul(_wei).div(weiPerToken); tokens = calctokens; if (calctokens > mintable) { tokens = mintable; uint weiPaying = mintable.mul(weiPerToken).div(METDECMULT); refund = _wei.sub(weiPaying); } } /// @notice Return the information about the next auction /// @return _startTime Start time of next auction /// @return _startPrice Start price of MET in next auction /// @return _auctionTokens MET supply in next auction function nextAuction() internal constant returns(uint _startTime, uint _startPrice, uint _auctionTokens) { if (block.timestamp < genesisTime) { _startTime = genesisTime; _startPrice = lastPurchasePrice; _auctionTokens = mintable; return; } uint recentAuction = whichAuction(lastPurchaseTick); uint currAuc = currentAuction(); uint totalAuctions = currAuc - recentAuction; _startTime = dailyAuctionStartTime; if (currAuc > 1) { _startTime = auctionStartTime(currentTick()); } _auctionTokens = nextAuctionSupply(totalAuctions); if (totalAuctions > 1) { _startPrice = lastPurchasePrice / 100 + 1; } else { if (mintable == 0 || totalAuctions == 0) { // Sold out scenario or someone querying projected start price of next auction _startPrice = (lastPurchasePrice * 2) + 1; } else { // Timed out and all tokens not sold. if (currAuc == 1) { // If initial auction timed out then price before start of new auction will touch floor price _startPrice = minimumPrice * 2; } else { // Descending price till end of auction and then multiply by 2 uint tickWhenAuctionEnded = whichTick(_startTime); uint numTick = 0; if (tickWhenAuctionEnded > lastPurchaseTick) { numTick = tickWhenAuctionEnded - lastPurchaseTick; } _startPrice = priceAt(lastPurchasePrice, numTick) * 2; } } } } /// @notice Calculate results of a purchase /// @param _wei Amount of wei the purchaser will pay /// @param _t Prospective purchase tick /// @return weiPerToken expected MET token rate /// @return tokens Expected token for a prospective purchase /// @return refund Wei refund the purchaser will get if amount is excess and MET supply is less function calcPurchase(uint _wei, uint _t) internal view returns (uint weiPerToken, uint tokens, uint refund) { require(_t >= lastPurchaseTick); uint numTicks = _t - lastPurchaseTick; if (isInitialAuctionEnded()) { weiPerToken = priceAt(lastPurchasePrice, numTicks); } else { weiPerToken = priceAtInitialAuction(lastPurchasePrice, numTicks); } uint calctokens = METDECMULT.mul(_wei).div(weiPerToken); tokens = calctokens; if (calctokens > mintable) { tokens = mintable; uint ethPaying = mintable.mul(weiPerToken).div(METDECMULT); refund = _wei.sub(ethPaying); } } /// @notice MET supply for next Auction also considering carry forward met. /// @param totalAuctionMissed auction count when no purchase done. function nextAuctionSupply(uint totalAuctionMissed) internal view returns (uint supply) { uint thisAuction = currentAuction(); uint tokensHere = token.totalSupply().add(mintable); supply = INITIAL_GLOBAL_DAILY_SUPPLY; uint dailySupplyAtLastPurchase; if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { supply = globalDailySupply(); if (totalAuctionMissed > 1) { dailySupplyAtLastPurchase = globalSupplyAfterPercentageLogic.mul(2).div(36525); supply = dailySupplyAtLastPurchase.add(supply).mul(totalAuctionMissed).div(2); } supply = (supply.mul(tokensHere)).div(globalSupplyAfterPercentageLogic); } else { if (totalAuctionMissed > 1) { supply = supply.mul(totalAuctionMissed); } uint previousGlobalMetSupply = INITIAL_SUPPLY.add(INITIAL_GLOBAL_DAILY_SUPPLY.mul(whichAuction(lastPurchaseTick))); supply = (supply.mul(tokensHere)).div(previousGlobalMetSupply); } } /// @notice price at a number of minutes out in Initial auction and daily auction /// @param _tick Metronome tick /// @return weiPerToken function calcPriceAt(uint _tick) internal constant returns (uint weiPerToken) { uint recentAuction = whichAuction(lastPurchaseTick); uint totalAuctions = whichAuction(_tick).sub(recentAuction); uint prevPrice; uint numTicks = 0; // Auction is sold out and metronome clock is in same auction if (mintable == 0 && totalAuctions == 0) { return lastPurchasePrice; } // Metronome has missed one auction ie no purchase in last auction if (totalAuctions > 1) { prevPrice = lastPurchasePrice / 100 + 1; numTicks = numTicksSinceAuctionStart(_tick); } else if (totalAuctions == 1) { // Metronome clock is in new auction, next auction // previous auction sold out if (mintable == 0) { prevPrice = lastPurchasePrice * 2; } else { // previous auctions timed out // first daily auction if (whichAuction(_tick) == 1) { prevPrice = minimumPrice * 2; } else { prevPrice = priceAt(lastPurchasePrice, numTicksTillAuctionStart(_tick)) * 2; } } numTicks = numTicksSinceAuctionStart(_tick); } else { //Auction is running prevPrice = lastPurchasePrice; numTicks = _tick - lastPurchaseTick; } require(numTicks >= 0); if (isInitialAuctionEnded()) { weiPerToken = priceAt(prevPrice, numTicks); } else { weiPerToken = priceAtInitialAuction(prevPrice, numTicks); } } /// @notice Calculate number of ticks elapsed between auction start time and given tick. /// @param _tick Given metronome tick function numTicksSinceAuctionStart(uint _tick) private view returns (uint ) { uint currentAuctionStartTime = auctionStartTime(_tick); return _tick - whichTick(currentAuctionStartTime); } /// @notice Calculate number of ticks elapsed between lastPurchaseTick and auctions start time of given tick. /// @param _tick Given metronome tick function numTicksTillAuctionStart(uint _tick) private view returns (uint) { uint currentAuctionStartTime = auctionStartTime(_tick); return whichTick(currentAuctionStartTime) - lastPurchaseTick; } /// @notice First calculate the auction which contains the given tick and then calculate /// auction start time of given tick. /// @param _tick Metronome tick function auctionStartTime(uint _tick) private view returns (uint) { return ((whichAuction(_tick)) * 1 days) / timeScale + dailyAuctionStartTime - 1 days; } /// @notice start the next day's auction function restartAuction() private { uint time; uint price; uint auctionTokens; (time, price, auctionTokens) = nextAuction(); uint thisAuction = currentAuction(); if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { globalSupplyAfterPercentageLogic = globalSupplyAfterPercentageLogic.add(globalDailySupply()); } mintable = mintable.add(auctionTokens); lastPurchasePrice = price; lastPurchaseTick = whichTick(time); } } /// @title This contract serves as a locker for a founder's tokens contract TokenLocker is Ownable { using SafeMath for uint; uint internal constant QUARTER = 91 days + 450 minutes; Auctions public auctions; METToken public token; bool public locked = false; uint public deposited; uint public lastWithdrawTime; uint public quarterlyWithdrawable; event Withdrawn(address indexed who, uint amount); event Deposited(address indexed who, uint amount); modifier onlyAuction() { require(msg.sender == address(auctions)); _; } modifier preLock() { require(!locked); _; } modifier postLock() { require(locked); _; } /// @notice Constructor to initialize TokenLocker contract. /// @param _auctions Address of auctions contract /// @param _token Address of METToken contract function TokenLocker(address _auctions, address _token) public { require(_auctions != 0x0); require(_token != 0x0); auctions = Auctions(_auctions); token = METToken(_token); } /// @notice If auctions is initialized, call to this function will result in /// locking of deposited tokens and further deposit of tokens will not be allowed. function lockTokenLocker() public onlyAuction { require(auctions.initialAuctionEndTime() != 0); require(auctions.initialAuctionEndTime() >= auctions.genesisTime()); locked = true; } /// @notice It will deposit tokens into the locker for given beneficiary. /// @param beneficiary Address of the beneficiary, whose tokens are being locked. /// @param amount Amount of tokens being locked function deposit (address beneficiary, uint amount ) public onlyAuction preLock { uint totalBalance = token.balanceOf(this); require(totalBalance.sub(deposited) >= amount); deposited = deposited.add(amount); emit Deposited(beneficiary, amount); } /// @notice This function will allow token withdraw from locker. /// 25% of total deposited tokens can be withdrawn after initial auction end. /// Remaining 75% can be withdrawn in equal amount over 12 quarters. function withdraw() public onlyOwner postLock { require(deposited > 0); uint withdrawable = 0; uint withdrawTime = auctions.initialAuctionEndTime(); if (lastWithdrawTime == 0 && auctions.isInitialAuctionEnded()) { withdrawable = withdrawable.add((deposited.mul(25)).div(100)); quarterlyWithdrawable = (deposited.sub(withdrawable)).div(12); lastWithdrawTime = withdrawTime; } require(lastWithdrawTime != 0); if (now >= lastWithdrawTime.add(QUARTER)) { uint daysSinceLastWithdraw = now.sub(lastWithdrawTime); uint totalQuarters = daysSinceLastWithdraw.div(QUARTER); require(totalQuarters > 0); withdrawable = withdrawable.add(quarterlyWithdrawable.mul(totalQuarters)); if (now >= withdrawTime.add(QUARTER.mul(12))) { withdrawable = deposited; } lastWithdrawTime = lastWithdrawTime.add(totalQuarters.mul(QUARTER)); } if (withdrawable > 0) { deposited = deposited.sub(withdrawable); token.transfer(msg.sender, withdrawable); emit Withdrawn(msg.sender, withdrawable); } } } /// @title Interface for TokenPorter contract. /// Define events and functions for TokenPorter contract interface ITokenPorter { event ExportOnChainClaimedReceiptLog(address indexed destinationMetronomeAddr, address indexed destinationRecipientAddr, uint amount); event ExportReceiptLog(bytes8 destinationChain, address destinationMetronomeAddr, address indexed destinationRecipientAddr, uint amountToBurn, uint fee, bytes extraData, uint currentTick, uint indexed burnSequence, bytes32 indexed currentBurnHash, bytes32 prevBurnHash, uint dailyMintable, uint[] supplyOnAllChains, uint genesisTime, uint blockTimestamp, uint dailyAuctionStartTime); event ImportReceiptLog(address indexed destinationRecipientAddr, uint amountImported, uint fee, bytes extraData, uint currentTick, uint indexed importSequence, bytes32 indexed currentHash, bytes32 prevHash, uint dailyMintable, uint blockTimestamp, address caller); function export(address tokenOwner, bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool); function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool); } /// @title This contract will provide export functionality for tokens. contract TokenPorter is ITokenPorter, Owned { using SafeMath for uint; Auctions public auctions; METToken public token; Validator public validator; ChainLedger public chainLedger; uint public burnSequence = 1; uint public importSequence = 1; bytes32[] public exportedBurns; uint[] public supplyOnAllChains = new uint[](6); /// @notice mapping that tracks valid destination chains for export mapping(bytes8 => address) public destinationChains; /// @notice Initialize TokenPorter contract. /// @param _tokenAddr Address of metToken contract /// @param _auctionsAddr Address of auctions contract function initTokenPorter(address _tokenAddr, address _auctionsAddr) public onlyOwner { require(_tokenAddr != 0x0); require(_auctionsAddr != 0x0); auctions = Auctions(_auctionsAddr); token = METToken(_tokenAddr); } /// @notice set address of validator contract /// @param _validator address of validator contract function setValidator(address _validator) public onlyOwner returns (bool) { require(_validator != 0x0); validator = Validator(_validator); return true; } /// @notice set address of chainLedger contract /// @param _chainLedger address of chainLedger contract function setChainLedger(address _chainLedger) public onlyOwner returns (bool) { require(_chainLedger != 0x0); chainLedger = ChainLedger(_chainLedger); return true; } /// @notice only owner can add destination chains /// @param _chainName string of destination blockchain name /// @param _contractAddress address of destination MET token to import to function addDestinationChain(bytes8 _chainName, address _contractAddress) public onlyOwner returns (bool) { require(_chainName != 0 && _contractAddress != address(0)); destinationChains[_chainName] = _contractAddress; return true; } /// @notice only owner can remove destination chains /// @param _chainName string of destination blockchain name function removeDestinationChain(bytes8 _chainName) public onlyOwner returns (bool) { require(_chainName != 0); require(destinationChains[_chainName] != address(0)); destinationChains[_chainName] = address(0); return true; } /// @notice holds claims from users that have exported on-chain /// @param key is address of destination MET token contract /// @param subKey is address of users account that burned their original MET token mapping (address => mapping(address => uint)) public claimables; /// @notice destination MET token contract calls claimReceivables to record burned /// tokens have been minted in new chain /// @param recipients array of addresses of each user that has exported from /// original chain. These can be generated by ExportReceiptLog function claimReceivables(address[] recipients) public returns (uint) { require(recipients.length > 0); uint total; for (uint i = 0; i < recipients.length; i++) { address recipient = recipients[i]; uint amountBurned = claimables[msg.sender][recipient]; if (amountBurned > 0) { claimables[msg.sender][recipient] = 0; emit ExportOnChainClaimedReceiptLog(msg.sender, recipient, amountBurned); total = total.add(1); } } return total; } /// @notice import MET tokens from another chain to this chain. /// @param _destinationChain destination chain name /// @param _addresses _addresses[0] is destMetronomeAddr and _addresses[1] is recipientAddr /// @param _extraData extra information for import /// @param _burnHashes _burnHashes[0] is previous burnHash, _burnHashes[1] is current burnHash /// @param _supplyOnAllChains MET supply on all supported chains /// @param _importData _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee /// _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, _importData[5] is _dailyMintable /// _importData[6] is _burnSequence, _importData[7] is _dailyAuctionStartTime /// @param _proof proof /// @return true/false function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool) { require(msg.sender == address(token)); require(_importData.length == 8); require(_addresses.length == 2); require(_burnHashes.length == 2); require(validator.isReceiptClaimable(_originChain, _destinationChain, _addresses, _extraData, _burnHashes, _supplyOnAllChains, _importData, _proof)); validator.claimHash(_burnHashes[1]); require(_destinationChain == auctions.chain()); uint amountToImport = _importData[1].add(_importData[2]); require(amountToImport.add(token.totalSupply()) <= auctions.globalMetSupply()); require(_addresses[0] == address(token)); if (_importData[1] == 0) { return false; } if (importSequence == 1 && token.totalSupply() == 0) { auctions.prepareAuctionForNonOGChain(); } token.mint(_addresses[1], _importData[1]); emit ImportReceiptLog(_addresses[1], _importData[1], _importData[2], _extraData, auctions.currentTick(), importSequence, _burnHashes[1], _burnHashes[0], auctions.dailyMintable(), now, msg.sender); importSequence++; chainLedger.registerImport(_originChain, _destinationChain, _importData[1]); return true; } /// @notice Export MET tokens from this chain to another chain. /// @param tokenOwner Owner of the token, whose tokens are being exported. /// @param _destChain Destination chain for exported tokens /// @param _destMetronomeAddr Metronome address on destination chain /// @param _destRecipAddr Recipient address on the destination chain /// @param _amount Amount of token being exported /// @param _extraData Extra data for this export /// @return boolean true/false based on the outcome of export function export(address tokenOwner, bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool) { require(msg.sender == address(token)); require(_destChain != 0x0 && _destMetronomeAddr != 0x0 && _destRecipAddr != 0x0 && _amount != 0); require(destinationChains[_destChain] == _destMetronomeAddr); require(token.balanceOf(tokenOwner) >= _amount.add(_fee)); token.destroy(tokenOwner, _amount.add(_fee)); uint dailyMintable = auctions.dailyMintable(); uint currentTick = auctions.currentTick(); if (burnSequence == 1) { exportedBurns.push(keccak256(uint8(0))); } if (_destChain == auctions.chain()) { claimables[_destMetronomeAddr][_destRecipAddr] = claimables[_destMetronomeAddr][_destRecipAddr].add(_amount); } uint blockTime = block.timestamp; bytes32 currentBurn = keccak256( blockTime, auctions.chain(), _destChain, _destMetronomeAddr, _destRecipAddr, _amount, currentTick, auctions.genesisTime(), dailyMintable, token.totalSupply(), _extraData, exportedBurns[burnSequence - 1]); exportedBurns.push(currentBurn); supplyOnAllChains[0] = token.totalSupply(); emit ExportReceiptLog(_destChain, _destMetronomeAddr, _destRecipAddr, _amount, _fee, _extraData, currentTick, burnSequence, currentBurn, exportedBurns[burnSequence - 1], dailyMintable, supplyOnAllChains, auctions.genesisTime(), blockTime, auctions.dailyAuctionStartTime()); burnSequence = burnSequence + 1; chainLedger.registerExport(auctions.chain(), _destChain, _amount); return true; } } contract ChainLedger is Owned { using SafeMath for uint; mapping (bytes8 => uint) public balance; mapping (bytes8 => bool) public validChain; bytes8[] public chains; address public tokenPorter; Auctions public auctions; event LogRegisterChain(address indexed caller, bytes8 indexed chain, uint supply, bool outcome); event LogRegisterExport(address indexed caller, bytes8 indexed originChain, bytes8 indexed destChain, uint amount); event LogRegisterImport(address indexed caller, bytes8 indexed originChain, bytes8 indexed destChain, uint amount); function initChainLedger(address _tokenPorter, address _auctionsAddr) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); require(_auctionsAddr != 0x0); tokenPorter = _tokenPorter; auctions = Auctions(_auctionsAddr); return true; } function registerChain(bytes8 chain, uint supply) public onlyOwner returns (bool) { require(!validChain[chain]); validChain[chain] = true; chains.push(chain); balance[chain] = supply; emit LogRegisterChain(msg.sender, chain, supply, true); } function registerExport(bytes8 originChain, bytes8 destChain, uint amount) public { require(msg.sender == tokenPorter || msg.sender == owner); require(validChain[originChain] && validChain[destChain]); require(balance[originChain] >= amount); balance[originChain] = balance[originChain].sub(amount); balance[destChain] = balance[destChain].add(amount); emit LogRegisterExport(msg.sender, originChain, destChain, amount); } function registerImport(bytes8 originChain, bytes8 destChain, uint amount) public { require(msg.sender == tokenPorter || msg.sender == owner); require(validChain[originChain] && validChain[destChain]); balance[originChain] = balance[originChain].sub(amount); balance[destChain] = balance[destChain].add(amount); emit LogRegisterImport(msg.sender, originChain, destChain, amount); } } contract Validator is Owned { mapping (bytes32 => mapping (address => bool)) public hashAttestations; mapping (address => bool) public isValidator; mapping (address => uint8) public validatorNum; address[] public validators; address public metToken; address public tokenPorter; mapping (bytes32 => bool) public hashClaimed; uint8 public threshold = 2; event LogAttestation(bytes32 indexed hash, address indexed who, bool isValid); /// @param _validator1 first validator /// @param _validator2 second validator /// @param _validator3 third validator function initValidator(address _validator1, address _validator2, address _validator3) public onlyOwner { // Clear old validators. Validators can be updated multiple times for (uint8 i = 0; i < validators.length; i++) { delete isValidator[validators[i]]; delete validatorNum[validators[i]]; } delete validators; validators.push(_validator1); validators.push(_validator2); validators.push(_validator3); // TODO: This will be NA, Bloq and a third party (escrow or company) at launch, // and should be scripted into deploy isValidator[_validator1] = true; isValidator[_validator2] = true; isValidator[_validator3] = true; validatorNum[_validator1] = 0; validatorNum[_validator2] = 1; validatorNum[_validator3] = 2; } /// @notice set address of token porter /// @param _tokenPorter address of token porter function setTokenPorter(address _tokenPorter) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); tokenPorter = _tokenPorter; return true; } function validateHash(bytes32 hash) public { require(isValidator[msg.sender]); hashAttestations[hash][msg.sender] = true; emit LogAttestation(hash, msg.sender, true); } function invalidateHash(bytes32 hash) public { require(isValidator[msg.sender]); hashAttestations[hash][msg.sender] = false; emit LogAttestation(hash, msg.sender, false); } function hashClaimable(bytes32 hash) public view returns(bool) { if (hashClaimed[hash]) { return false; } uint8 count = 0; for (uint8 i = 0; i < validators.length; i++) { if (hashAttestations[hash][validators[i]]) { count++;} } if (count >= threshold) { return true; } return false; } function claimHash(bytes32 hash) public { require(msg.sender == tokenPorter); require(hashClaimable(hash)); hashClaimed[hash] = true; } function isReceiptClaimable(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChain, uint[] _importData, bytes _proof) public view returns(bool) { // We want to validate that these hash to the provided hash as a safety check, // then we want to know if the hash is Claimable. // Due to stack too deep error and limitation in using number of local // variables we have to use uint array here. // _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee, // _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, // _importData[5] is _dailyMintable, _importData[6] is _burnSequence, // _addresses[0] is _destMetronomeAddr and _addresses[1] is _recipAddr require(_burnHashes[1] == keccak256(_importData[0], _originChain, _destinationChain, _addresses[0], _addresses[1], _importData[1], _importData[3], _importData[4], _importData[5], _supplyOnAllChain[0], _extraData, _burnHashes[0])); if (hashClaimable(_burnHashes[1])) { return true; } return false; } }
@notice Find out what the results would be of a prospective purchase @param _wei Amount of wei the purchaser will pay @param _timestamp Prospective purchase timestamp @return weiPerToken expected MET token rate @return tokens Expected token for a prospective purchase @return refund Wei refund the purchaser will get if amount is excess and MET supply is less
function whatWouldPurchaseDo(uint _wei, uint _timestamp) public constant returns (uint weiPerToken, uint tokens, uint refund) { weiPerToken = calcPriceAt(whichTick(_timestamp)); uint calctokens = METDECMULT.mul(_wei).div(weiPerToken); tokens = calctokens; if (calctokens > mintable) { tokens = mintable; uint weiPaying = mintable.mul(weiPerToken).div(METDECMULT); refund = _wei.sub(weiPaying); } }
624,362
[ 1, 3125, 596, 4121, 326, 1686, 4102, 506, 434, 279, 450, 13234, 688, 23701, 225, 389, 1814, 77, 16811, 434, 732, 77, 326, 5405, 343, 14558, 903, 8843, 225, 389, 5508, 1186, 13234, 688, 23701, 2858, 327, 732, 77, 2173, 1345, 2665, 6791, 1147, 4993, 327, 2430, 13219, 1147, 364, 279, 450, 13234, 688, 23701, 327, 16255, 1660, 77, 16255, 326, 5405, 343, 14558, 903, 336, 309, 3844, 353, 23183, 471, 6791, 14467, 353, 5242, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4121, 59, 1006, 23164, 3244, 12, 11890, 389, 1814, 77, 16, 2254, 389, 5508, 13, 1071, 5381, 203, 3639, 1135, 261, 11890, 732, 77, 2173, 1345, 16, 2254, 2430, 16, 2254, 16255, 13, 203, 565, 288, 203, 3639, 732, 77, 2173, 1345, 273, 7029, 5147, 861, 12, 12784, 6264, 24899, 5508, 10019, 203, 3639, 2254, 1443, 299, 3573, 273, 6791, 1639, 9611, 2274, 18, 16411, 24899, 1814, 77, 2934, 2892, 12, 1814, 77, 2173, 1345, 1769, 203, 3639, 2430, 273, 1443, 299, 3573, 31, 203, 3639, 309, 261, 771, 299, 3573, 405, 312, 474, 429, 13, 288, 203, 5411, 2430, 273, 312, 474, 429, 31, 203, 5411, 2254, 732, 77, 9148, 310, 273, 312, 474, 429, 18, 16411, 12, 1814, 77, 2173, 1345, 2934, 2892, 12, 18315, 1639, 9611, 2274, 1769, 203, 5411, 16255, 273, 389, 1814, 77, 18, 1717, 12, 1814, 77, 9148, 310, 1769, 203, 3639, 289, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-11-06 */ /** *Submitted for verification at Etherscan.io on 2021-11-04 */ //SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } contract DINGERX is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => uint256) private _buyMap; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1e12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "DingerX"; string private constant _symbol = "DINGERX"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; uint256 private maxWalletAmount = _tTotal * 30 / 1000; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0xc296B2166F7dAf1E25995010E6a6f22C63069a1A); _feeAddrWallet2 = payable(0xe5C205d80C4D90E6c47C5b26c60BDa22F4f7d2D4); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x0000000000000000000000000000000000000000), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function originalPurchase(address account) public view returns (uint256) { return _buyMap[account]; } function balanceOf(address account) public view override returns (uint256) { 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 setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function setMaxTx(uint256 maxTransactionAmount) external onlyOwner() { _maxTxAmount = maxTransactionAmount; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } 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 from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (!_isBuy(from)) { // TAX SELLERS 30% WHO SELL WITHIN 12 HOURS if (_buyMap[from] != 0 && (_buyMap[from] + (12 hours) >= block.timestamp)) { _feeAddr1 = 2; _feeAddr2 = 18; } else { _feeAddr1 = 2; _feeAddr2 = 8; } } else { if (_buyMap[to] == 0) { _buyMap[to] = block.timestamp; } _feeAddr1 = 2; _feeAddr2 = 8; } if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(cooldown[to] < block.timestamp); require(amount <= _maxTxAmount); require(balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded"); cooldown[to] = block.timestamp + (30 seconds); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } 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, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 10000000000 * 10 ** 9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function removeStrictTxLimit() public onlyOwner { _maxTxAmount = 1e12 * 10**9; } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } 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 _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function updateMaxTx (uint256 fee) public onlyOwner { _maxTxAmount = fee; } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, 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 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _isBuy(address _sender) private view returns (bool) { return _sender == uniswapV2Pair; } 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; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
TAX SELLERS 30% WHO SELL WITHIN 12 HOURS Cooldown
function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (!_isBuy(from)) { if (_buyMap[from] != 0 && (_buyMap[from] + (12 hours) >= block.timestamp)) { _feeAddr1 = 2; _feeAddr2 = 18; _feeAddr1 = 2; _feeAddr2 = 8; } if (_buyMap[to] == 0) { _buyMap[to] = block.timestamp; } _feeAddr1 = 2; _feeAddr2 = 8; } if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { require(cooldown[to] < block.timestamp); require(amount <= _maxTxAmount); require(balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded"); cooldown[to] = block.timestamp + (30 seconds); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); }
2,368,045
[ 1, 56, 2501, 20853, 48, 11367, 5196, 9, 678, 7995, 20853, 48, 13601, 706, 2593, 17001, 55, 385, 1371, 2378, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 3238, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 5912, 3844, 1297, 506, 6802, 2353, 3634, 8863, 203, 377, 203, 540, 203, 3639, 309, 16051, 67, 291, 38, 9835, 12, 2080, 3719, 288, 203, 5411, 309, 261, 67, 70, 9835, 863, 63, 2080, 65, 480, 374, 597, 203, 7734, 261, 67, 70, 9835, 863, 63, 2080, 65, 397, 261, 2138, 7507, 13, 1545, 1203, 18, 5508, 3719, 225, 288, 203, 7734, 389, 21386, 3178, 21, 273, 576, 31, 203, 7734, 389, 21386, 3178, 22, 273, 6549, 31, 203, 7734, 389, 21386, 3178, 21, 273, 576, 31, 203, 7734, 389, 21386, 3178, 22, 273, 1725, 31, 203, 5411, 289, 203, 5411, 309, 261, 67, 70, 9835, 863, 63, 869, 65, 422, 374, 13, 288, 203, 7734, 389, 70, 9835, 863, 63, 869, 65, 273, 1203, 18, 5508, 31, 203, 5411, 289, 203, 5411, 389, 21386, 3178, 21, 273, 576, 31, 203, 5411, 389, 21386, 3178, 22, 273, 1725, 31, 203, 3639, 289, 203, 540, 203, 3639, 309, 261, 2080, 480, 3410, 1435, 597, 358, 480, 3410, 10756, 288, 203, 5411, 2583, 12, 5, 4819, 87, 63, 2080, 65, 597, 401, 4819, 87, 63, 869, 19226, 203, 2 ]
pragma solidity 0.4.24; // File: contracts/ERC780.sol /// @title ERC780 /// @notice The ERC780 interface for storing and interacting with claims. /// See https://github.com/ethereum/EIPs/issues/780 contract ERC780 { function setClaim(address subject, bytes32 key, bytes32 value) public; function setSelfClaim(bytes32 key, bytes32 value) public; function getClaim(address issuer, address subject, bytes32 key) public view returns (bytes32); function removeClaim(address issuer, address subject, bytes32 key) public; } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/RBACInterface.sol /// @title RBACInterface /// @notice The interface for Role-Based Access Control. contract RBACInterface { function hasRole(address addr, string role) public view returns (bool); } // File: contracts/RBACManaged.sol /// @title RBACManaged /// @notice Controls access by delegating to a deployed RBAC contract. contract RBACManaged is Ownable { RBACInterface public rbac; /// @param rbacAddr The address of the RBAC contract which controls access. constructor(address rbacAddr) public { rbac = RBACInterface(rbacAddr); } function roleAdmin() internal pure returns (string); /// @notice Check if an address has a role. /// @param addr The address. /// @param role The role. /// @return A boolean indicating whether the address has the role. function hasRole(address addr, string role) public view returns (bool) { return rbac.hasRole(addr, role); } modifier onlyRole(string role) { require(hasRole(msg.sender, role), "Access denied: missing role"); _; } modifier onlyOwnerOrAdmin() { require( msg.sender == owner || hasRole(msg.sender, roleAdmin()), "Access denied: missing role"); _; } /// @notice Change the address of the deployed RBAC contract which /// controls access. Only the owner or an admin can change the address. /// @param rbacAddr The address of the RBAC contract which controls access. function setRBACAddress(address rbacAddr) public onlyOwnerOrAdmin { rbac = RBACInterface(rbacAddr); } } // File: contracts/UserAddressAliasable.sol /// @title UserAddressAliasable /// @notice Allows the address that represents an entity (individual) to be /// changed by setting aliases. Any data about an entity should be associated /// to the original (canonical) address. contract UserAddressAliasable is RBACManaged { event UserAddressAliased(address indexed oldAddr, address indexed newAddr); mapping(address => address) addressAlias; // canonical => alias function roleAddressAliaser() internal pure returns (string); /// @notice Alias a new address to an old address. Requires caller to have /// the address aliaser role returned by roleAddressAliaser(). Requires /// that neither address is already aliased to another address. /// @param oldAddr The old address. /// @param newAddr The new address. function setAddressAlias(address oldAddr, address newAddr) public onlyRole(roleAddressAliaser()) { require(addressAlias[oldAddr] == address(0), "oldAddr is already aliased to another address"); require(addressAlias[newAddr] == address(0), "newAddr is already aliased to another address"); require(oldAddr != newAddr, "oldAddr and newAddr must be different"); setAddressAliasUnsafe(oldAddr, newAddr); } /// @notice Alias a new address to an old address, bypassing all safety /// checks. Can result in broken state, so use at your own peril. Requires /// caller to have the address aliaser role returned by /// roleAddressAliaser(). /// @param oldAddr The old address. /// @param newAddr The new address. function setAddressAliasUnsafe(address oldAddr, address newAddr) public onlyRole(roleAddressAliaser()) { addressAlias[newAddr] = oldAddr; emit UserAddressAliased(oldAddr, newAddr); } /// @notice Change an address to no longer alias to anything else. Calling /// setAddressAlias(oldAddr, newAddr) is reversed by calling /// unsetAddressAlias(newAddr). /// @param addr The address to unalias. Equivalent to newAddr in setAddressAlias. function unsetAddressAlias(address addr) public onlyRole(roleAddressAliaser()) { setAddressAliasUnsafe(0, addr); } /// @notice Resolve an address to its canonical address. /// @param addr The address to resolve. /// @return The canonical address. function resolveAddress(address addr) public view returns (address) { address parentAddr = addressAlias[addr]; if (parentAddr == address(0)) { return addr; } else { return parentAddr; } } } // File: contracts/ODEMClaimsRegistry.sol /// @title ODEMClaimsRegistry /// @notice When an individual completes an event (educational course) with /// ODEM, ODEM generates a certificate of completion and sets a corresponding /// claim in this contract. The claim contains the URI (usually an IPFS path) /// where the certificate can be downloaded, and its hash (SHA-256) to prove its /// authenticity. /// If an individual changes their Ethereum address, for example if they lose /// access to their account, ODEM may alias the new address to the old /// address. Then claims apply automatically to both addresses. /// Implements the ERC780 interface. contract ODEMClaimsRegistry is RBACManaged, UserAddressAliasable, ERC780 { event ClaimSet( address indexed issuer, address indexed subject, bytes32 indexed key, bytes32 value, uint updatedAt ); event ClaimRemoved( address indexed issuer, address indexed subject, bytes32 indexed key, uint removedAt ); string constant ROLE_ADMIN = "claims__admin"; string constant ROLE_ISSUER = "claims__issuer"; string constant ROLE_ADDRESS_ALIASER = "claims__address_aliaser"; struct Claim { bytes uri; bytes32 hash; } mapping(address => mapping(bytes32 => Claim)) internal claims; // subject => key => claim // Used for safe address aliasing. Never reset to false. mapping(address => bool) internal hasClaims; /// @param rbacAddr The address of the RBAC contract which controls access to this /// contract. constructor(address rbacAddr) RBACManaged(rbacAddr) public {} /// @notice Get an ODEM claim. /// @param subject The address of the individual. /// @param key The ODEM event code. /// @return The URI where the certificate can be downloaded, and the hash /// of the certificate file. function getODEMClaim(address subject, bytes32 key) public view returns (bytes uri, bytes32 hash) { address resolved = resolveAddress(subject); return (claims[resolved][key].uri, claims[resolved][key].hash); } /// @notice Set an ODEM claim. /// Only ODEM can set claims. /// @dev Requires caller to have the role "claims__issuer". /// @param subject The address of the individual. /// @param key The ODEM event code. /// @param uri The URI where the certificate can be downloaded. /// @param hash The hash of the certificate file. function setODEMClaim(address subject, bytes32 key, bytes uri, bytes32 hash) public onlyRole(ROLE_ISSUER) { address resolved = resolveAddress(subject); claims[resolved][key].uri = uri; claims[resolved][key].hash = hash; hasClaims[resolved] = true; emit ClaimSet(msg.sender, subject, key, hash, now); } /// @notice Remove an ODEM claim. Anyone can remove a claim about /// themselves. /// Only ODEM can remove claims about others. /// @dev Requires caller to have the role "claims__issuer" or to be the /// subject. /// @param subject The address of the individual. /// @param key The ODEM event code. function removeODEMClaim(address subject, bytes32 key) public { require(hasRole(msg.sender, ROLE_ISSUER) || msg.sender == subject, "Access denied: missing role"); address resolved = resolveAddress(subject); delete claims[resolved][key]; emit ClaimRemoved(msg.sender, subject, key, now); } /// @notice Alias a new address to an old address. /// Only ODEM can set aliases. /// @dev Requires caller to have the role "claims__address_aliaser". /// Requires that neither address is already aliased to another address, /// and that the new address does not already have claims. /// @param oldAddr The old address. /// @param newAddr The new address. function setAddressAlias(address oldAddr, address newAddr) public onlyRole(ROLE_ADDRESS_ALIASER) { require(!hasClaims[newAddr], "newAddr already has claims"); super.setAddressAlias(oldAddr, newAddr); } /// @notice Get a claim. Provided for compatibility with ERC780. /// Only gets claims where the issuer is ODEM. /// @param issuer The address which set the claim. /// @param subject The address of the individual. /// @param key The ODEM event code. /// @return The hash of the certificate file. function getClaim(address issuer, address subject, bytes32 key) public view returns (bytes32) { if (hasRole(issuer, ROLE_ISSUER)) { return claims[subject][key].hash; } else { return bytes32(0); } } /// @notice Provided for compatibility with ERC780. Always fails. function setClaim(address subject, bytes32 key, bytes32 value) public { revert(); } /// @notice Provided for compatibility with ERC780. Always fails. function setSelfClaim(bytes32 key, bytes32 value) public { revert(); } /// @notice Remove a claim. Provided for compatibility with ERC780. /// Only removes claims where the issuer is ODEM. /// Anyone can remove a claim about themselves. Only ODEM can remove /// claims about others. /// @dev Requires issuer to have the role "claims__issuer". /// Requires caller to have the role "claims__issuer" or to be the /// subject. /// @param issuer The address which set the claim. /// @param subject The address of the individual. /// @param key The ODEM event code. function removeClaim(address issuer, address subject, bytes32 key) public { require(hasRole(issuer, ROLE_ISSUER), "Issuer not recognized"); removeODEMClaim(subject, key); } // Required by RBACManaged. function roleAdmin() internal pure returns (string) { return ROLE_ADMIN; } // Required by UserAddressAliasable function roleAddressAliaser() internal pure returns (string) { return ROLE_ADDRESS_ALIASER; } }
@notice Provided for compatibility with ERC780. Always fails.
function setSelfClaim(bytes32 key, bytes32 value) public { revert(); }
5,500,963
[ 1, 19254, 364, 8926, 598, 4232, 39, 27, 3672, 18, 14178, 6684, 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 ]
[ 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 ]
[ 1, 565, 445, 444, 10084, 9762, 12, 3890, 1578, 498, 16, 1731, 1578, 460, 13, 1071, 288, 203, 3639, 15226, 5621, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ uint256 private constant AIRLINE_FUND_AMOUNT = 10 ether; uint256 private constant INSURANCE_FUND_AMOUNT = 1 ether; address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint constant M = 4; // min number of multi-party voters uint private numVoted = 0; uint airlinesCount = 0; address[] multiCalls = new address[](0); // all of the addresses that have called the multi-party consensus function // address[] multiAirlineCalls = new address[](0); // all of the airlines that have called the multi-party consensus, vote function struct Passenger { bool purchasedInsurance; address wallet; uint256 insurancePaid; uint256 insurancePayout; bool insurancePayoutComplete; } mapping(address => Passenger) public passengers; mapping(bytes32 => address []) public passengersWhoBoughtInsurance; // track those passengers who purchasesed insurance for the flight mapping(address => uint256) public insurancePayout; // track insurance payout amount by passenger mapping(bytes32 => uint256[]) public amountInsuredForFlight; mapping(address => bool) private hasVoted; // track airline consesnsus voting address[] public registeredAirlines; // track registered airline address struct UserProfile { bool isRegistered; bool isAdmin; } mapping(address => UserProfile) userProfiles; struct Airline { bool isRegistered; uint numVotes; bool hasFunds; bool hasVoted; string name; address wallet; uint256 funds; } // Airline[] private airlines; mapping(address => Airline) airlines; mapping(address => uint256) private authorizedContracts; // list of authorized contracts that can call this data contract /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; authorizedContracts[msg.sender] = 1; // register the first airline airlines[msg.sender] = Airline({isRegistered: true, numVotes: 0, hasFunds: false, hasVoted: false, name: "first airline", wallet: msg.sender, funds: 0 }); numVoted = 0; airlinesCount++; registeredAirlines.push(msg.sender); // track registered airlines so that i can iterate over array of airlines. } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } // need to ensure that the calling contract is authorized modifier requireIsCallerAuthorized() { require(authorizedContracts[msg.sender] == 1, "Caller is not contract owner"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Check if a user is registered * * @return A bool that indicates if the user is registered */ function isUserRegistered ( address account ) external view returns(bool) { require(account != address(0), "'account' must be a valid address."); return userProfiles[account].isRegistered; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } function registerUser ( address account, bool isAdmin ) external requireIsOperational requireContractOwner { require(!userProfiles[account].isRegistered, "User is already registered."); userProfiles[account] = UserProfile({ isRegistered: true, isAdmin: isAdmin }); } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } // authorize the calling contract(s) to restrict data contract callers function authorizeContract ( address contractAddress ) external requireContractOwner { authorizedContracts[contractAddress] = 1; } // function to check to see if the calling contract is authorized to call this data contract function isCallerAuthorized(address callingContract) external view returns(bool) { return (authorizedContracts[callingContract] == 1); } // deauthorize the calling contract function deauthorizeContract ( address contractAddress ) external requireContractOwner { delete authorizedContracts[contractAddress]; } // verify that the airline is valid by ensuring it is funded. function isAirline(address airline) external view returns(bool) { return (airlines[airline].hasFunds == true); } // retrieve airline funds function airlineFunds(address airline) external view returns (uint256) { return (airlines[airline].funds); } function isAirlineRegistered ( address account ) external view returns(bool) { require(account != address(0),"'airline' must be a valid address"); return airlines[account].isRegistered; } function getPassenger(address passenger) requireIsOperational external view returns (bool , uint256, uint256, bool) { return ( passengers[passenger].purchasedInsurance, passengers[passenger].insurancePaid, passengers[passenger].insurancePayout, passengers[passenger].insurancePayoutComplete ); } function getPassengerInsurancePayout(address passenger) requireIsOperational external view returns (uint256) { return (passengers[passenger].insurancePayout ); } function getAirline(address airline) requireIsOperational public view returns (bool registered, bool hasfunds, string name, uint256 funds, uint numVotes,uint256 numairlines) { return ( airlines[airline].isRegistered, airlines[airline].hasFunds, airlines[airline].name, airlines[airline].funds, airlines[airline].numVotes, airlinesCount ); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function getInsurancePayout(address passenger) external view returns (uint256) { //return insurancePayout[passenger]; return 1500000000000000000; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address airline, string airlinename ) external requireIsOperational requireIsCallerAuthorized { //require(!airlines[airline].isRegistered,"Airline is already registered."); if (airlinesCount < M) { airlines[airline] = Airline({isRegistered: true,hasFunds: false, hasVoted:false, numVotes: 1,funds: 0,name: airlinename, wallet: airline}); registeredAirlines.push(airline); airlinesCount++; } else { if (!hasVoted[msg.sender]) { numVoted++; airlines[airline].numVotes++; // need at least 50% consensus if (airlines[airline].numVotes >= airlinesCount.div(2)) { // reset the voting for (uint i = 0; i < registeredAirlines.length; i++) { hasVoted[registeredAirlines[i]] = false; } airlines[airline] = Airline({isRegistered: true,hasFunds: false, hasVoted:false, numVotes: numVoted,funds: 0,name: airlinename, wallet: airline}); numVoted = 0; registeredAirlines.push(airline); airlinesCount++; } } } } /** * @dev Buy insurance for a flight * */ function buy ( address airline, string flightCode, uint256 timestamp ) requireIsOperational external payable { require(msg.value >= INSURANCE_FUND_AMOUNT, "Insufficient funds to purchase flight insurance"); require(msg.sender == tx.origin, "Unauthorized Contract"); bytes32 flightkey = getFlightKey(airline,flightCode,timestamp); // track passengers who bought insurance passengers[msg.sender] = Passenger({purchasedInsurance: true, insurancePaid: msg.value,insurancePayout: msg.value, wallet: msg.sender, insurancePayoutComplete: false}); passengersWhoBoughtInsurance[flightkey].push(msg.sender); // track amount of insurance purchased for the flight amountInsuredForFlight[flightkey].push(msg.value); } /** * @dev Credits payouts to insurees */ function creditInsurees ( bytes32 flightKey ) external requireIsOperational { address passengerWallet; uint256 insuranceToPayout; uint256 passengerPaid; for (uint i = 0; i < passengersWhoBoughtInsurance[flightKey].length; i++) { passengerWallet = passengersWhoBoughtInsurance[flightKey][i]; passengerPaid = passengers[passengerWallet].insurancePaid; insuranceToPayout = passengerPaid.mul(15).div(10); insurancePayout[passengerWallet] = insuranceToPayout; passengers[passengerWallet] = Passenger ({ purchasedInsurance: true, wallet:passengerWallet, insurancePaid:passengerPaid, insurancePayout:insuranceToPayout, insurancePayoutComplete:true}); } } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address account ) requireIsOperational external payable { require(msg.value <= passengers[account].insurancePayout,"cannot withdraw more than what is in the insurance payout"); uint256 withdrawalAmount = passengers[account].insurancePayout; passengers[account].insurancePayout = 0; insurancePayout[account] = 0; account.transfer(withdrawalAmount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( address airline ) public payable { airlines[airline].funds += msg.value; // when airline has the required funds to Vote, set hasFunds to true airlines[airline].hasFunds = true; } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(msg.sender); } }
retrieve airline funds
function airlineFunds(address airline) external view returns (uint256) { return (airlines[airline].funds); }
14,034,080
[ 1, 17466, 23350, 1369, 284, 19156, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23350, 1369, 42, 19156, 12, 2867, 23350, 1369, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 1377, 327, 261, 1826, 3548, 63, 1826, 1369, 8009, 74, 19156, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6928b8F5DC33A53C7001Aed4fA13e52Be284D331/sources/contracts/Database.sol
@notice Function that removes addresses from being approved to audit for a dev @param auditors_ Array of addresses to remove as approved auditor for a dev
function removeApprovedAuditor(address[] calldata auditors_) external { if (proofOfDeveloper.balanceOf(msg.sender) == 0) revert DoesNotOwnPODNFT(); for (uint256 i; i < auditors_.length; ++i) { approvedAuditorForDev[msg.sender][auditors_[i]] = false; } }
8,466,793
[ 1, 2083, 716, 7157, 6138, 628, 3832, 20412, 358, 8215, 364, 279, 4461, 225, 8215, 1383, 67, 225, 1510, 434, 6138, 358, 1206, 487, 20412, 20232, 1811, 364, 279, 4461, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 31639, 37, 1100, 1811, 12, 2867, 8526, 745, 892, 8215, 1383, 67, 13, 3903, 288, 203, 3639, 309, 261, 24207, 951, 28145, 18, 12296, 951, 12, 3576, 18, 15330, 13, 422, 374, 13, 15226, 9637, 1248, 5460, 52, 1212, 50, 4464, 5621, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 8215, 1383, 27799, 2469, 31, 965, 77, 13, 288, 203, 5411, 20412, 37, 1100, 1811, 1290, 8870, 63, 3576, 18, 15330, 6362, 17413, 1383, 67, 63, 77, 13563, 273, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x77b52D33CD10b7dC9bEAC8cFcFac5BAA7AaaC76e/sources/contracts/Organization.sol
return _users[tokenId].expires;
function userExpires(address _account, uint256 _tokenId) public view virtual returns (uint64) { return _subscriptions[_account][_tokenId]; }
841,528
[ 1, 2463, 389, 5577, 63, 2316, 548, 8009, 12431, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 729, 14449, 12, 2867, 389, 4631, 16, 2254, 5034, 389, 2316, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 1135, 261, 11890, 1105, 13, 203, 565, 288, 203, 3639, 327, 389, 19964, 63, 67, 4631, 6362, 67, 2316, 548, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/420/0x5597F952E9aB06D914CFf34f6E26f3D0C0cc5e51/sources/contracts/core/promise/PromiseRouter.sol
* @notice Sends a request to execute callback in the originated domain @param _domain The domain where to execute callback @param _transferId The transferId @param _callbackAddress A callback address to be called when promise callback is received @param _returnSuccess The returnSuccess from the execution @param _returnData The returnData from the execution/ get remote PromiseRouter address; revert if not found emit Send event
function send( uint32 _domain, bytes32 _transferId, address _callbackAddress, bool _returnSuccess, bytes calldata _returnData ) external onlyConnext { if (_callbackAddress == address(0)) revert PromiseRouter__send_callbackEmpty(); bytes32 remote = _mustHaveRemote(_domain); bytes memory message = PromiseMessage.formatPromiseCallback( _transferId, _callbackAddress, _returnSuccess, _returnData ); xAppConnectionManager.home().dispatch(_domain, remote, message); emit Send(_domain, remote, _transferId, _callbackAddress, _returnSuccess, _returnData, message); }
13,226,980
[ 1, 10501, 279, 590, 358, 1836, 1348, 316, 326, 4026, 690, 2461, 225, 389, 4308, 1021, 2461, 1625, 358, 1836, 1348, 225, 389, 13866, 548, 1021, 7412, 548, 225, 389, 3394, 1887, 432, 1348, 1758, 358, 506, 2566, 1347, 5109, 1348, 353, 5079, 225, 389, 2463, 4510, 1021, 327, 4510, 628, 326, 4588, 225, 389, 2463, 751, 1021, 327, 751, 628, 326, 4588, 19, 336, 2632, 5835, 8259, 1758, 31, 15226, 309, 486, 1392, 3626, 2479, 871, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1366, 12, 203, 565, 2254, 1578, 389, 4308, 16, 203, 565, 1731, 1578, 389, 13866, 548, 16, 203, 565, 1758, 389, 3394, 1887, 16, 203, 565, 1426, 389, 2463, 4510, 16, 203, 565, 1731, 745, 892, 389, 2463, 751, 203, 225, 262, 3903, 1338, 3543, 408, 288, 203, 565, 309, 261, 67, 3394, 1887, 422, 1758, 12, 20, 3719, 15226, 5835, 8259, 972, 4661, 67, 3394, 1921, 5621, 203, 203, 565, 1731, 1578, 2632, 273, 389, 11926, 17944, 5169, 24899, 4308, 1769, 203, 203, 565, 1731, 3778, 883, 273, 5835, 1079, 18, 2139, 7643, 2428, 12, 203, 1377, 389, 13866, 548, 16, 203, 1377, 389, 3394, 1887, 16, 203, 1377, 389, 2463, 4510, 16, 203, 1377, 389, 2463, 751, 203, 565, 11272, 203, 203, 565, 619, 3371, 1952, 1318, 18, 8712, 7675, 10739, 24899, 4308, 16, 2632, 16, 883, 1769, 203, 203, 565, 3626, 2479, 24899, 4308, 16, 2632, 16, 389, 13866, 548, 16, 389, 3394, 1887, 16, 389, 2463, 4510, 16, 389, 2463, 751, 16, 883, 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 ]
./full_match/1/0xD79d6ec24016357f1Bdf17AEfA84C198D2396E52/sources/_dsla-protocol/core/contracts/SLA.sol
* @notice External function to withdraw staked tokens from Provider Pool @param _amount amount to withdraw @param _tokenAddress token address to withdraw/
function withdrawProviderTokens(uint256 _amount, address _tokenAddress) external { _withdrawProviderTokens( _amount, _tokenAddress, nextVerifiablePeriod, contractFinished() ); emit ProviderWithdraw( _tokenAddress, nextVerifiablePeriod, msg.sender, _amount ); }
17,152,374
[ 1, 6841, 445, 358, 598, 9446, 384, 9477, 2430, 628, 7561, 8828, 225, 389, 8949, 3844, 358, 598, 9446, 225, 389, 2316, 1887, 1147, 1758, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 2249, 5157, 12, 11890, 5034, 389, 8949, 16, 1758, 389, 2316, 1887, 13, 203, 3639, 3903, 203, 565, 288, 203, 3639, 389, 1918, 9446, 2249, 5157, 12, 203, 5411, 389, 8949, 16, 203, 5411, 389, 2316, 1887, 16, 203, 5411, 1024, 3945, 8424, 5027, 16, 203, 5411, 6835, 10577, 1435, 203, 3639, 11272, 203, 203, 3639, 3626, 7561, 1190, 9446, 12, 203, 5411, 389, 2316, 1887, 16, 203, 5411, 1024, 3945, 8424, 5027, 16, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 389, 8949, 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 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.9; import { FullMath } from '@uniswap/v3-core-0.8-support/contracts/libraries/FullMath.sol'; import { FixedPoint128 } from '@uniswap/v3-core-0.8-support/contracts/libraries/FixedPoint128.sol'; import { Account } from './Account.sol'; import { SignedFullMath } from './SignedFullMath.sol'; import { LiquidityPosition } from './LiquidityPosition.sol'; import { LiquidityPositionSet } from './LiquidityPositionSet.sol'; import { FundingPayment } from './FundingPayment.sol'; import { Protocol } from './Protocol.sol'; import { IVPoolWrapper } from '../interfaces/IVPoolWrapper.sol'; import { UniswapV3PoolHelper } from './UniswapV3PoolHelper.sol'; import { IUniswapV3Pool } from '@uniswap/v3-core-0.8-support/contracts/interfaces/IUniswapV3Pool.sol'; /// @title VToken position functions library VTokenPosition { using FullMath for uint256; using SignedFullMath for int256; using UniswapV3PoolHelper for IUniswapV3Pool; using LiquidityPosition for LiquidityPosition.Info; using LiquidityPositionSet for LiquidityPosition.Set; using Protocol for Protocol.Info; enum RISK_SIDE { LONG, SHORT } struct Set { // Fixed length array of poolId = vTokenAddress.truncate() // Open positions in 8 different pairs at same time. // Collision between poolId is not possible. uint32[8] active; // array of poolIds mapping(uint32 => VTokenPosition.Info) positions; // poolId => Position int256 vQuoteBalance; uint256[100] _emptySlots; // reserved for adding variables when upgrading logic } struct Info { int256 balance; // vTokenLong - vTokenShort int256 netTraderPosition; int256 sumALastX128; // this is moved from accounts to here because of the in margin available check // the loop needs to be done over liquidity positions of same token only LiquidityPosition.Set liquidityPositions; uint256[100] _emptySlots; // reserved for adding variables when upgrading logic } /// @notice Gives the market value of the supplied token position /// @param position token position /// @param priceX128 price in Q128 /// @param wrapper pool wrapper corresponding to position function marketValue( VTokenPosition.Info storage position, uint256 priceX128, IVPoolWrapper wrapper ) internal view returns (int256 value) { value = position.balance.mulDiv(priceX128, FixedPoint128.Q128); value += unrealizedFundingPayment(position, wrapper); } /// @notice returns the market value of the supplied token position /// @param position token position /// @param priceX128 price in Q128 /// @param poolId id of the rage trade pool /// @param protocol platform constants function marketValue( VTokenPosition.Info storage position, uint32 poolId, uint256 priceX128, Protocol.Info storage protocol ) internal view returns (int256 value) { return marketValue(position, priceX128, protocol.vPoolWrapper(poolId)); } /// @notice returns the market value of the supplied token position /// @param position token position /// @param poolId id of the rage trade pool /// @param protocol platform constants function marketValue( VTokenPosition.Info storage position, uint32 poolId, Protocol.Info storage protocol ) internal view returns (int256) { uint256 priceX128 = protocol.getVirtualTwapPriceX128(poolId); return marketValue(position, poolId, priceX128, protocol); } function riskSide(VTokenPosition.Info storage position) internal view returns (RISK_SIDE) { return position.balance > 0 ? RISK_SIDE.LONG : RISK_SIDE.SHORT; } /// @notice returns the unrealized funding payment for the trader position /// @param position token position /// @param wrapper pool wrapper corresponding to position function unrealizedFundingPayment(VTokenPosition.Info storage position, IVPoolWrapper wrapper) internal view returns (int256) { int256 extrapolatedSumAX128 = wrapper.getExtrapolatedSumAX128(); int256 unrealizedFpBill = -FundingPayment.bill( extrapolatedSumAX128, position.sumALastX128, position.netTraderPosition ); return unrealizedFpBill; } function getNetPosition( VTokenPosition.Info storage position, uint32 poolId, Protocol.Info storage protocol ) internal view returns (int256) { return position.netTraderPosition + position.liquidityPositions.getNetPosition(protocol.vPool(poolId).sqrtPriceCurrent()); } }
reserved for adding variables when upgrading logic
uint256[100] _emptySlots;
2,526,922
[ 1, 18898, 364, 6534, 3152, 1347, 731, 15210, 4058, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 63, 6625, 65, 389, 5531, 16266, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./interfaces/IVotingPower.sol"; import "./interfaces/ITokenRegistry.sol"; import "./interfaces/IVotingPowerFormula.sol"; import "./lib/AccessControl.sol"; import "./lib/SafeMath.sol"; /** * @title LockManager * @dev Manages voting power for stakes that are locked within the Archer ecosystem, but not in the Voting Power prism */ contract LockManager is AccessControl { using SafeMath for uint256; /// @notice Admin role to create voting power from locked stakes bytes32 public constant LOCKER_ROLE = keccak256("LOCKER_ROLE"); /// @notice The amount of a given locked token that has been staked, and the resulting voting power struct LockedStake { uint256 amount; uint256 votingPower; } // Official record of staked balances for each account > token > locked stake mapping (address => mapping (address => LockedStake)) lockedStakes; /// @notice Voting power contract IVotingPower public votingPower; /// @notice modifier to restrict functions to only contracts that have been added as lockers modifier onlyLockers() { require(hasRole(LOCKER_ROLE, msg.sender), "Caller must have LOCKER_ROLE role"); _; } /// @notice An event that's emitted when a user's staked balance increases event StakeLocked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower); /// @notice An event that's emitted when a user's staked balance decreases event StakeUnlocked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower); /** * @notice Create new LockManager contract * @param _votingPower VotingPower prism contract * @param _roleManager address that is in charge of assigning roles */ constructor(address _votingPower, address _roleManager) { votingPower = IVotingPower(_votingPower); _setupRole(DEFAULT_ADMIN_ROLE, _roleManager); } /** * @notice Get total amount of tokens staked in contract by `staker` * @param staker The user with staked tokens * @param stakedToken The staked token * @return total amount staked */ function getAmountStaked(address staker, address stakedToken) public view returns (uint256) { return getStake(staker, stakedToken).amount; } /** * @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker` * @param staker The user with staked tokens * @param stakedToken The staked token * @return total staked */ function getStake(address staker, address stakedToken) public view returns (LockedStake memory) { return lockedStakes[staker][stakedToken]; } /** * @notice Calculate the voting power that will result from locking `amount` of `token` * @param token token that will be locked * @param amount amount of token that will be locked * @return resulting voting power */ function calculateVotingPower(address token, uint256 amount) public view returns (uint256) { address registry = votingPower.tokenRegistry(); require(registry != address(0), "LM::calculateVotingPower: registry not set"); address tokenFormulaAddress = ITokenRegistry(registry).tokenFormulas(token); require(tokenFormulaAddress != address(0), "LM::calculateVotingPower: token not supported"); IVotingPowerFormula tokenFormula = IVotingPowerFormula(tokenFormulaAddress); return tokenFormula.convertTokensToVotingPower(amount); } /** * @notice Grant voting power from locked `tokenAmount` of `token` * @param receiver recipient of voting power * @param token token that is locked * @param tokenAmount amount of token that is locked * @return votingPowerGranted amount of voting power granted */ function grantVotingPower( address receiver, address token, uint256 tokenAmount ) public onlyLockers returns (uint256 votingPowerGranted){ votingPowerGranted = calculateVotingPower(token, tokenAmount); lockedStakes[receiver][token].amount = lockedStakes[receiver][token].amount.add(tokenAmount); lockedStakes[receiver][token].votingPower = lockedStakes[receiver][token].votingPower.add(votingPowerGranted); votingPower.addVotingPowerForLockedTokens(receiver, votingPowerGranted); emit StakeLocked(receiver, token, tokenAmount, votingPowerGranted); } /** * @notice Remove voting power by unlocking `tokenAmount` of `token` * @param receiver holder of voting power * @param token token that is being unlocked * @param tokenAmount amount of token that is being unlocked * @return votingPowerRemoved amount of voting power removed */ function removeVotingPower( address receiver, address token, uint256 tokenAmount ) public onlyLockers returns (uint256 votingPowerRemoved) { require(lockedStakes[receiver][token].amount >= tokenAmount, "LM::removeVotingPower: not enough tokens staked"); LockedStake memory s = getStake(receiver, token); votingPowerRemoved = tokenAmount.mul(s.votingPower).div(s.amount); lockedStakes[receiver][token].amount = lockedStakes[receiver][token].amount.sub(tokenAmount); lockedStakes[receiver][token].votingPower = lockedStakes[receiver][token].votingPower.sub(votingPowerRemoved); votingPower.removeVotingPowerForUnlockedTokens(receiver, votingPowerRemoved); emit StakeUnlocked(receiver, token, tokenAmount, votingPowerRemoved); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface ITokenRegistry { function owner() external view returns (address); function tokenFormulas(address) external view returns (address); function setTokenFormula(address token, address formula) external; function removeToken(address token) external; function changeOwner(address newOwner) external; event ChangedOwner(address indexed oldOwner, address indexed newOwner); event TokenAdded(address indexed token, address indexed formula); event TokenRemoved(address indexed token); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/PrismProxy.sol"; interface IVotingPower { struct Stake { uint256 amount; uint256 votingPower; } function setPendingProxyImplementation(address newPendingImplementation) external returns (bool); function acceptProxyImplementation() external returns (bool); function setPendingProxyAdmin(address newPendingAdmin) external returns (bool); function acceptProxyAdmin() external returns (bool); function proxyAdmin() external view returns (address); function pendingProxyAdmin() external view returns (address); function proxyImplementation() external view returns (address); function pendingProxyImplementation() external view returns (address); function proxyImplementationVersion() external view returns (uint8); function become(PrismProxy prism) external; function initialize(address _archToken, address _vestingContract) external; function owner() external view returns (address); function archToken() external view returns (address); function vestingContract() external view returns (address); function tokenRegistry() external view returns (address); function lockManager() external view returns (address); function changeOwner(address newOwner) external; function setTokenRegistry(address registry) external; function setLockManager(address newLockManager) external; function stake(uint256 amount) external; function stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function withdraw(uint256 amount) external; function addVotingPowerForVestingTokens(address account, uint256 amount) external; function removeVotingPowerForClaimedTokens(address account, uint256 amount) external; function addVotingPowerForLockedTokens(address account, uint256 amount) external; function removeVotingPowerForUnlockedTokens(address account, uint256 amount) external; function getARCHAmountStaked(address staker) external view returns (uint256); function getAmountStaked(address staker, address stakedToken) external view returns (uint256); function getARCHStake(address staker) external view returns (Stake memory); function getStake(address staker, address stakedToken) external view returns (Stake memory); function balanceOf(address account) external view returns (uint256); function balanceOfAt(address account, uint256 blockNumber) external view returns (uint256); event NewPendingImplementation(address indexed oldPendingImplementation, address indexed newPendingImplementation); event NewImplementation(address indexed oldImplementation, address indexed newImplementation); event NewPendingAdmin(address indexed oldPendingAdmin, address indexed newPendingAdmin); event NewAdmin(address indexed oldAdmin, address indexed newAdmin); event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower); event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower); event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface IVotingPowerFormula { function convertTokensToVotingPower(uint256 amount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./EnumerableSet.sol"; import "./Address.sol"; import "./Context.sol"; /** * @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()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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 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(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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; contract PrismProxy { /// @notice Proxy admin and implementation storage variables struct ProxyStorage { // Administrator for this contract address admin; // Pending administrator for this contract address pendingAdmin; // Active implementation of this contract address implementation; // Pending implementation of this contract address pendingImplementation; // Implementation version of this contract uint8 version; } /// @dev Position in contract storage where prism ProxyStorage struct will be stored bytes32 constant PRISM_PROXY_STORAGE_POSITION = keccak256("prism.proxy.storage"); /// @notice Emitted when pendingImplementation is changed event NewPendingImplementation(address indexed oldPendingImplementation, address indexed newPendingImplementation); /// @notice Emitted when pendingImplementation is accepted, which means implementation is updated event NewImplementation(address indexed oldImplementation, address indexed newImplementation); /// @notice Emitted when pendingAdmin is changed event NewPendingAdmin(address indexed oldPendingAdmin, address indexed newPendingAdmin); /// @notice Emitted when pendingAdmin is accepted, which means admin is updated event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /** * @notice Load proxy storage struct from specified PRISM_PROXY_STORAGE_POSITION * @return ps ProxyStorage struct */ function proxyStorage() internal pure returns (ProxyStorage storage ps) { bytes32 position = PRISM_PROXY_STORAGE_POSITION; assembly { ps.slot := position } } /*** Admin Functions ***/ /** * @notice Create new pending implementation for prism. msg.sender must be admin * @dev Admin function for proposing new implementation contract * @return boolean indicating success of operation */ function setPendingProxyImplementation(address newPendingImplementation) public returns (bool) { ProxyStorage storage s = proxyStorage(); require(msg.sender == s.admin, "Prism::setPendingProxyImp: caller must be admin"); address oldPendingImplementation = s.pendingImplementation; s.pendingImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, s.pendingImplementation); return true; } /** * @notice Accepts new implementation for prism. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return boolean indicating success of operation */ function acceptProxyImplementation() public returns (bool) { ProxyStorage storage s = proxyStorage(); // Check caller is pendingImplementation and pendingImplementation ≠ address(0) require(msg.sender == s.pendingImplementation && s.pendingImplementation != address(0), "Prism::acceptProxyImp: caller must be pending implementation"); // Save current values for inclusion in log address oldImplementation = s.implementation; address oldPendingImplementation = s.pendingImplementation; s.implementation = s.pendingImplementation; s.pendingImplementation = address(0); s.version++; emit NewImplementation(oldImplementation, s.implementation); emit NewPendingImplementation(oldPendingImplementation, s.pendingImplementation); return true; } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return boolean indicating success of operation */ function setPendingProxyAdmin(address newPendingAdmin) public returns (bool) { ProxyStorage storage s = proxyStorage(); // Check caller = admin require(msg.sender == s.admin, "Prism::setPendingProxyAdmin: caller must be admin"); // Save current value, if any, for inclusion in log address oldPendingAdmin = s.pendingAdmin; // Store pendingAdmin with value newPendingAdmin s.pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return true; } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return boolean indicating success of operation */ function acceptProxyAdmin() public returns (bool) { ProxyStorage storage s = proxyStorage(); // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require(msg.sender == s.pendingAdmin && msg.sender != address(0), "Prism::acceptProxyAdmin: caller must be pending admin"); // Save current values for inclusion in log address oldAdmin = s.admin; address oldPendingAdmin = s.pendingAdmin; // Store admin with value pendingAdmin s.admin = s.pendingAdmin; // Clear the pending value s.pendingAdmin = address(0); emit NewAdmin(oldAdmin, s.admin); emit NewPendingAdmin(oldPendingAdmin, s.pendingAdmin); return true; } /** * @notice Get current admin for prism proxy * @return admin address */ function proxyAdmin() public view returns (address) { ProxyStorage storage s = proxyStorage(); return s.admin; } /** * @notice Get pending admin for prism proxy * @return admin address */ function pendingProxyAdmin() public view returns (address) { ProxyStorage storage s = proxyStorage(); return s.pendingAdmin; } /** * @notice Address of implementation contract * @return implementation address */ function proxyImplementation() public view returns (address) { ProxyStorage storage s = proxyStorage(); return s.implementation; } /** * @notice Address of pending implementation contract * @return pending implementation address */ function pendingProxyImplementation() public view returns (address) { ProxyStorage storage s = proxyStorage(); return s.pendingImplementation; } /** * @notice Current implementation version for proxy * @return version number */ function proxyImplementationVersion() public view returns (uint8) { ProxyStorage storage s = proxyStorage(); return s.version; } /** * @notice Delegates execution to an implementation contract. * @dev Returns to the external caller whatever the implementation returns or forwards reverts */ function _forwardToImplementation() internal { ProxyStorage storage s = proxyStorage(); // delegate all other functions to current implementation (bool success, ) = s.implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize()) switch success case 0 { revert(free_mem_ptr, returndatasize()) } default { return(free_mem_ptr, returndatasize()) } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @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 addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
* @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 { pragma solidity ^0.7.0; function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } 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 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 mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); 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; } }
269,271
[ 1, 24114, 1879, 348, 7953, 560, 1807, 30828, 5295, 598, 3096, 9391, 4271, 18, 27443, 5295, 316, 348, 7953, 560, 2193, 603, 9391, 18, 1220, 848, 17997, 563, 316, 22398, 16, 2724, 5402, 81, 414, 11234, 6750, 716, 392, 9391, 14183, 392, 555, 16, 1492, 353, 326, 4529, 6885, 316, 3551, 1801, 5402, 11987, 8191, 18, 1375, 9890, 10477, 68, 3127, 3485, 333, 509, 89, 608, 635, 15226, 310, 326, 2492, 1347, 392, 1674, 9391, 87, 18, 11637, 333, 5313, 3560, 434, 326, 22893, 5295, 19229, 4174, 392, 7278, 667, 434, 22398, 16, 1427, 518, 1807, 14553, 358, 999, 518, 3712, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 31, 203, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 2583, 12, 71, 1545, 279, 16, 315, 9890, 10477, 30, 2719, 9391, 8863, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 16, 533, 3778, 9324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 2583, 12, 71, 1545, 279, 16, 9324, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 720, 12, 69, 16, 324, 16, 315, 9890, 10477, 30, 720, 25693, 3613, 2426, 8863, 203, 565, 289, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 16, 533, 3778, 9324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 70, 1648, 279, 16, 9324, 1769, 203, 3639, 2254, 5034, 276, 273, 279, 300, 324, 31, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 2 ]
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import 'OpenZeppelin/[email protected]/contracts/token/ERC20/IERC20.sol'; import 'OpenZeppelin/[email protected]/contracts/math/SafeMath.sol'; import './BasicSpell.sol'; import '../utils/HomoraMath.sol'; import '../../interfaces/ICurvePool.sol'; import '../../interfaces/ICurveRegistry.sol'; import '../../interfaces/IWLiquidityGauge.sol'; import '../../interfaces/IWERC20.sol'; contract CurveSpellV1 is BasicSpell { using SafeMath for uint; using HomoraMath for uint; ICurveRegistry public immutable registry; IWLiquidityGauge public immutable wgauge; address public immutable crv; mapping(address => address[]) public ulTokens; // lpToken -> underlying token array mapping(address => address) public poolOf; // lpToken -> pool constructor( IBank _bank, address _werc20, address _weth, address _wgauge ) public BasicSpell(_bank, _werc20, _weth) { wgauge = IWLiquidityGauge(_wgauge); IWLiquidityGauge(_wgauge).setApprovalForAll(address(_bank), true); registry = IWLiquidityGauge(_wgauge).registry(); crv = address(IWLiquidityGauge(_wgauge).crv()); } /// @dev Return pool address given LP token and update pool info if not exist. /// @param lp LP token to find the corresponding pool. function getPool(address lp) public returns (address) { address pool = poolOf[lp]; if (pool == address(0)) { require(lp != address(0), 'no lp token'); pool = registry.get_pool_from_lp_token(lp); require(pool != address(0), 'no corresponding pool for lp token'); poolOf[lp] = pool; uint n = registry.get_n_coins(pool); address[8] memory tokens = registry.get_coins(pool); ulTokens[lp] = new address[](n); for (uint i = 0; i < n; i++) { ulTokens[lp][i] = tokens[i]; } } return pool; } function ensureApproveN(address lp, uint n) public { require(ulTokens[lp].length == n, 'incorrect pool length'); address pool = poolOf[lp]; address[] memory tokens = ulTokens[lp]; for (uint idx = 0; idx < n; idx++) { ensureApprove(tokens[idx], pool); } } /// @dev add liquidity for pools with 2 underlying tokens function addLiquidity2( address lp, uint[2] calldata amtsUser, uint amtLPUser, uint[2] calldata amtsBorrow, uint amtLPBorrow, uint minLPMint, uint pid, uint gid ) external { address pool = getPool(lp); require(ulTokens[lp].length == 2, 'incorrect pool length'); require(wgauge.getUnderlyingToken(wgauge.encodeId(pid, gid, 0)) == lp, 'incorrect underlying'); address[] memory tokens = ulTokens[lp]; // 0. Take out collateral uint positionId = bank.POSITION_ID(); (, , uint collId, uint collSize) = bank.getPositionInfo(positionId); if (collSize > 0) { (uint decodedPid, uint decodedGid, ) = wgauge.decodeId(collId); require(decodedPid == pid && decodedGid == gid, 'incorrect coll id'); bank.takeCollateral(address(wgauge), collId, collSize); wgauge.burn(collId, collSize); } // 1. Ensure approve 2 underlying tokens ensureApproveN(lp, 2); // 2. Get user input amounts for (uint i = 0; i < 2; i++) doTransmit(tokens[i], amtsUser[i]); doTransmit(lp, amtLPUser); // 3. Borrow specified amounts for (uint i = 0; i < 2; i++) doBorrow(tokens[i], amtsBorrow[i]); doBorrow(lp, amtLPBorrow); // 4. add liquidity uint[2] memory suppliedAmts; for (uint i = 0; i < 2; i++) { suppliedAmts[i] = IERC20(tokens[i]).balanceOf(address(this)); } ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint); // 5. Put collateral uint amount = IERC20(lp).balanceOf(address(this)); ensureApprove(lp, address(wgauge)); uint id = wgauge.mint(pid, gid, amount); bank.putCollateral(address(wgauge), id, amount); // 6. Refund for (uint i = 0; i < 2; i++) doRefund(tokens[i]); // 7. Refund crv doRefund(crv); } /// @dev add liquidity for pools with 3 underlying tokens function addLiquidity3( address lp, uint[3] calldata amtsUser, uint amtLPUser, uint[3] calldata amtsBorrow, uint amtLPBorrow, uint minLPMint, uint pid, uint gid ) external { address pool = getPool(lp); require(ulTokens[lp].length == 3, 'incorrect pool length'); require(wgauge.getUnderlyingToken(wgauge.encodeId(pid, gid, 0)) == lp, 'incorrect underlying'); address[] memory tokens = ulTokens[lp]; // 0. take out collateral uint positionId = bank.POSITION_ID(); (, , uint collId, uint collSize) = bank.getPositionInfo(positionId); if (collSize > 0) { (uint decodedPid, uint decodedGid, ) = wgauge.decodeId(collId); require(decodedPid == pid && decodedGid == gid, 'incorrect coll id'); bank.takeCollateral(address(wgauge), collId, collSize); wgauge.burn(collId, collSize); } // 1. Ensure approve 3 underlying tokens ensureApproveN(lp, 3); // 2. Get user input amounts for (uint i = 0; i < 3; i++) doTransmit(tokens[i], amtsUser[i]); doTransmit(lp, amtLPUser); // 3. Borrow specified amounts for (uint i = 0; i < 3; i++) doBorrow(tokens[i], amtsBorrow[i]); doBorrow(lp, amtLPBorrow); // 4. add liquidity uint[3] memory suppliedAmts; for (uint i = 0; i < 3; i++) { suppliedAmts[i] = IERC20(tokens[i]).balanceOf(address(this)); } ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint); // 5. put collateral uint amount = IERC20(lp).balanceOf(address(this)); ensureApprove(lp, address(wgauge)); uint id = wgauge.mint(pid, gid, amount); bank.putCollateral(address(wgauge), id, amount); // 6. Refund for (uint i = 0; i < 3; i++) doRefund(tokens[i]); // 7. Refund crv doRefund(crv); } /// @dev add liquidity for pools with 4 underlying tokens function addLiquidity4( address lp, uint[4] calldata amtsUser, uint amtLPUser, uint[4] calldata amtsBorrow, uint amtLPBorrow, uint minLPMint, uint pid, uint gid ) external { address pool = getPool(lp); require(ulTokens[lp].length == 4, 'incorrect pool length'); require(wgauge.getUnderlyingToken(wgauge.encodeId(pid, gid, 0)) == lp, 'incorrect underlying'); address[] memory tokens = ulTokens[lp]; // 0. Take out collateral uint positionId = bank.POSITION_ID(); (, , uint collId, uint collSize) = bank.getPositionInfo(positionId); if (collSize > 0) { (uint decodedPid, uint decodedGid, ) = wgauge.decodeId(collId); require(decodedPid == pid && decodedGid == gid, 'incorrect coll id'); bank.takeCollateral(address(wgauge), collId, collSize); wgauge.burn(collId, collSize); } // 1. Ensure approve 4 underlying tokens ensureApproveN(lp, 4); // 2. Get user input amounts for (uint i = 0; i < 4; i++) doTransmit(tokens[i], amtsUser[i]); doTransmit(lp, amtLPUser); // 3. Borrow specified amounts for (uint i = 0; i < 4; i++) doBorrow(tokens[i], amtsBorrow[i]); doBorrow(lp, amtLPBorrow); // 4. add liquidity uint[4] memory suppliedAmts; for (uint i = 0; i < 4; i++) { suppliedAmts[i] = IERC20(tokens[i]).balanceOf(address(this)); } ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint); // 5. Put collateral uint amount = IERC20(lp).balanceOf(address(this)); ensureApprove(lp, address(wgauge)); uint id = wgauge.mint(pid, gid, amount); bank.putCollateral(address(wgauge), id, amount); // 6. Refund for (uint i = 0; i < 4; i++) doRefund(tokens[i]); // 7. Refund crv doRefund(crv); } function removeLiquidity2( address lp, uint amtLPTake, uint amtLPWithdraw, uint[2] calldata amtsRepay, uint amtLPRepay, uint[2] calldata amtsMin ) external { address pool = getPool(lp); uint positionId = bank.POSITION_ID(); (, address collToken, uint collId, ) = bank.getPositionInfo(positionId); require(IWLiquidityGauge(collToken).getUnderlyingToken(collId) == lp, 'incorrect underlying'); address[] memory tokens = ulTokens[lp]; // 0. Ensure approve ensureApproveN(lp, 2); // 1. Compute repay amount if MAX_INT is supplied (max debt) uint[2] memory actualAmtsRepay; for (uint i = 0; i < 2; i++) { actualAmtsRepay[i] = amtsRepay[i] == uint(-1) ? bank.borrowBalanceCurrent(positionId, tokens[i]) : amtsRepay[i]; } uint[2] memory amtsDesired; for (uint i = 0; i < 2; i++) { amtsDesired[i] = actualAmtsRepay[i].add(amtsMin[i]); // repay amt + slippage control } // 2. Take out collateral bank.takeCollateral(address(wgauge), collId, amtLPTake); wgauge.burn(collId, amtLPTake); // 3. Compute amount to actually remove. Remove to repay just enough uint amtLPToRemove; if (amtsDesired[0] > 0 || amtsDesired[1] > 0) { amtLPToRemove = IERC20(lp).balanceOf(address(this)).sub(amtLPWithdraw); ICurvePool(pool).remove_liquidity_imbalance(amtsDesired, amtLPToRemove); } // 4. Compute leftover amount to remove. Remove balancedly. amtLPToRemove = IERC20(lp).balanceOf(address(this)).sub(amtLPWithdraw); uint[2] memory mins; ICurvePool(pool).remove_liquidity(amtLPToRemove, mins); // 5. Repay for (uint i = 0; i < 2; i++) { doRepay(tokens[i], actualAmtsRepay[i]); } doRepay(lp, amtLPRepay); // 6. Refund for (uint i = 0; i < 2; i++) { doRefund(tokens[i]); } doRefund(lp); // 7. Refund crv doRefund(crv); } function removeLiquidity3( address lp, uint amtLPTake, uint amtLPWithdraw, uint[3] calldata amtsRepay, uint amtLPRepay, uint[3] calldata amtsMin ) external { address pool = getPool(lp); uint positionId = bank.POSITION_ID(); (, address collToken, uint collId, ) = bank.getPositionInfo(positionId); require(IWLiquidityGauge(collToken).getUnderlyingToken(collId) == lp, 'incorrect underlying'); address[] memory tokens = ulTokens[lp]; // 0. Ensure approve ensureApproveN(lp, 3); // 1. Compute repay amount if MAX_INT is supplied (max debt) uint[3] memory actualAmtsRepay; for (uint i = 0; i < 3; i++) { actualAmtsRepay[i] = amtsRepay[i] == uint(-1) ? bank.borrowBalanceCurrent(positionId, tokens[i]) : amtsRepay[i]; } uint[3] memory amtsDesired; for (uint i = 0; i < 3; i++) { amtsDesired[i] = actualAmtsRepay[i].add(amtsMin[i]); // repay amt + slippage control } // 2. Take out collateral bank.takeCollateral(address(wgauge), collId, amtLPTake); wgauge.burn(collId, amtLPTake); // 3. Compute amount to actually remove. Remove to repay just enough uint amtLPToRemove; if (amtsDesired[0] > 0 || amtsDesired[1] > 0 || amtsDesired[2] > 0) { amtLPToRemove = IERC20(lp).balanceOf(address(this)).sub(amtLPWithdraw); ICurvePool(pool).remove_liquidity_imbalance(amtsDesired, amtLPToRemove); } // 4. Compute leftover amount to remove. Remove balancedly. amtLPToRemove = IERC20(lp).balanceOf(address(this)).sub(amtLPWithdraw); uint[3] memory mins; ICurvePool(pool).remove_liquidity(amtLPToRemove, mins); // 5. Repay for (uint i = 0; i < 3; i++) { doRepay(tokens[i], actualAmtsRepay[i]); } doRepay(lp, amtLPRepay); // 6. Refund for (uint i = 0; i < 3; i++) { doRefund(tokens[i]); } doRefund(lp); // 7. Refund crv doRefund(crv); } function removeLiquidity4( address lp, uint amtLPTake, uint amtLPWithdraw, uint[4] calldata amtsRepay, uint amtLPRepay, uint[4] calldata amtsMin ) external { address pool = getPool(lp); uint positionId = bank.POSITION_ID(); (, address collToken, uint collId, ) = bank.getPositionInfo(positionId); require(IWLiquidityGauge(collToken).getUnderlyingToken(collId) == lp, 'incorrect underlying'); address[] memory tokens = ulTokens[lp]; // 0. Ensure approve ensureApproveN(lp, 4); // 1. Compute repay amount if MAX_INT is supplied (max debt) uint[4] memory actualAmtsRepay; for (uint i = 0; i < 4; i++) { actualAmtsRepay[i] = amtsRepay[i] == uint(-1) ? bank.borrowBalanceCurrent(positionId, tokens[i]) : amtsRepay[i]; } uint[4] memory amtsDesired; for (uint i = 0; i < 4; i++) { amtsDesired[i] = actualAmtsRepay[i].add(amtsMin[i]); // repay amt + slippage control } // 2. Take out collateral bank.takeCollateral(address(wgauge), collId, amtLPTake); wgauge.burn(collId, amtLPTake); // 3. Compute amount to actually remove. Remove to repay just enough uint amtLPToRemove; if (amtsDesired[0] > 0 || amtsDesired[1] > 0 || amtsDesired[2] > 0 || amtsDesired[3] > 0) { amtLPToRemove = IERC20(lp).balanceOf(address(this)).sub(amtLPWithdraw); ICurvePool(pool).remove_liquidity_imbalance(amtsDesired, amtLPToRemove); } // 4. Compute leftover amount to remove. Remove balancedly. amtLPToRemove = IERC20(lp).balanceOf(address(this)).sub(amtLPWithdraw); uint[4] memory mins; ICurvePool(pool).remove_liquidity(amtLPToRemove, mins); // 5. Repay for (uint i = 0; i < 4; i++) { doRepay(tokens[i], actualAmtsRepay[i]); } doRepay(lp, amtLPRepay); // 6. Refund for (uint i = 0; i < 4; i++) { doRefund(tokens[i]); } doRefund(lp); // 7. Refund crv doRefund(crv); } function harvest() external { uint positionId = bank.POSITION_ID(); (, , uint collId, uint collSize) = bank.getPositionInfo(positionId); (uint pid, uint gid, ) = wgauge.decodeId(collId); address lp = wgauge.getUnderlyingToken(collId); // 1. Take out collateral bank.takeCollateral(address(wgauge), collId, collSize); wgauge.burn(collId, collSize); // 2. Put collateral uint amount = IERC20(lp).balanceOf(address(this)); ensureApprove(lp, address(wgauge)); uint id = wgauge.mint(pid, gid, amount); bank.putCollateral(address(wgauge), id, amount); // 3. Refund crv doRefund(crv); } }
@dev add liquidity for pools with 3 underlying tokens 0. take out collateral
function addLiquidity3( address lp, uint[3] calldata amtsUser, uint amtLPUser, uint[3] calldata amtsBorrow, uint amtLPBorrow, uint minLPMint, uint pid, uint gid ) external { address pool = getPool(lp); require(ulTokens[lp].length == 3, 'incorrect pool length'); require(wgauge.getUnderlyingToken(wgauge.encodeId(pid, gid, 0)) == lp, 'incorrect underlying'); address[] memory tokens = ulTokens[lp]; uint positionId = bank.POSITION_ID(); (, , uint collId, uint collSize) = bank.getPositionInfo(positionId); if (collSize > 0) { (uint decodedPid, uint decodedGid, ) = wgauge.decodeId(collId); require(decodedPid == pid && decodedGid == gid, 'incorrect coll id'); bank.takeCollateral(address(wgauge), collId, collSize); wgauge.burn(collId, collSize); } doTransmit(lp, amtLPUser); doBorrow(lp, amtLPBorrow); for (uint i = 0; i < 3; i++) { suppliedAmts[i] = IERC20(tokens[i]).balanceOf(address(this)); } ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint); ensureApprove(lp, address(wgauge)); uint id = wgauge.mint(pid, gid, amount); bank.putCollateral(address(wgauge), id, amount); }
12,582,163
[ 1, 1289, 4501, 372, 24237, 364, 16000, 598, 890, 6808, 2430, 374, 18, 4862, 596, 4508, 2045, 287, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 527, 48, 18988, 24237, 23, 12, 203, 565, 1758, 12423, 16, 203, 565, 2254, 63, 23, 65, 745, 892, 25123, 87, 1299, 16, 203, 565, 2254, 25123, 14461, 1299, 16, 203, 565, 2254, 63, 23, 65, 745, 892, 25123, 87, 38, 15318, 16, 203, 565, 2254, 25123, 14461, 38, 15318, 16, 203, 565, 2254, 1131, 48, 12728, 474, 16, 203, 565, 2254, 4231, 16, 203, 565, 2254, 11399, 203, 225, 262, 3903, 288, 203, 565, 1758, 2845, 273, 28575, 12, 9953, 1769, 203, 565, 2583, 12, 332, 5157, 63, 9953, 8009, 2469, 422, 890, 16, 296, 267, 6746, 2845, 769, 8284, 203, 565, 2583, 12, 18197, 8305, 18, 588, 14655, 6291, 1345, 12, 18197, 8305, 18, 3015, 548, 12, 6610, 16, 11399, 16, 374, 3719, 422, 12423, 16, 296, 267, 6746, 6808, 8284, 203, 565, 1758, 8526, 3778, 2430, 273, 7493, 5157, 63, 9953, 15533, 203, 203, 565, 2254, 1754, 548, 273, 11218, 18, 15258, 67, 734, 5621, 203, 565, 261, 16, 269, 2254, 4508, 548, 16, 2254, 4508, 1225, 13, 273, 11218, 18, 588, 2555, 966, 12, 3276, 548, 1769, 203, 565, 309, 261, 12910, 1225, 405, 374, 13, 288, 203, 1377, 261, 11890, 6383, 12478, 16, 2254, 6383, 43, 350, 16, 262, 273, 8397, 8305, 18, 3922, 548, 12, 12910, 548, 1769, 203, 1377, 2583, 12, 26646, 12478, 422, 4231, 597, 6383, 43, 350, 422, 11399, 16, 296, 267, 6746, 4508, 612, 8284, 203, 1377, 11218, 18, 22188, 13535, 2045, 287, 12, 2867, 12, 18197, 8305, 3631, 4508, 548, 16, 2 ]
pragma solidity ^0.5.0; contract CrushChain { address owner; uint constant public crush = 1 ether; struct Post { uint id; // Reference posts with their IDs string content; uint256 timestamp; uint award; // bool claimed; // Whether the owner has claimed the post uint flags; // Number of spam/inappropriate reports on post } struct IOU { address sender; uint award; } // Posts are a collection of post mapped from their id to content uint public postsCount; mapping(uint => Post) public posts; // Securely store which address belong to which post mapping(uint => address) private post2wallet; mapping(address => uint[]) private wallet2post_ids; // Awards pool contains a dictionary of a list, each post with an award // maps its id to an IOU list which contains the awarder address and the award mapping (uint => IOU[]) public crushes_pool; // Public ledger that stores which address can see posts' identities mapping (address => uint[]) public whoCanSeeWhom; constructor() public { addPost("Welcome to CrushChain! Make immutable posts to your crush and be awarded by the community!"); addPost("Reward posts which you want to find out owners identity, the owner can then claim the reward and REVEAL him/herself!"); addPost("Our site deploys Machine Learning models to filter out spams! Help its performance by flagging fake crush posts."); } event PostAdded( uint id, string content ); function addPost (string memory _content) public { posts[postsCount] = Post(postsCount, _content , now, 0, false, 0); post2wallet[postsCount] = msg.sender; wallet2post_ids[msg.sender].push(postsCount); postsCount ++; emit PostAdded(postsCount, _content); } function myPosts () public view returns (uint[] memory) { return wallet2post_ids[msg.sender]; } function crushBalance() public view returns (uint) { return address(this).balance; } function awardPost (uint _id) public payable { // Need to specify post id require(msg.value >= crush); Post storage mypost = posts[_id]; require(mypost.claimed == false); crushes_pool[_id].push(IOU(msg.sender, msg.value)); mypost.award = mypost.award + msg.value; // Verify in truffle console: app = await CrushChain.deployed() } function claimPost (uint _id) public returns (uint) { // First check whether the post belongs to the claimer require(msg.sender == post2wallet[_id]); // Second check whether their are any awards on the post IOU[] storage myIOU_lst = crushes_pool[_id]; require(myIOU_lst.length >= 0); uint rewardAmount; for (uint i=0; i<myIOU_lst.length; i++) { IOU storage myIOU = myIOU_lst[i]; rewardAmount = rewardAmount + myIOU.award; // Add the sender id to the list of posts'identities which the sender can see whoCanSeeWhom[myIOU.sender].push(_id); } // Transfer fund to owner msg.sender.transfer(rewardAmount); // Set the post to be claimed and clear the amount awarded Post storage mypost = posts[_id]; mypost.claimed = true; mypost.award = 0; return rewardAmount; } function idsIcanSee() public view returns(uint [] memory) { return whoCanSeeWhom[msg.sender]; } function addsIcanSee() public view returns(address[] memory) { // Get a list of ids which the current wallet has the privilege to see uint[] memory viewable_ids = whoCanSeeWhom[msg.sender]; // Initialize address array which has the same length as viewable ids address[] memory addresses = new address[](viewable_ids.length); for (uint i=0; i<viewable_ids.length; i++) { // Convert the post id to the owner's wallet address uint id = viewable_ids[i]; address owner_add = post2wallet[id]; addresses[i] = owner_add; } return addresses; } }
Transfer fund to owner
msg.sender.transfer(rewardAmount);
13,111,273
[ 1, 5912, 284, 1074, 358, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1234, 18, 15330, 18, 13866, 12, 266, 2913, 6275, 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 ]
pragma solidity ^0.4.21; /**xxp 校验防止溢出情况 * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20Basic { using SafeMath for uint256; mapping (address => mapping (address => uint256)) internal allowed; // store tokens mapping(address => uint256) balances; // uint256 public totalSupply; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @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(); } } /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } } /* * @title EchoChainToken */ contract EchoChainToken is BurnableToken, MintableToken, PausableToken { // Public variables of the token string public name; string public symbol; // decimals is the strongly suggested default, avoid changing it uint8 public decimals; function EchoChainToken() public { name = "EchoChain"; symbol = "ECO"; decimals = 18; totalSupply = 1000000000 * 10 ** uint256(decimals); // Allocate initial balance to the owner balances[msg.sender] = totalSupply; } // transfer balance to owner function withdrawEther() onlyOwner public { address addr = this; owner.transfer(addr.balance); } // can accept ether function() payable public { } }
* @dev Function to mint tokens @param _to The address that will receive the minted tokens. @param _amount The amount of tokens to mint. @return A boolean that indicates if the operation was successful./
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(0x0, _to, _amount); return true; }
6,709,603
[ 1, 2083, 358, 312, 474, 2430, 225, 389, 869, 1021, 1758, 716, 903, 6798, 326, 312, 474, 329, 2430, 18, 225, 389, 8949, 1021, 3844, 434, 2430, 358, 312, 474, 18, 327, 432, 1250, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1338, 5541, 848, 49, 474, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1289, 24899, 8949, 1769, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 8949, 1769, 203, 3639, 3626, 490, 474, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 3626, 12279, 12, 20, 92, 20, 16, 389, 869, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-04-12 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } 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); } /** * @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); } } } } 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); } } library SafeMathUpgradeable { /** * @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; } } abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } interface IERC20Upgradeable { /** * @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); } contract Staking is OwnableUpgradeable, ReentrancyGuard{ using SafeMathUpgradeable for uint256; IERC20Upgradeable StakingToken; address private stakingTokenAddress; uint256 private _DECIMALS; address private _admin; uint256 private _MIN_STAKE_AMOUNT; uint256 private _MAX_STAKE_AMOUNT; uint256 private _REWARD_CYCLE; uint256 private _REWARD_RATE; uint256 private _currentStakedAmount; uint256 private _stakingCount; uint256 private _stakingstartdate; // start date for staking uint256 private _firstphase; uint256 private _secondphase; uint256 private _thirdphase; uint256 private _fourthphase; struct Stake { uint256 id; address staker; uint256 amount; uint256 stakeTimeStamp; uint256 lastClaimTimeStamp; bool staking; uint256 REWARDS_RATE; } mapping(address => Stake[]) private stakerToStakes; mapping(uint256 => Stake) private idToStake; uint256 private stakeId; function initialize() public initializer{ __Ownable_init(); stakingTokenAddress = 0xd718Ad25285d65eF4D79262a6CD3AEA6A8e01023; StakingToken = IERC20Upgradeable(0xd718Ad25285d65eF4D79262a6CD3AEA6A8e01023); _admin = 0xd0d725208fd36BE1561050Fc1DD6a651d7eA7C89; _DECIMALS = 18; _MIN_STAKE_AMOUNT = 10 * 10 ** _DECIMALS; _MAX_STAKE_AMOUNT = 2500 * 10 ** _DECIMALS; _REWARD_CYCLE = 30 days; // default 30 days _currentStakedAmount = 0; _stakingCount = 0; stakeId = 0; _stakingstartdate = block.timestamp; _firstphase = 30 days; _secondphase = 90 days; _thirdphase = 240 days; _fourthphase = 361 days; } //-------------------------------------------------------------------- //-------------------------- Set Values Machine ---------------------- //-------------------------------------------------------------------- function setMinStakeAmount (uint256 _minAmount) external { require(msg.sender == _admin, "You are not Admin!"); _MIN_STAKE_AMOUNT = _minAmount * 10 ** _DECIMALS; } function setMaxStakeAmount (uint256 _maxAmount) external { require(msg.sender == _admin, "You are not Admin!"); _MAX_STAKE_AMOUNT = _maxAmount * 10 ** _DECIMALS; } function setRewardsCycle (uint256 _cycle) external { require(msg.sender == _admin, "You are not Admin!"); _REWARD_CYCLE = _cycle; } function setFirstPeriod (uint256 _cycle) external { require(msg.sender == _admin, "You are not Admin!"); _firstphase = _cycle; } function setSecondPeriod (uint256 _cycle) external { require(msg.sender == _admin, "You are not Admin!"); _secondphase = _cycle; } function setThirdPeriod (uint256 _cycle) external { require(msg.sender == _admin, "You are not Admin!"); _thirdphase = _cycle; } function setFourthPeriod (uint256 _cycle) external { require(msg.sender == _admin); _fourthphase = _cycle; } //-------------------------------------------------------------------- //-------------------------- Staking Machine ------------------------- //-------------------------------------------------------------------- function stakeToken(uint256 _amount) external nonReentrant { require(StakingToken.allowance(msg.sender, address(this)) >= _amount, "Enough amount not approved."); StakingToken.transferFrom(msg.sender, address(this), _amount); Stake memory newStake; newStake.id = stakeId; newStake.staker = msg.sender; newStake.amount = _amount; newStake.stakeTimeStamp = block.timestamp; newStake.lastClaimTimeStamp = block.timestamp; newStake.staking = true; if(block.timestamp - _stakingstartdate < _firstphase) { newStake.REWARDS_RATE = 37*10**17; } else if(block.timestamp - _stakingstartdate > _firstphase && block.timestamp - _stakingstartdate < (_firstphase+_secondphase)) { newStake.REWARDS_RATE = 17*10*17; } else if(block.timestamp - _stakingstartdate > (_firstphase+_secondphase) && block.timestamp - _stakingstartdate < (_firstphase+_secondphase+_thirdphase)) { newStake.REWARDS_RATE = 69*10*16; } else if(block.timestamp - _stakingstartdate > (_firstphase+_secondphase+_thirdphase) && block.timestamp - _stakingstartdate < (_firstphase+_secondphase+_thirdphase+_fourthphase)) { newStake.REWARDS_RATE = 37*10*16; } idToStake[stakeId] = newStake; stakeId = stakeId.add(1); _currentStakedAmount = _currentStakedAmount.add(_amount); stakerToStakes[msg.sender].push(newStake); _stakingCount = _stakingCount.add(1); } function claimReward(uint256 _id) external nonReentrant{ require(idToStake[_id].staker == msg.sender, "Caller is not staker."); require(idToStake[_id].staking == true, "This staking have been finished."); require(block.timestamp - idToStake[_id].lastClaimTimeStamp >= _REWARD_CYCLE, "Reward is pending..."); uint256 stakingTime = block.timestamp - idToStake[_id].lastClaimTimeStamp; // staking time by selected Id uint256 claimableCycle = stakingTime.sub(stakingTime.mod(_REWARD_CYCLE)).div(_REWARD_CYCLE); uint256 rewardAmount = idToStake[_id].amount.div(_currentStakedAmount).mul(idToStake[_id].REWARDS_RATE).mul(6500).mul(claimableCycle); StakingToken.transfer(msg.sender, rewardAmount); idToStake[_id].lastClaimTimeStamp = block.timestamp; } function unStake(uint256 _id) external nonReentrant { require(idToStake[_id].staker == msg.sender, "Caller is not staker."); require(idToStake[_id].staking == true, "This staking have been finished."); StakingToken.transfer(msg.sender, idToStake[_id].amount); idToStake[_id].staking = false; removeFinishedStake(msg.sender, _id); _currentStakedAmount = _currentStakedAmount.sub(idToStake[_id].amount); _stakingCount = _stakingCount.sub(1); } //-------------------------------------------------------------------- //-------------------------- Views ----------------------------------- //-------------------------------------------------------------------- function getStakingTokenBalance () public view returns (uint256) { return StakingToken.balanceOf(address(this)); } function getCurrentStakedAmount () public view returns (uint256) { return _currentStakedAmount; } function getStakeInfo (uint256 _id) public view returns (uint256, address, uint256, uint256, uint256, bool) { return ( idToStake[_id].id, idToStake[_id].staker, idToStake[_id].amount, idToStake[_id].stakeTimeStamp, idToStake[_id].lastClaimTimeStamp, idToStake[_id].staking ); } function getStakingCount () public view returns (uint256) { return _stakingCount; } function getStakesByStaker (address _staker) public view returns (Stake[] memory) { return stakerToStakes[_staker]; } function getClaimable (uint256 _id) public view returns (uint256) { bool claimable_ = block.timestamp - idToStake[_id].lastClaimTimeStamp >= _REWARD_CYCLE; if(claimable_) { uint256 stakingTime = block.timestamp - idToStake[_id].lastClaimTimeStamp; uint256 claimableCycle = stakingTime.sub(stakingTime.mod(_REWARD_CYCLE)).div(_REWARD_CYCLE); uint256 rewardAmount = idToStake[_id].amount.div(_currentStakedAmount).mul(idToStake[_id].REWARDS_RATE).mul(6500).mul(claimableCycle); return rewardAmount; } else { return 0; } } function getMinStakeAmount () public view returns (uint256) { return _MIN_STAKE_AMOUNT; } function getMaxStakeAmount () public view returns (uint256) { return _MAX_STAKE_AMOUNT; } //-------------------------------------------------------------------- //-------------------------- Internal -------------------------------- //-------------------------------------------------------------------- function removeFinishedStake (address _staker, uint256 _id) internal { for (uint256 i = 0; i < stakerToStakes[_staker].length; i++) { if(stakerToStakes[_staker][i].id == _id) { stakerToStakes[_staker][i] = stakerToStakes[_staker][stakerToStakes[_staker].length - 1]; stakerToStakes[_staker].pop(); } } } }
---------------------------------------------------------------------------------------------- Set Values Machine ------------------------------------------------------------------------------------------
function setMinStakeAmount (uint256 _minAmount) external { require(msg.sender == _admin, "You are not Admin!"); _MIN_STAKE_AMOUNT = _minAmount * 10 ** _DECIMALS; }
14,517,693
[ 1, 28253, 17908, 1000, 6876, 12026, 8879, 1271, 8567, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 27724, 510, 911, 6275, 261, 11890, 5034, 389, 1154, 6275, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 225, 389, 3666, 16, 315, 6225, 854, 486, 7807, 4442, 1769, 203, 3639, 389, 6236, 67, 882, 37, 6859, 67, 2192, 51, 5321, 273, 389, 1154, 6275, 380, 1728, 2826, 389, 23816, 55, 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 ]
pragma solidity ^0.5.11; import "./oracle.sol"; contract Roulette{ // contains the game-logic //#################### CUSTOM TYPES ################################################################################ struct bet { // instead of having to keep track of the types of bets the clients make, simply collect the winning numbers affected // by the type of bet received -> easier evaluation address payable owner; uint winningAmount; // NOTE: there is seemingly no float type only a fixed-point type which is "not fully supported"... uint8[] winningNumbers; } //#################### ATTRIBUTES ################################################################################## bet[] bets; bool gameFinished; uint readyCount; uint clientCount; Oracle oracle; uint256 randomNumber; uint256 lastRoundWinningNumber; address payable oracleAddress; address payable firstClient; bool started=false; //#################### EVENTS ################################################################################## event LogSpinningWheel(string desc, address client); event RouletteDone(address client, uint rng); event EventFirstReadyClient(address client); event NotFirstClient(address client); event ClientJoined(uint clientCount); event ClientLeft(uint clientCount); event ClientReady(address client, uint readyCount); //#################### CONSTRUCTOR ################################################################################# constructor(address payable orAddress) payable public { oracle = Oracle(orAddress); readyCount = 0; clientCount = 0; gameFinished = false; oracleAddress = orAddress; } //#################### METHODS ##################################################################################### //### CLIENT-RELATED function join() public { // allows client to enter the game clientCount=clientCount+1; emit ClientJoined(clientCount); } function leave(address leaver) public { // allows client to leave the game if (clientCount >= 1) { clientCount=clientCount-1; emit ClientLeft(clientCount); // in case the firstClient leaves if(clientCount==0){ delete firstClient; } if(leaver == firstClient){ for(uint i=0;i<bets.length;i++){ bet memory temp=bets[i]; if(temp.owner != leaver){ firstClient=temp.owner; break; } } } } } function setReady() public { // allows client to mark as ready / finished betting readyCount=readyCount+1; emit ClientReady(msg.sender, readyCount); if (readyCount == 1) { // set firstClient, used to avoid race-condition in playRoulette() firstClient = msg.sender; emit EventFirstReadyClient(firstClient); } allReady(); } //### GAME MANAGEMENT function allReady() private { // if all clients ready, trigger oracle if (readyCount == clientCount) { createRandomNumber(); } } function createRandomNumber() private{ // gameFinished to indicate that no more bets can be placed gameFinished=true; oracle.generateRandomNumber(); } function getRandomNumber() private{ // allows roulette.sol to get the generated number from the oracle randomNumber=oracle.getRandomNumber(); } function playRoulette() public { // triggered upon all clients being ready require(clientCount==readyCount); // only the request of the firstClient is respected to avoid race-condition if(msg.sender == firstClient){ started=true; emit LogSpinningWheel("started playing roulette", msg.sender); getRandomNumber(); evaluate(); teardown(); } else { emit NotFirstClient(msg.sender); } } function evaluate() private { // evaluates bets and performs the according payouts for(uint i=0;i<bets.length;i++){ bet memory temp=bets[i]; for(uint j=0;j<temp.winningNumbers.length;j++){ if(randomNumber==temp.winningNumbers[j]){ payout(temp.owner,temp.winningAmount); } } } } function payout(address payable owner, uint winningAmount) private { owner.transfer(winningAmount); } function teardown() private { // at the end of the round, reset the game-state clientCount=0; readyCount=0; lastRoundWinningNumber=randomNumber; delete randomNumber; delete bets; gameFinished=false; started=false; delete firstClient; emit RouletteDone(msg.sender, lastRoundWinningNumber); } function createBet(uint8[] memory winningNumbers, uint8 payoutFactor) private { // creates the internal representation of the bet require(!gameFinished); bet memory temp; temp.winningAmount = msg.value*payoutFactor; temp.owner = msg.sender; temp.winningNumbers = winningNumbers; bets.push(temp); } //### BETS // different bet types and their respective helpers //https://livecasino.com/wp-content/uploads/2018/12/How-to-bet-on-roulette-Red.png function betRed() payable public { uint8[] memory numbers=new uint8[](18); numbers[0]=1; numbers[1]=3; numbers[2]=5; numbers[3]=7; numbers[4]=9; numbers[5]=12; numbers[6]=14; numbers[7]=16; numbers[8]=18; numbers[9]=19; numbers[10]=21; numbers[11]=23; numbers[12]=25; numbers[13]=27; numbers[14]=30; numbers[15]=32; numbers[16]=34; numbers[17]=36; createBet(numbers, 2); } function betBlack() payable public { uint8[] memory numbers=new uint8[](18); numbers[0]=2; numbers[1]=4; numbers[2]=6; numbers[3]=8; numbers[4]=10; numbers[5]=11; numbers[6]=13; numbers[7]=15; numbers[8]=17; numbers[9]=20; numbers[10]=22; numbers[11]=24; numbers[12]=26; numbers[13]=28; numbers[14]=29; numbers[15]=31; numbers[16]=33; numbers[17]=35; createBet(numbers, 2); } function betRange(uint8 start, uint8 number_count, uint8 payoutFactor) private { uint8 end = start + number_count; uint8[] memory numbers = new uint8[](number_count); uint8 counter = 0; for (uint8 i = start; i < end; i++) { numbers[counter] = i; counter++; } createBet(numbers, payoutFactor); } function betFirstDozen() payable public { betRange(1, 12, 3); } function betSecondDozen() payable public { betRange(13, 12, 3); } function betThirdDozen() payable public { betRange(25, 12, 3); } function bet1to18() payable public { betRange(1, 18, 2); } function bet19to36() payable public { betRange(19, 18, 2); } function betModulo(uint8 remainder, uint8 divisor) private { uint8[] memory numbers = new uint8[](36/divisor); uint8 counter = 0; for (uint8 i = 1; i < 37; i++) { if (i % divisor == remainder){ numbers[counter] = i; counter++; } } createBet(numbers, divisor); } function betEven() payable public { betModulo(0, 2); } function betOdd() payable public { betModulo(1, 2); } function betCol1() payable public { betModulo(1, 3); } function betCol2() payable public { betModulo(2, 3); } function betCol3() payable public { betModulo(0, 3); } function betNumber(uint8 number) payable public { uint8[] memory numbers=new uint8[](1); numbers[0] = number; createBet(numbers, 36); } // A bet on two numbers which are adjacent on the table, made by placing the chip on the shared line of the two numbers’ squares. function betSplit(uint8 number1, uint8 number2) payable public { uint8[] memory numbers=new uint8[](2); numbers[0] = number1; numbers[1] = number2; createBet(numbers, 18); } function betComboFour(uint8 number1, uint8 number2, uint8 number3, uint8 number4) payable public { uint8[] memory numbers=new uint8[](4); numbers[0] = number1; numbers[1] = number2; numbers[2] = number3; numbers[3] = number4; createBet(numbers, 9); } }
allows client to mark as ready / finished betting set firstClient, used to avoid race-condition in playRoulette()
function setReady() public { readyCount=readyCount+1; emit ClientReady(msg.sender, readyCount); if (readyCount == 1) { firstClient = msg.sender; emit EventFirstReadyClient(firstClient); } allReady(); }
1,763,429
[ 1, 5965, 87, 1004, 358, 2267, 487, 5695, 342, 6708, 2701, 1787, 444, 1122, 1227, 16, 1399, 358, 4543, 17996, 17, 4175, 316, 6599, 54, 1003, 7637, 1435, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 8367, 1435, 1071, 288, 203, 3639, 5695, 1380, 33, 1672, 1380, 15, 21, 31, 203, 3639, 3626, 2445, 8367, 12, 3576, 18, 15330, 16, 5695, 1380, 1769, 203, 3639, 309, 261, 1672, 1380, 422, 404, 13, 203, 3639, 288, 203, 5411, 1122, 1227, 273, 1234, 18, 15330, 31, 203, 5411, 3626, 2587, 3759, 8367, 1227, 12, 3645, 1227, 1769, 203, 3639, 289, 203, 3639, 777, 8367, 5621, 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 ]
./full_match/1/0xf6fd32Cbbf83e4Deb63ad40406DEB840E788ac3e/sources/contracts/others/GrowCropCorpTreasury.sol
* @notice add token-ETH liquidity. @param _token: token address @param _ethAmt: eth amount to add liquidity @param _tokenAmt: token amount to add liquidity @param _to: receiver address/
function _addLiquidityEth(address _token, uint256 _ethAmt, uint256 _tokenAmt, address _to) internal returns (uint256 amountToken, uint256 amountETH, uint256 liquidity) { IERC20(_token).safeIncreaseAllowance(uniRouterAddress, _tokenAmt); address(_token), _tokenAmt, 0, 0, _to, block.timestamp + 600 ); IERC20(_token).safeApprove(uniRouterAddress, uint256(0)); }
9,707,829
[ 1, 1289, 1147, 17, 1584, 44, 4501, 372, 24237, 18, 225, 389, 2316, 30, 1147, 1758, 225, 389, 546, 31787, 30, 13750, 3844, 358, 527, 4501, 372, 24237, 225, 389, 2316, 31787, 30, 1147, 3844, 358, 527, 4501, 372, 24237, 225, 389, 869, 30, 5971, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1289, 48, 18988, 24237, 41, 451, 12, 2867, 389, 2316, 16, 2254, 5034, 389, 546, 31787, 16, 2254, 5034, 389, 2316, 31787, 16, 1758, 389, 869, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 11890, 5034, 3844, 1345, 16, 2254, 5034, 3844, 1584, 44, 16, 2254, 5034, 4501, 372, 24237, 13, 203, 565, 288, 203, 3639, 467, 654, 39, 3462, 24899, 2316, 2934, 4626, 382, 11908, 7009, 1359, 12, 318, 77, 8259, 1887, 16, 389, 2316, 31787, 1769, 203, 203, 5411, 1758, 24899, 2316, 3631, 389, 2316, 31787, 16, 374, 16, 374, 16, 389, 869, 16, 1203, 18, 5508, 397, 14707, 203, 3639, 11272, 203, 203, 3639, 467, 654, 39, 3462, 24899, 2316, 2934, 4626, 12053, 537, 12, 318, 77, 8259, 1887, 16, 2254, 5034, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./ERC721Namable.sol"; import "./NineMilkToken.sol"; /* Error message: e1: Presale has not started e2: Public sale has not started e3: !eligible e4: All tokens have been minted e5: > PRESALE_MAX_MINT e6: Minting would exceed max supply e7: Purchase exceeds max allowed e8: Must mint at least one 9Cat e9: != ETH e10: > MAX_PER_MINT e11: must > 0 e12: Invalid Hash */ contract NineCat is ERC721Namable, Ownable { using Strings for uint256; uint256 public constant MAX_9CAT = 9999; uint256 public constant PUBLIC_SALE_PRICE = 0.07 ether; uint256 public constant PRESALE_PRICE = 0.06 ether; uint256 public constant MAX_PER_MINT = 9; uint256 public constant PRESALE_MAX_MINT = 3; uint256 public constant MAX_9CAT_MINT = 9; uint256 public nameChangePrice = 297 ether; uint256 public bioChangePrice = 99 ether; string public baseTokenURI; bool public publicSaleStarted; bool public presaleStarted; address private signer; mapping(address => uint256) private _totalClaimed; event BaseURIChanged(string baseURI); event PresaleMint(address minter, uint256 amountOf9Cat); event PublicSaleMint(address minter, uint256 amountOf9Cat); event GiveawayMint(address receiver, uint256 amountOf9Cat); modifier whenPresaleStarted() { require(presaleStarted, "e1"); _; } modifier whenPublicSaleStarted() { require(publicSaleStarted, "e2"); _; } constructor(address _signer, string memory baseURI) ERC721Namable("9Cat", "9CAT") { baseTokenURI = baseURI; signer = _signer; } function giveaway(address receiver, uint256 amountOf9Cat) external onlyOwner { uint256 _nextTokenId = totalSupply() + 1; for (uint256 i = 0; i < amountOf9Cat; i++) { _safeMint(receiver, _nextTokenId); _nextTokenId++; } yieldToken.updateRewardOnMint(receiver, amountOf9Cat); emit GiveawayMint(receiver, amountOf9Cat); } function checkPresaleEligibility(bytes32 hash, bytes memory signature) public view returns (bool) { require(ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(msg.sender))) == hash, "e12"); return ECDSA.recover(hash, signature) == signer; } function amountClaimedBy(address owner) external view returns (uint256) { require(owner != address(0)); return _totalClaimed[owner]; } function mintPresale( uint256 amountOf9Cat, bytes32 hash, bytes memory signature ) external payable whenPresaleStarted { require(checkPresaleEligibility(hash, signature), "e3"); require(totalSupply() < MAX_9CAT, "e4"); require(amountOf9Cat <= PRESALE_MAX_MINT, "e5"); require(totalSupply() + amountOf9Cat <= MAX_9CAT, "e6"); require(_totalClaimed[msg.sender] + amountOf9Cat <= PRESALE_MAX_MINT, "e7"); require(amountOf9Cat > 0, "e8"); require(PRESALE_PRICE * amountOf9Cat == msg.value, "e9"); uint256 _nextTokenId = totalSupply() + 1; for (uint256 i = 0; i < amountOf9Cat; i++) { _safeMint(msg.sender, _nextTokenId); _nextTokenId++; } _totalClaimed[msg.sender] += amountOf9Cat; yieldToken.updateRewardOnMint(msg.sender, amountOf9Cat); emit PresaleMint(msg.sender, amountOf9Cat); } function mint(uint256 amountOf9Cat) external payable whenPublicSaleStarted { require(totalSupply() < MAX_9CAT, "e4"); require(amountOf9Cat <= MAX_PER_MINT, "e10"); require(totalSupply() + amountOf9Cat <= MAX_9CAT, "e6"); require(_totalClaimed[msg.sender] + amountOf9Cat <= MAX_9CAT_MINT, "e7"); require(amountOf9Cat > 0, "e11"); require(PUBLIC_SALE_PRICE * amountOf9Cat == msg.value, "e9"); uint256 _nextTokenId = totalSupply() + 1; for (uint256 i = 0; i < amountOf9Cat; i++) { _safeMint(msg.sender, _nextTokenId); _nextTokenId++; } _totalClaimed[msg.sender] += amountOf9Cat; yieldToken.updateRewardOnMint(msg.sender, amountOf9Cat); emit PublicSaleMint(msg.sender, amountOf9Cat); } function setSigner(address addr) external onlyOwner { signer = addr; } function togglePresaleStarted() external onlyOwner { presaleStarted = !presaleStarted; } function togglePublicSaleStarted() external onlyOwner { publicSaleStarted = !publicSaleStarted; } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; emit BaseURIChanged(baseURI); } function withdrawAll() public onlyOwner { _widthdraw(0x7BcBa9cE8e52f999f5c8B175269abD4d70209407, address(this).balance); } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success); } NineMilkToken public yieldToken; function setYieldToken(address _yield) external onlyOwner { yieldToken = NineMilkToken(_yield); } function changeNamePrice(uint256 _price) external onlyOwner { nameChangePrice = _price; } function changeBioPrice(uint256 _price) external onlyOwner { bioChangePrice = _price; } function transferFrom( address from, address to, uint256 tokenId ) public override { yieldToken.updateReward(from, to, 1); super.transferFrom(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { yieldToken.updateReward(from, to, 1); super.safeTransferFrom(from, to, tokenId, _data); } function changeName(uint256 tokenId, string memory newName) public override { yieldToken.consume(msg.sender, nameChangePrice); super.changeName(tokenId, newName); } function changeBio(uint256 tokenId, string memory _bio) public override { yieldToken.consume(msg.sender, bioChangePrice); super.changeBio(tokenId, _bio); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract NineMilkToken is ERC20("9MILK", "9MILK"), Ownable, AccessControl { using SafeMath for uint256; uint256 public constant BASE_RATE = 9 ether; uint256 public constant INITIAL_ISSUANCE = 99 ether; mapping(address => uint256) public rewards; mapping(address => uint256) public lastUpdate; mapping(address => uint256) public stackableBalance; uint256 public END = 0; uint256 public START = 0; bytes32 public constant REWARD_ROLE = keccak256("REWARD_ROLE"); event RewardPaid(address indexed user, uint256 reward); 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 ? b : a; } modifier onlyRewarder() { _checkRole(REWARD_ROLE, _msgSender()); _; } modifier onlyStarted() { require(START > 0, "Not Started"); _; } function addRewardRole(address addr) external { grantRole(REWARD_ROLE, addr); } constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } function startReward() external onlyOwner { START = block.timestamp; END = START + 283824000; } // called when minting many NFTs function updateRewardOnMint(address _user, uint256 _amount) external onlyRewarder { stackableBalance[_user] += _amount; uint256 time = min(block.timestamp, END); uint256 timerUser = max(START, lastUpdate[_user]); if (timerUser > 0 && START > 0) { rewards[_user] = rewards[_user].add( stackableBalance[_user].mul(BASE_RATE.mul((time.sub(timerUser)))).div(86400).add( _amount.mul(INITIAL_ISSUANCE) ) ); } else { rewards[_user] = rewards[_user].add(_amount.mul(INITIAL_ISSUANCE)); } lastUpdate[_user] = time; } // called on transfers function updateReward( address _from, address _to, uint256 balanceChange ) external onlyRewarder { stackableBalance[_from] -= balanceChange; if (_to != address(0)) { stackableBalance[_to] += balanceChange; } uint256 time = min(block.timestamp, END); uint256 timerFrom = max(lastUpdate[_from], START); if (timerFrom > 0) rewards[_from] += stackableBalance[_from].mul(BASE_RATE.mul((time.sub(timerFrom)))).div( 86400 ); if (timerFrom != END) lastUpdate[_from] = time; if (_to != address(0)) { uint256 timerTo = max(lastUpdate[_to], START); if (timerTo > 0) rewards[_to] += stackableBalance[_to].mul(BASE_RATE.mul((time.sub(timerTo)))).div(86400); if (timerTo != END) lastUpdate[_to] = time; } } function getTotalClaimable(address _user) public view onlyStarted returns (uint256) { uint256 time = min(block.timestamp, END); uint256 u = max(lastUpdate[_user], START); uint256 pending = stackableBalance[_user].mul(BASE_RATE.mul((time.sub(u)))).div(86400); return rewards[_user] + pending; } function getReward() external onlyStarted { uint256 pending = getTotalClaimable(msg.sender); uint256 reward = rewards[msg.sender] + pending; if (reward > 0) { lastUpdate[msg.sender] = min(block.timestamp, END); rewards[msg.sender] = 0; _mint(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function consume(address _from, uint256 _amount) external onlyRewarder { _transfer(_from, owner(), _amount); } function burn(address _from, uint256 _amount) external onlyRewarder { _burn(_from, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.8; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; abstract contract ERC721Namable is ERC721Enumerable { mapping(uint256 => string) private bio; // Mapping from token ID to name mapping(uint256 => string) private _tokenName; // Mapping if certain name string has already been reserved mapping(string => bool) private _nameReserved; event NameChange(uint256 indexed tokenId, string newName); event BioChange(uint256 indexed tokenId, string bio); constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) {} function changeName(uint256 tokenId, string memory newName) public virtual { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(validateName(newName) == true, "invalid"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "x same"); require(isNameReserved(newName) == false, "reserved"); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; emit NameChange(tokenId, newName); } function changeBio(uint256 _tokenId, string memory _bio) public virtual { address owner = ownerOf(_tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); bio[_tokenId] = _bio; emit BioChange(_tokenId, _bio); } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } /** * @dev Returns name of the NFT at index. */ function tokenNameByIndex(uint256 index) public view returns (string memory) { return _tokenName[index]; } /** * @dev Returns bio of the NFT at index. */ function tokenBioByIndex(uint256 index) public view returns (string memory) { return bio[index]; } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[toLower(nameString)]; } function validateName(string memory str) public pure returns (bool) { bytes memory b = bytes(str); if (b.length < 1) return false; if (b.length > 25) return false; // Cannot be longer than 25 characters if (b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for (uint256 i; i < b.length; i++) { bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if ( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) public pure returns (string memory) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint256 i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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; /** * @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; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 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 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 "./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 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 { 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 { 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()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC721/IERC721.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; 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; 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 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; /** * @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 "../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; /** * @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 "../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; /** * @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; /** * @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 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); }
called on transfers
function updateReward( address _from, address _to, uint256 balanceChange ) external onlyRewarder { stackableBalance[_from] -= balanceChange; if (_to != address(0)) { stackableBalance[_to] += balanceChange; } uint256 time = min(block.timestamp, END); uint256 timerFrom = max(lastUpdate[_from], START); if (timerFrom > 0) rewards[_from] += stackableBalance[_from].mul(BASE_RATE.mul((time.sub(timerFrom)))).div( 86400 ); if (timerFrom != END) lastUpdate[_from] = time; if (_to != address(0)) { uint256 timerTo = max(lastUpdate[_to], START); if (timerTo > 0) rewards[_to] += stackableBalance[_to].mul(BASE_RATE.mul((time.sub(timerTo)))).div(86400); if (timerTo != END) lastUpdate[_to] = time; } }
1,147,446
[ 1, 11777, 603, 29375, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1089, 17631, 1060, 12, 203, 202, 202, 2867, 389, 2080, 16, 203, 202, 202, 2867, 389, 869, 16, 203, 202, 202, 11890, 5034, 11013, 3043, 203, 202, 13, 3903, 1338, 17631, 297, 765, 288, 203, 202, 202, 3772, 429, 13937, 63, 67, 2080, 65, 3947, 11013, 3043, 31, 203, 202, 202, 430, 261, 67, 869, 480, 1758, 12, 20, 3719, 288, 203, 1082, 202, 3772, 429, 13937, 63, 67, 869, 65, 1011, 11013, 3043, 31, 203, 202, 202, 97, 203, 202, 202, 11890, 5034, 813, 273, 1131, 12, 2629, 18, 5508, 16, 7273, 1769, 203, 202, 202, 11890, 5034, 5441, 1265, 273, 943, 12, 2722, 1891, 63, 67, 2080, 6487, 10485, 1769, 203, 202, 202, 430, 261, 12542, 1265, 405, 374, 13, 203, 1082, 202, 266, 6397, 63, 67, 2080, 65, 1011, 2110, 429, 13937, 63, 67, 2080, 8009, 16411, 12, 8369, 67, 24062, 18, 16411, 12443, 957, 18, 1717, 12, 12542, 1265, 20349, 2934, 2892, 12, 203, 9506, 202, 28, 1105, 713, 203, 1082, 202, 1769, 203, 202, 202, 430, 261, 12542, 1265, 480, 7273, 13, 1142, 1891, 63, 67, 2080, 65, 273, 813, 31, 203, 202, 202, 430, 261, 67, 869, 480, 1758, 12, 20, 3719, 288, 203, 1082, 202, 11890, 5034, 5441, 774, 273, 943, 12, 2722, 1891, 63, 67, 869, 6487, 10485, 1769, 203, 1082, 202, 430, 261, 12542, 774, 405, 374, 13, 203, 9506, 202, 266, 6397, 63, 67, 869, 65, 1011, 2110, 429, 13937, 63, 67, 869, 8009, 16411, 12, 8369, 67, 24062, 18, 16411, 12443, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-08-14 */ pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view 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); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- 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; } } contract BAPE is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "BABY APE"; symbol = "BAPE"; decimals = 18; _totalSupply = 1000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, 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); emit Transfer(from, to, tokens); return true; } }
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "BABY APE"; symbol = "BAPE"; decimals = 18; _totalSupply = 1000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
14,382,949
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 38, 2090, 61, 432, 1423, 14432, 203, 3639, 3273, 273, 315, 12536, 1423, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 9449, 31, 203, 540, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // Same version as openzeppelin 3.4 pragma solidity >=0.6.0 <0.8.0; pragma abicoder v2; // import "@openzeppelin/contracts/math/SafeMath.sol"; import "./CollectCode.sol"; import "./ICollectCode.sol"; import "./Utils.sol"; contract ChromaFive is CollectCode { uint8 internal constant GRID_SIZE = 5; constructor() ERC721("CHROMA5", "CH5") CollectCode() { config_ = Config ( "chroma5", // (seriesCode) 50, // (initialSupply) 100, // (maxSupply) 1, // (initialPrice) ETH cents GRID_SIZE, // (width) GRID_SIZE // (height) ); } } // SPDX-License-Identifier: MIT // Same version as openzeppelin 3.4 pragma solidity >=0.6.0 <0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./Utils.sol"; // import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; // for ECR721Holder.test.js abstract contract CollectCode is ERC721, Ownable { using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIds; struct Config { string seriesCode; uint256 initialSupply; uint256 maxSupply; uint256 initialPrice; uint8 width; uint8 height; } Config internal config_; struct State { bool isReleased; // Token Zero was minted uint256 mintedCount; // (ignores Token Zero) uint256 builtCount; // (ignores Token Zero) uint256 notBuiltCount; // (ignores Token Zero) uint256 currentSupply; // permitted to mint uint256 availableSupply; // not minted uint256 maxBuyout; // not minted bool isAvailable; // availableSupply > 0 } State internal state_; struct TokenInfo { address owner; bool youOwnIt; bool isBuilt; uint256 sequenceNumber; uint256[] sequenceTokens; string pixels; } mapping (uint256 => bytes) internal _pixels; mapping (uint256 => uint256) internal _sequenceNumber; constructor() { state_ = State( false, // isReleased 0, // mintedCount 0, // builtCount 0, // notBuiltCount 0, // currentSupply 0, // availableSupply 0, // maxBuyout false // isAvailable ); } // // public actions function giftCode(address to) onlyOwner public returns (uint256) { require(!state_.isReleased, "CC: Token Zero already issued"); require(to == owner(), "CC: Not Contract owner"); //require(isOwner(), "CC: Not Contract owner"); // Ownable takes care return mintCode_( to, 1, true ); } function buyCode(address to, uint256 quantity, bool build) public payable returns (uint256) { require(state_.isReleased, "CC: Not for sale yet"); require(msg.value == calculatePriceForQuantity(quantity), "CC: Value do not match quantity"); return mintCode_( to, quantity, build ); } function buildCode(uint256 tokenId) public returns (bool) { require(_exists(tokenId), "CC: Token does not exist"); require(_pixels[tokenId].length == 0, "CC: Token already built"); require(msg.sender == ownerOf(tokenId), "CC: Not Token owner"); buildCode_( msg.sender, tokenId, 0 ); return true; } function withdraw() onlyOwner public { msg.sender.transfer(address(this).balance); } // // public getters function getConfig() public view returns (Config memory) { return config_; } function getState() public view returns (State memory) { return state_; } function getTokenInfo(address from, uint256 tokenId) public view returns (TokenInfo memory) { require(_exists(tokenId), "CC: Token query for nonexistent token"); uint256[] memory sequenceTokens; if(_sequenceNumber[tokenId] > 0) { // find this token's complete sequence uint256 tokenCount = _sequenceNumber[tokenId]; for(uint256 t = tokenId+1 ; _sequenceNumber[t] > 0 && _sequenceNumber[t] > _sequenceNumber[tokenId] ; ++t) tokenCount++; sequenceTokens = new uint256[](tokenCount); for(uint256 i = 0 ; i < tokenCount ; ++i) sequenceTokens[i] = tokenId-_sequenceNumber[tokenId]+1+i; } return TokenInfo( ownerOf(tokenId), // owner address (from == ownerOf(tokenId)), // sender owns it (_pixels[tokenId].length > 0), // is built _sequenceNumber[tokenId], // build sequential number sequenceTokens, // sequence of tokens Utils.convertBytesToHexString(_pixels[tokenId]) // pixels ); } function calculatePriceForQuantity(uint256 quantity) public view returns (uint256) { uint256 price = 0; for(uint256 i = 1 ; i <= quantity ; i++) price += state_.mintedCount.add(i) * config_.initialPrice * 10000000000000000; // 1 ETH=1000000000000000000 return price; } function getPrices() public view returns (uint256[] memory) { uint256 quantity = 0; if(totalSupply() > 0 && totalSupply() < config_.maxSupply) quantity = Utils.max_uint256(state_.maxBuyout, 1); uint256[] memory prices = new uint[](quantity); for(uint256 i = 1 ; i <= quantity ; i++) prices[i-1] = calculatePriceForQuantity(i); return prices; //return Utils.convertArrayToString_uint256(prices); } function getOwnedTokens(address from) public view returns (uint256[] memory) { uint256[] memory tokenIds = new uint[](balanceOf(from)); for(uint256 i = 0 ; i < tokenIds.length ; i++) tokenIds[i] = tokenOfOwnerByIndex(from, i); return tokenIds; //return Utils.convertArrayToString_uint256(tokenIds); } // // Privates // function mintCode_(address to, uint256 quantity, bool build) internal returns (uint256) { require(quantity > 0, "CC: Quantity must be positive"); if( state_.isReleased ) { require(state_.mintedCount < config_.maxSupply, "CC: Sold out"); require(state_.mintedCount < state_.currentSupply, "CC: Sales on hold"); require(state_.mintedCount.add(quantity) <= state_.currentSupply, "CC: Quantity not available"); require(quantity <= state_.maxBuyout, "CC: Quantity not allowed"); } for(uint256 i = 0 ; i < quantity ; i++) { if( state_.isReleased ) { _tokenIds.increment(); } uint256 newTokenId = _tokenIds.current(); _mint( to, newTokenId ); // update contract state state_.isReleased = true; state_.mintedCount = newTokenId; if(newTokenId > 0) state_.notBuiltCount++; if( build ) { buildCode_(to, newTokenId, quantity == 1 ? 0 : (i+1)); } else { calculateSupply_(); makeTokenURI_(newTokenId); } } return quantity; } function buildCode_(address to, uint256 tokenId, uint256 sequenceNumber) internal { // make colors uint8[] memory c3 = Utils.reduceColors( bytes20(address(this)), // seed 1: contract address bytes20(to), // seed 2: owner address Utils.getBlockSeed(), // seed 3: block hash uint8(config_.width*2), tokenId*config_.width); // make pixels for(uint8 y = 0 ; y < config_.width ; y++) { for(uint8 x = 0 ; x < config_.width ; x++) { _pixels[tokenId].push(byte(Utils.step_uint8( c3[x*3+0], c3[(x+config_.width)*3+0], config_.width, y ))); _pixels[tokenId].push(byte(Utils.step_uint8( c3[x*3+1], c3[(x+config_.width)*3+1], config_.width, y ))); _pixels[tokenId].push(byte(Utils.step_uint8( c3[x*3+2], c3[(x+config_.width)*3+2], config_.width, y ))); } } _sequenceNumber[tokenId] = sequenceNumber; // increase built count for supply (ignore Token Zero) if(tokenId > 0) { state_.notBuiltCount--; state_.builtCount++; } calculateSupply_(); makeTokenURI_(tokenId); } function calculateSupply_() internal { if(state_.mintedCount < config_.initialSupply) { // Initial supply must go first state_.currentSupply = config_.initialSupply; } else { // Release 10% minus not build tokens uint256 surplus = Utils.percent_uint256(config_.maxSupply, 10); state_.currentSupply = state_.mintedCount // minted + surplus // add 10% - Utils.clamp_uint256(state_.notBuiltCount, 0, surplus); // minus not built if(state_.currentSupply > config_.maxSupply) state_.currentSupply = config_.maxSupply; } state_.availableSupply = state_.currentSupply - state_.mintedCount; state_.maxBuyout = Utils.min_uint256( state_.availableSupply, Utils.percent_uint256(config_.maxSupply, 5) ); state_.isAvailable = (state_.availableSupply > 0); } function makeTokenURI_(uint256 tokenId) internal { _setTokenURI( tokenId, string(abi.encodePacked( "https://collect-code.com/api/token/", config_.seriesCode, "/", Utils.utoa(uint(tokenId)), "/metadata?pixels=", Utils.convertBytesToHexString(_pixels[tokenId])) ) ); } } // SPDX-License-Identifier: MIT // Same version as openzeppelin 3.4 pragma solidity >=0.6.0 <0.8.0; interface ICollectCode { function makePixels(bytes20 s0, bytes20 s1, bytes20 s2, uint256 tokenId) external pure returns (bytes memory); } // SPDX-License-Identifier: MIT // Same version as openzeppelin 3.4 pragma solidity >=0.6.0 <0.8.0; library Utils { //--------------------------- // Convert // function convertBlockHashToAddress(uint256 blockNumber) public view returns (address) { // https://docs.soliditylang.org/en/v0.7.6/types.html#address return address(uint160(bytes20(blockhash(blockNumber)))); } function getBlockSeed() public view returns (bytes20) { address s = convertBlockHashToAddress(block.number); if( s == address(0) && block.number > 0 ) s = convertBlockHashToAddress(block.number-1); return bytes20(s); } function convertBytesToHexString(bytes memory values) public pure returns (string memory) { bytes memory result = new bytes(values.length*2); for(uint8 i = 0; i < values.length; i++) { for(uint8 j = 0 ; j < 2; j++) { uint8 v = ( j == 0 ? uint8(values[i]>>4) : uint8(values[i] & 0x0f) ); result[i*2+j] = v > 9 ? byte(55+v) : byte(48+v); } } return string(result); } function convertByteToHexString(byte b) public pure returns (string memory) { bytes memory result = new bytes(2); for(uint8 j = 0 ; j < 2; j++) { uint8 v = ( j == 0 ? uint8(b>>4) : uint8(b & 0x0f) ); result[j] = v > 9 ? byte(55+v) : byte(48+v); } return string(result); } //--------------------------- // Math // function clamp_uint256(uint256 value, uint256 min, uint256 max) public pure returns (uint256) { return value < min ? min : value > max ? max : value; } function min_uint256(uint256 a, uint256 b) public pure returns (uint256) { return a < b ? a : b; } function max_uint256(uint256 a, uint256 b) public pure returns (uint256) { return a > b ? a : b; } function percent_uint256(uint256 value, uint256 percentage) public pure returns (uint256) { return value * percentage / 100; } //--------------------------- // Pixels // function step_int(int min, int max, int stepCount, int stepIndex) public pure returns (int) { if( stepIndex <= 0 || stepCount <= 1 || min == max ) return min; if( stepIndex >= stepCount - 1 ) return max; int d = (max - min) / (stepCount - 1); return min + (d * stepIndex); } function step_uint8(uint8 min, uint8 max, uint8 stepCount, uint8 stepIndex) public pure returns (uint8) { int result = step_int( min, max, stepCount, stepIndex ); return result < 0 ? 0 : result > 255 ? 255 : uint8(result); } function map_uint256(uint256 value, uint256 min, uint256 max) public pure returns (uint256) { return min + ((value * (max - min)) / 255); } function map_uint8(uint8 value, uint8 min, uint8 max) public pure returns (uint8) { return uint8(int(min) + ((int(value) * int(max - min)) / 255)); } function rshift_bytes20(bytes20 buffer, uint256 bits) public pure returns (bytes20) { uint256 b = bits % (20*8); return (buffer >> b) | (buffer << (20*8-b)); } function lshift_bytes20(bytes20 buffer, uint256 bits) public pure returns (bytes20) { uint256 b = bits % (20*8); return (buffer << b) | (buffer >> (20*8-b)); } function sum_bytes20(bytes20 buffer) public pure returns (uint256) { uint256 sum = 0; for(uint8 i = 0 ; i < 20 ; ++i) { sum += uint8(buffer[i]); } return sum; } // HSV Conversion from // https://stackoverflow.com/a/14733008/360930 function hsvToRgb(uint8 h, uint8 s, uint8 v) public pure returns (uint8, uint8, uint8) { if (s == 0) { return (v, v, v); } int region = h / 43; int remainder = (h - (region * 43)) * 6; int p = (v * (255 - s)) >> 8; int q = (v * (255 - ((s * remainder) >> 8))) >> 8; int t = (v * (255 - ((s * (255 - remainder)) >> 8))) >> 8; if(region == 0) { return(v, uint8(t), uint8(p)); } else if (region == 1) { return(uint8(q), v, uint8(p)); } else if (region == 2) { return(uint8(p), v, uint8(t)); } else if (region == 3) { return(uint8(p), uint8(q), v); } else if (region == 4) { return(uint8(t), uint8(p), v); } return(v, uint8(p), uint8(q)); } function reduceColors(bytes20 s0, bytes20 s1, bytes20 s2, uint8 colorCount, uint256 offset) public pure returns (uint8[] memory) { uint8[] memory c3 = new uint8[](colorCount*3); uint256 sum0 = sum_bytes20(s0) + sum_bytes20(s1); uint256 sum2 = sum_bytes20(s2); bytes20 hues = lshift_bytes20(s2, sum2 + (offset*8)); for(uint8 c = 0 ; c < colorCount ; c++) { uint8 h = uint8(hues[c]); uint8 s = map_uint8(uint8((uint256(uint8(hues[c+10])) + sum0*3) % 256), (64+(5-(colorCount/2))*30), 255); uint8 v = map_uint8(h|uint8((uint256(uint8(hues[c+10])) + sum0) % 256), (127+(5-(colorCount/2))*30), 255); h = uint8(map_uint256(h, sum2, sum2+map_uint8(uint8((sum2+sum0)%256),100,240))%256); // h = uint8(map_uint256(h, lh, lh+192)%256); (c3[c*3+0], c3[c*3+1], c3[c*3+2]) = hsvToRgb(h,s,v); } return (c3); } // // From truffle/Assert.sol // MIT Licence // uint8 constant ZERO = uint8(bytes1('0')); uint8 constant A = uint8(bytes1('a')); bytes1 constant MINUS = bytes1('-'); function utoa(uint n) public pure returns (string memory) { return utoa(n, 10); } function utoa(uint n, uint8 radix) public pure returns (string memory) { if (n == 0 || radix < 2 || radix > 16) return '0'; bytes memory bts = new bytes(256); uint i; while (n > 0) { bts[i++] = _utoa(uint8(uint(n % radix))); // Turn it to ascii. n /= radix; } // Reverse bytes memory rev = new bytes(i); for (uint j = 0; j < i; j++) rev[j] = bts[i - j - 1]; return string(rev); } function _utoa(uint8 u) public pure returns (bytes1) { if (u < 10) return bytes1(u + ZERO); else if (u < 16) return bytes1(u - 10 + A); else return 0; } } // 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; 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.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: 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 "./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 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.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.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.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: 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: 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 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 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); } }
public actionsrequire(isOwner(), "CC: Not Contract owner"); Ownable takes care
function giftCode(address to) onlyOwner public returns (uint256) { require(!state_.isReleased, "CC: Token Zero already issued"); require(to == owner(), "CC: Not Contract owner"); return mintCode_( to, 1, true ); }
9,954,279
[ 1, 482, 4209, 6528, 12, 291, 5541, 9334, 315, 6743, 30, 2288, 13456, 3410, 8863, 225, 14223, 6914, 5530, 7671, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 314, 2136, 1085, 12, 2867, 358, 13, 1338, 5541, 1071, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 5, 2019, 27799, 291, 26363, 16, 315, 6743, 30, 3155, 12744, 1818, 16865, 8863, 203, 3639, 2583, 12, 869, 422, 3410, 9334, 315, 6743, 30, 2288, 13456, 3410, 8863, 203, 3639, 327, 312, 474, 1085, 67, 12, 358, 16, 404, 16, 638, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // import "./TokenStake.sol"; contract Atadia is ERC20, Ownable{ constructor() ERC20("Atadia", "ATA"){ _mint(msg.sender, 5000 ); } // Staking Contract Address address stakeContract; // Only the TokenSale contract can mint new tokens. modifier onlyTokenStake { require (msg.sender == stakeContract); _; } function issueToken(address receiver, uint256 amount) external onlyTokenStake returns(bool sent){ _mint(receiver, amount); return true; } /* @dev Set this before making Token sales. This tells our modifier which contract has the right to mint new tokens. */ function setTokenStakeAddress (address _stakeContract) public onlyOwner{ stakeContract = _stakeContract; } } contract DEX is Ownable { // Event that logs sale operation event BuyTokens(address _buyer, uint256 _amountEth, uint256 _amountToken); // rate uint256 public rate = 1000; Atadia public token; address internal _owner; constructor(address ca) { token = Atadia(ca); _owner = msg.sender; } 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, 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; } function buyToken() payable public { require( msg.value > 0, "Your ETH balance is low." ); uint256 base = 1 ether; uint256 amtpayed = div(msg.value, base, "Division by zero error"); uint256 amountToBuy = mul(amtpayed, rate); require(amountToBuy > 0, "Send some ether"); uint256 _balance = token.balanceOf(_owner); require(amountToBuy <= _balance, "Reserve is low"); // Mint new tokens to provided address (bool sent) = token.transferFrom(_owner, msg.sender, amountToBuy); require(sent, "Failed to complete sale"); emit BuyTokens(msg.sender, msg.value, amountToBuy); } function modifyTokenBuyPrice(uint256 _rate) public onlyOwner { rate = _rate; } }
Staking Contract Address
address stakeContract;
13,004,864
[ 1, 510, 6159, 13456, 5267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 384, 911, 8924, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x3Ac99803FDe05F46B467d0D36C3C5326b141cE79/sources/contracts/campaign/TokenRewardCampaignManager.sol
Function to create a new campaign
function createCampaign(address _rewardToken, uint256 _rewardAmount, uint256 _rewardSeats, TokenRewardCampaign.CampaignType _campaignType) public { TokenRewardCampaign newCampaign = new TokenRewardCampaign(msg.sender, _rewardToken, _rewardAmount, _rewardSeats, _campaignType, address(this)); campaigns.push(newCampaign); isCampaign[address(newCampaign)] = true; TransferHelper.safeApprove( _rewardToken, address(newCampaign), _rewardAmount ); TransferHelper.safeTransferFrom( _rewardToken, msg.sender, address(newCampaign), _rewardAmount ); emit CampaignCreated(address(newCampaign)); }
5,569,895
[ 1, 2083, 358, 752, 279, 394, 8965, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 13432, 12, 2867, 389, 266, 2913, 1345, 16, 2254, 5034, 389, 266, 2913, 6275, 16, 2254, 5034, 389, 266, 2913, 1761, 2323, 16, 3155, 17631, 1060, 13432, 18, 13432, 559, 389, 14608, 559, 13, 1071, 288, 203, 3639, 3155, 17631, 1060, 13432, 394, 13432, 273, 394, 3155, 17631, 1060, 13432, 12, 3576, 18, 15330, 16, 389, 266, 2913, 1345, 16, 389, 266, 2913, 6275, 16, 389, 266, 2913, 1761, 2323, 16, 389, 14608, 559, 16, 1758, 12, 2211, 10019, 203, 3639, 8965, 87, 18, 6206, 12, 2704, 13432, 1769, 203, 3639, 353, 13432, 63, 2867, 12, 2704, 13432, 25887, 273, 638, 31, 203, 203, 3639, 12279, 2276, 18, 4626, 12053, 537, 12, 203, 5411, 389, 266, 2913, 1345, 16, 203, 5411, 1758, 12, 2704, 13432, 3631, 203, 5411, 389, 266, 2913, 6275, 203, 3639, 11272, 203, 203, 3639, 12279, 2276, 18, 4626, 5912, 1265, 12, 203, 5411, 389, 266, 2913, 1345, 16, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1758, 12, 2704, 13432, 3631, 203, 5411, 389, 266, 2913, 6275, 203, 3639, 11272, 203, 203, 3639, 3626, 17820, 6119, 12, 2867, 12, 2704, 13432, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @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; } } /** * @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; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @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); } } /** * @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)); } } /** * @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); } } } } /** * @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"); } } } // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferNative(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: Native_TRANSFER_FAILED'); } } /** * @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; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 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 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)); } } /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } contract StakingPool is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _governors; struct UserInfo { uint256 amount; uint256 rewardDebt; uint256 lockAmount; uint256 releaseAmount; } struct PoolInfo { IERC20 lpToken; IERC20 rewardToken; uint256 timeStart; uint256 timeEnd; // bonus tokens for per second. uint256 bonusPerSecond; uint256 lockedSeconds; //after exit stake ,need lock time uint256 lpAmount; uint256 lastRewardTime; uint256 accBonusPerShare; uint256 lpTokenType; //0 indicate normal token, 1 is xtoken IERC20 lpTokenFrom; bool open; //pool status } // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; struct WithdrawOrder { uint256 orderTime; uint256 amount; } mapping(uint256 => mapping(address => WithdrawOrder[])) public userWithdrawInfo; event Deposit(address indexed user, uint256 indexed pid, address token, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, address token, uint256 amount); event WithdrawUnlock(address indexed user, uint256 indexed pid, address token, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event GovernorAdded( address _user); event GovernorDeleted( address _user); bytes32 constant public STAKINGPOOL_CALL_HASH_TYPE = keccak256("withdrawExit(address receiver,uint256 pid,uint256 exitAmount)"); /** * @dev Constructor. */ constructor(){ } function poolLength() external view returns (uint256) { return poolInfo.length; } function getLockLength(uint256 _pid, address _user) public view returns (uint256) { return userWithdrawInfo[_pid][_user].length; } // Add a new staking pool to the pool. Can only be called by the owner. function add( IERC20 _lpToken,IERC20 _rewardToken, uint256 _timeStart, uint256 _timeEnd , uint256 _bonusPerSecond,uint256 _lockedSeconds, uint256 _lpTokenType, IERC20 _lpTokenFrom , bool _open) public onlyGovernor { require( _timeStart > block.timestamp && _timeEnd > _timeStart, "invalid time limit"); poolInfo.push(PoolInfo({ lpToken : _lpToken, rewardToken : _rewardToken, timeStart : _timeStart, timeEnd : _timeEnd, bonusPerSecond : _bonusPerSecond, lockedSeconds : _lockedSeconds, lpAmount : 0, lastRewardTime : _timeStart, accBonusPerShare :0, lpTokenType :_lpTokenType, lpTokenFrom : _lpTokenFrom, open : _open })); //need transfer staking bonus token uint256 _amount = _timeEnd.sub(_timeStart).mul(_bonusPerSecond); TransferHelper.safeTransferFrom( address(_rewardToken), msg.sender, address(this), _amount); } // set staking pool info, only can adjust time where pool is not start harvest. function setPoolInfo( uint256 _pid, uint256 _timeStart, uint256 _timeEnd , uint256 _bonusPerSecond,uint256 _lockedSeconds, uint256 _lpTokenType, IERC20 _lpTokenFrom , bool _open) public onlyGovernor { require( _timeStart > block.timestamp && _timeEnd > _timeStart, "invalid time limit"); PoolInfo storage pool = poolInfo[_pid]; require( pool.timeStart > block.timestamp, "staking is enabled"); require( block.timestamp < pool.timeStart, "pool is mining"); //reward token uint256 _newAmount = _timeEnd.sub(_timeStart).mul(_bonusPerSecond); uint256 _amount = pool.timeEnd.sub(pool.timeStart).mul(pool.bonusPerSecond); if( _newAmount > _amount){ TransferHelper.safeTransferFrom( address(pool.rewardToken), msg.sender, address(this), _newAmount.sub(_amount)); } else if( _newAmount < _amount){ TransferHelper.safeTransfer( address(pool.rewardToken), msg.sender , _amount.sub(_newAmount) ); } pool.timeStart = _timeStart; pool.lastRewardTime = _timeStart; pool.timeEnd = _timeEnd; pool.bonusPerSecond = _bonusPerSecond; pool.lockedSeconds = _lockedSeconds; pool.lpTokenType = _lpTokenType; pool.lpTokenFrom = _lpTokenFrom; pool.open = _open; } //update pool status function setPoolStatus( uint256 _pid, bool _open) public onlyGovernor { PoolInfo storage pool = poolInfo[_pid]; pool.open = _open; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 number = block.timestamp ; if (number <= pool.lastRewardTime) { return; } if( pool.lastRewardTime >= pool.timeEnd){ return; } //set the end time if( number >= pool.timeEnd ){ number = pool.timeEnd; } uint256 lpSupply = pool.lpAmount; if (lpSupply == 0) { pool.lastRewardTime = number; return; } uint256 multiplier = number.sub(pool.lastRewardTime); uint256 bonusReward = multiplier.mul(pool.bonusPerSecond); pool.accBonusPerShare = pool.accBonusPerShare.add(bonusReward.mul(1e12).div(lpSupply)); pool.lastRewardTime = number; } function pending(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBonusPerShare = pool.accBonusPerShare; uint256 lpSupply = pool.lpAmount; uint256 number = block.timestamp; if( number <= pool.timeStart ){ return 0; } if( number > pool.timeEnd ){ number = pool.timeEnd; } if (number > pool.lastRewardTime && lpSupply != 0) { uint256 multiplier = number.sub(pool.lastRewardTime); uint256 bonusReward = multiplier.mul(pool.bonusPerSecond) ; accBonusPerShare = accBonusPerShare.add(bonusReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accBonusPerShare).div(1e12).sub(user.rewardDebt); } // Deposit LP tokens dividends bonus; function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; require( pool.open == true , "pool is closed!"); UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pendingAmount = user.amount.mul(pool.accBonusPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { TransferHelper.safeTransfer( address(pool.rewardToken), msg.sender , pendingAmount ); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); pool.lpAmount = pool.lpAmount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12); emit Deposit(msg.sender, _pid, address(pool.lpToken), _amount); } // Withdraw LP tokens. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pendingAmount = user.amount.mul(pool.accBonusPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { TransferHelper.safeTransfer( address(pool.rewardToken), msg.sender , pendingAmount ); } if (_amount > 0 ) { if( pool.lockedSeconds == 0 ){ user.amount = user.amount.sub(_amount); pool.lpAmount = pool.lpAmount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } else{ user.lockAmount = user.lockAmount.add(_amount); userWithdrawInfo[_pid][msg.sender].push(WithdrawOrder({orderTime: block.timestamp, amount: _amount})); } } user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12); emit Withdraw(msg.sender, _pid, address(pool.lpToken), _amount); } //unlock lp token function pendingUnlock(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 unlockAmount = 0; uint256 checkTime = block.timestamp; if( user.lockAmount > 0 && pool.lockedSeconds > 0){ WithdrawOrder[] memory orders = userWithdrawInfo[_pid][_user]; uint256 len = orders.length; for (uint256 i = 0; i < len; i++) { if( orders[i].orderTime.add(pool.lockedSeconds) <= checkTime ){ unlockAmount = unlockAmount.add( orders[i].amount); } else{ break;//withdraw orders sorted by ordertime asc } } } return unlockAmount; } //withdraw unlock lp function withdrawUnlock(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(pool.lockedSeconds > 0 , "invalid pool"); updatePool(_pid); uint256 unlockAmount = 0; uint256 checkTime = block.timestamp; uint256 index = 0; if( user.lockAmount > 0 && pool.lockedSeconds > 0){ WithdrawOrder[] memory orders = userWithdrawInfo[_pid][msg.sender]; uint256 len = orders.length; if( len > 0 ){ index = len ; for (uint256 i = 0; i < len; i++) { if( orders[i].orderTime.add(pool.lockedSeconds) <= checkTime ){ unlockAmount = unlockAmount.add( orders[i].amount); } else{ index = i; break; } } //pop some orders for (uint256 i = 0; i < len - index; i++) { userWithdrawInfo[_pid][msg.sender][i] = userWithdrawInfo[_pid][msg.sender][i + index]; } for (uint256 j = len -index; j < len ; j++) { userWithdrawInfo[_pid][msg.sender].pop(); } } } uint256 pendingAmount = user.amount.mul(pool.accBonusPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { TransferHelper.safeTransfer( address(pool.rewardToken), msg.sender , pendingAmount ); } if (unlockAmount > 0 ) { user.amount = user.amount.sub(unlockAmount); user.lockAmount = user.lockAmount.sub(unlockAmount); user.releaseAmount = user.releaseAmount.add( unlockAmount ); pool.lpAmount = pool.lpAmount.sub(unlockAmount); pool.lpToken.safeTransfer(address(msg.sender), unlockAmount); } user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12); emit WithdrawUnlock(msg.sender, _pid, address(pool.lpToken), unlockAmount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; if( amount > 0 && pool.lockedSeconds == 0 ){ user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); } emit EmergencyWithdraw(msg.sender, _pid, amount); } //emergency withdraw function withdrawEmergency(address tokenaddress,address to) public onlyOwner{ TransferHelper.safeTransfer( tokenaddress, to , IERC20(tokenaddress).balanceOf(address(this))); } function withdrawEmergencyNative(address to , uint256 amount) public onlyOwner{ TransferHelper.safeTransferNative(to, amount); } //governor function addGovernor(address _governor) public onlyOwner returns (bool) { require(_governor != address(0), "_governor is the zero address"); emit GovernorAdded( _governor ); return EnumerableSet.add(_governors, _governor); } function delGovernor(address _governor) public onlyOwner returns (bool) { require(_governor != address(0), "_governor is the zero address"); emit GovernorDeleted( _governor ); return EnumerableSet.remove(_governors, _governor); } function getGovernorLength() public view returns (uint256) { return EnumerableSet.length(_governors); } function isGovernor(address account) public view returns (bool) { return EnumerableSet.contains(_governors, account); } function getGovernor(uint256 _index) public view returns (address){ require(_index <= getGovernorLength() - 1, "index out of bounds"); return EnumerableSet.at(_governors, _index); } // modifier for governor function modifier onlyGovernor() { require(isGovernor(msg.sender) || owner() == msg.sender , "caller is not the governor"); _; } }
* @dev Constructor./
constructor(){ }
1,287,505
[ 1, 6293, 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 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 95, 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 ]
./partial_match/1/0x508efB44A06a64Bd4020e8c5e8Ecf1A9236C75aE/sources/wallet.sol
pos += 20 + 32 + 32 + dataLength, reverts in case of overflow
pos = pos.add(dataLength).add(84);
3,597,917
[ 1, 917, 1011, 4200, 397, 3847, 397, 3847, 397, 27972, 16, 15226, 87, 316, 648, 434, 9391, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 949, 273, 949, 18, 1289, 12, 892, 1782, 2934, 1289, 12, 5193, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-10-29 */ /* Keep4r 1 kp4r.network - 2020 */ pragma solidity 0.6.6; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } 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; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } contract Keep4rPresale { using SafeMath for uint256; // cannot purchase until started bool internal started; IERC20 KP4R; address kp4rAddress; address internal manager; address internal managerPending; uint256 constant managerS = 80; uint256 internal managerWithdrawn; address internal overseer; address internal overseerPending; uint256 constant overseerS = 20; uint256 internal overseerWithdrawn; uint256 internal unitPrice = 1e18/2; uint256 internal minimumOrder = 100000; /** @notice the date when purchased KP4R can be claimed */ uint256 internal unlocksOn; /** @notice the date when KP4R can no longer be purchased from the contract */ uint256 internal endsOn; /** @notice percentage bonus actived upon purchasing more than the trigger * value. */ uint256 internal bonusTrigger; uint256 internal bonusPercentage; // Stats: uint256 internal totalForSale; uint256 internal totalSold; uint256 internal totalSettled; uint256 internal weiRaised; mapping(address => uint256) internal balance; event Purchase (address indexed buyer, uint256 amount, uint256 price); constructor(address _kp4r) public { manager = msg.sender; overseer = msg.sender; KP4R = IERC20(_kp4r); kp4rAddress = _kp4r; } modifier onlyManager { require( msg.sender == manager, "Only the manager can call this function." ); _; } modifier onlyOverseer { require( msg.sender == overseer, "Only the overseer can call this function."); _; } function transferRole(address _new) public { require(msg.sender == manager || msg.sender == overseer, "!manager or overseer"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (msg.sender == manager) { managerPending = _new; return; } //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (msg.sender == overseer) { overseerPending = _new; return; } //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function acceptRole() public { require(msg.sender == managerPending || msg.sender == overseerPending, "!managerPending or overseerPending"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (msg.sender == managerPending) { manager = managerPending; managerPending = address(0); return; } //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (msg.sender == overseerPending) { overseer = overseerPending; managerPending = address(0); return; } //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function managerSetPrice(uint256 _price) public onlyManager { unitPrice = _price; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function managerSetMinimum(uint256 _minimum) public onlyManager { minimumOrder = _minimum; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function managerSetBonus(uint256 _trigger, uint256 _percentage) public onlyManager { bonusTrigger = _trigger; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC bonusPercentage = _percentage; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function managerDeposit(uint256 _amount) public onlyManager { KP4R.transferFrom(msg.sender, address(this), _amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC totalForSale = totalForSale.add(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** @notice manager can reclaim unsold tokens */ function managerReclaim(uint256 _amount) public onlyManager { // calculate the amount of tokens that haven not been sold // and settled and are thus reclaimable: uint256 unreclaimable = totalSold.sub(totalSettled); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint256 reclaimable = KP4R.balanceOf(address(this)).sub(unreclaimable); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(_amount <= reclaimable, "cannot withdraw already sold tokens"); // transfer the tokens to the manager KP4R.transfer(msg.sender, _amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC totalForSale = totalForSale.sub(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function managerWithdraw(uint256 _amount) public onlyManager { require(managerWithdrawn.add(_amount) <= weiRaised.mul(managerS).div(100), "cannot withdraw more than the managers share"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC managerWithdrawn = managerWithdrawn.add(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC msg.sender.transfer(_amount); } function overseerWithdraw(uint _amount) public onlyOverseer { require(overseerWithdrawn.add(_amount) <= weiRaised.mul(overseerS).div(100), "cannot withdraw more than overseerS"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC overseerWithdrawn = overseerWithdrawn.add(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC msg.sender.transfer(_amount); } function managerClose(uint256 amount) public onlyManager { require(block.timestamp > endsOn.add(31536000).mul(2), "must wait until 6 months past end date"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC msg.sender.transfer(amount); } function managerForceUnlock() public onlyManager { unlocksOn = block.timestamp-1; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function start(uint256 _unlocksOn, uint256 _endsOn, uint256 _price, uint256 _minimumOrder) public onlyManager { require(!started, "already started"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC unlocksOn = _unlocksOn; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC endsOn = _endsOn; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC unitPrice = _price; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC minimumOrder = _minimumOrder; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC started = true; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** @notice The amount of KP4R remaining */ function remaining() public view returns (uint256) { return KP4R.balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** @notice purchase KP4R at the current unit price */ function purchase() public payable { require(started, "token sale has not yet started"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(msg.value > minimumOrder, "amount purchased is too small"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(block.timestamp < endsOn, "presale has ended"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC // calculate the amount of KP4R purchasable uint256 _kp4r = calculateAmountPurchased(msg.value); require(_kp4r <= KP4R.balanceOf(address(this)), "not enough KP4R left"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC // update the users balance balance[msg.sender] = balance[msg.sender].add(_kp4r); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC totalSold = totalSold.add(_kp4r); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC weiRaised = weiRaised.add(msg.value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit Purchase(msg.sender, _kp4r, msg.value); } /** @notice calculates the amount purchasedfor a given amount of eth */ function calculateAmountPurchased(uint256 _value) public view returns (uint256) { uint256 _kp4r = _value.div(unitPrice).mul(1e18); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_value > bonusTrigger) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint256 _bonus = _kp4r.mul(bonusPercentage).div(1000); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_kp4r.add(_bonus) <= KP4R.balanceOf(address(this))) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _kp4r = _kp4r.add(_bonus); } } return _kp4r; } /** @notice claim you eth */ function claim() public { require(block.timestamp > unlocksOn, "presale has not unlocked yet"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(balance[msg.sender] > 0, "nothing to withdraw"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC KP4R.transfer(msg.sender, balance[msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC totalSettled = totalSettled.add(balance[msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } // fallbacks to allow users to send to the contract to purchase KP4R receive() external payable { purchase(); } fallback() external payable { purchase(); } }
inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(msg.sender == manager || msg.sender == overseer, "!manager or overseer");
7,284,160
[ 1, 22170, 18708, 14939, 8350, 13255, 40, 6953, 17187, 478, 21163, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 3576, 18, 15330, 422, 3301, 747, 1234, 18, 15330, 422, 1879, 307, 264, 16, 17528, 4181, 578, 1879, 307, 264, 8863, 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 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "hardhat/console.sol"; contract WavePortal { uint256 totalWaves; uint256 private seed; // Emit a new wave event when a wave happens event NewWave(address indexed from, uint256 timestamp, string message); struct Wave{ address waver; // address of the user who waved. string message; // message sent by the user who waved. uint256 timestamp; //timestamp when the user waved. } // Array of waves. Holds all the waves anyone ever sent to us. Wave[] waves; // Address to timestamp mapping for implementing cooldown. mapping(address => uint256) public lastWavedAt; constructor() payable { console.log("Wave Portal smart contract"); // Generates a new seed for the next user that sends a wave to us seed = (block.timestamp * block.difficulty + seed) % 100; } function wave(string memory _msg) public { // Assert that the sender is not bombarding the contract. Cooldown for avoiding spam-waving. require(lastWavedAt[msg.sender] + 30 seconds < block.timestamp, "Wait for 30 seconds before waving again"); // Update the current timestamp for the sender of the wave. lastWavedAt[msg.sender] = block.timestamp; totalWaves += 1; // Its like built in-authentication. We know exactly who called the function because in order to even call a smart contract funciton, // you need to be connected with a valid wallet. console.log("%s has waved!", msg.sender); // current block timestamp in seconds waves.push(Wave(msg.sender, _msg, block.timestamp)); // Everytime generate a new seed seed = (block.difficulty + block.timestamp + seed) % 100; console.log("Random # generated : %d", seed); if(seed <= 50) { // Send prize amount to whoever waves at you. uint256 prizeAmount = 0.0001 ether; // address(this).balance lets retrieve the balance of the contract itself. require(prizeAmount <= address(this).balance, "Trying to withdraw more money than the contract has"); // Send the value to the sender (bool success, ) = (msg.sender).call{value: prizeAmount}(""); require(success, "Failed to withdraw money from contract"); console.log("%s won the prize!", msg.sender); } emit NewWave(msg.sender, block.timestamp, _msg); } function getAllWaves() public view returns (Wave[] memory) { return waves; } function getTotalWaves() public view returns(uint256) { console.log("We have %d total waves!", totalWaves); return totalWaves; } }
Assert that the sender is not bombarding the contract. Cooldown for avoiding spam-waving. Update the current timestamp for the sender of the wave. Its like built in-authentication. We know exactly who called the function because in order to even call a smart contract funciton, you need to be connected with a valid wallet. current block timestamp in seconds Everytime generate a new seed Send prize amount to whoever waves at you. address(this).balance lets retrieve the balance of the contract itself. Send the value to the sender
function wave(string memory _msg) public { require(lastWavedAt[msg.sender] + 30 seconds < block.timestamp, "Wait for 30 seconds before waving again"); lastWavedAt[msg.sender] = block.timestamp; totalWaves += 1; console.log("%s has waved!", msg.sender); waves.push(Wave(msg.sender, _msg, block.timestamp)); seed = (block.difficulty + block.timestamp + seed) % 100; console.log("Random # generated : %d", seed); if(seed <= 50) { uint256 prizeAmount = 0.0001 ether; require(prizeAmount <= address(this).balance, "Trying to withdraw more money than the contract has"); require(success, "Failed to withdraw money from contract"); console.log("%s won the prize!", msg.sender); } emit NewWave(msg.sender, block.timestamp, _msg); }
1,848,835
[ 1, 8213, 716, 326, 5793, 353, 486, 324, 16659, 1060, 310, 326, 6835, 18, 385, 1371, 2378, 364, 4543, 310, 24824, 17, 91, 5339, 18, 2315, 326, 783, 2858, 364, 326, 5793, 434, 326, 10794, 18, 29517, 3007, 6650, 316, 17, 12293, 18, 1660, 5055, 8950, 10354, 2566, 326, 445, 2724, 316, 1353, 358, 5456, 745, 279, 13706, 6835, 1326, 26949, 16, 1846, 1608, 358, 506, 5840, 598, 279, 923, 9230, 18, 783, 1203, 2858, 316, 3974, 16420, 957, 2103, 279, 394, 5009, 2479, 846, 554, 3844, 358, 10354, 6084, 341, 6606, 622, 1846, 18, 1758, 12, 2211, 2934, 12296, 14557, 4614, 326, 11013, 434, 326, 6835, 6174, 18, 2479, 326, 460, 358, 326, 5793, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10794, 12, 1080, 3778, 389, 3576, 13, 1071, 288, 203, 3639, 2583, 12, 2722, 59, 8158, 861, 63, 3576, 18, 15330, 65, 397, 5196, 3974, 411, 1203, 18, 5508, 16, 315, 5480, 364, 5196, 3974, 1865, 341, 5339, 3382, 8863, 203, 203, 3639, 1142, 59, 8158, 861, 63, 3576, 18, 15330, 65, 273, 1203, 18, 5508, 31, 203, 3639, 2078, 59, 6606, 1011, 404, 31, 203, 3639, 2983, 18, 1330, 27188, 87, 711, 341, 8158, 5, 3113, 1234, 18, 15330, 1769, 203, 203, 3639, 341, 6606, 18, 6206, 12, 22368, 12, 3576, 18, 15330, 16, 389, 3576, 16, 1203, 18, 5508, 10019, 203, 203, 3639, 5009, 273, 261, 2629, 18, 5413, 21934, 397, 1203, 18, 5508, 397, 5009, 13, 738, 2130, 31, 203, 3639, 2983, 18, 1330, 2932, 8529, 468, 4374, 294, 738, 72, 3113, 5009, 1769, 203, 3639, 309, 12, 12407, 1648, 6437, 13, 288, 203, 5411, 2254, 5034, 846, 554, 6275, 273, 374, 18, 13304, 225, 2437, 31, 203, 5411, 2583, 12, 683, 554, 6275, 1648, 1758, 12, 2211, 2934, 12296, 16, 315, 18038, 358, 598, 9446, 1898, 15601, 2353, 326, 6835, 711, 8863, 203, 5411, 2583, 12, 4768, 16, 315, 2925, 358, 598, 9446, 15601, 628, 6835, 8863, 203, 5411, 2983, 18, 1330, 27188, 87, 8462, 326, 846, 554, 5, 3113, 1234, 18, 15330, 1769, 203, 3639, 289, 203, 3639, 3626, 1166, 22368, 12, 3576, 18, 15330, 16, 1203, 18, 5508, 16, 389, 3576, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } // File: openzeppelin-solidity/contracts/ownership/HasNoEther.sol /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be sent to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ constructor() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { owner.transfer(this.balance); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @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/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @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/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/ChartToken.sol contract ChartToken is StandardToken, BurnableToken, Ownable, HasNoEther { string public constant name = "BetOnChart token"; string public constant symbol = "CHART"; uint8 public constant decimals = 18; // 1 ether bool public saleFinished; address public saleAgent; address private wallet; /** * @dev Event should be emited when sale agent changed */ event SaleAgent(address); /** * @dev ChartToken constructor * All tokens supply will be assign to contract owner. * @param _wallet Wallet to handle initial token emission. */ constructor(address _wallet) public { require(_wallet != address(0)); totalSupply_ = 50*1e6*(1 ether); saleFinished = false; balances[_wallet] = totalSupply_; wallet = _wallet; saleAgent = address(0); } /** * @dev Modifier to make a function callable only by owner or sale agent. */ modifier onlyOwnerOrSaleAgent() { require(msg.sender == owner || msg.sender == saleAgent); _; } /** * @dev Modifier to make a function callable only when a sale is finished. */ modifier whenSaleFinished() { require(saleFinished || msg.sender == saleAgent || msg.sender == wallet ); _; } /** * @dev Modifier to make a function callable only when a sale is not finished. */ modifier whenSaleNotFinished() { require(!saleFinished); _; } /** * @dev Set sale agent * @param _agent The agent address which you want to set. */ function setSaleAgent(address _agent) public whenSaleNotFinished onlyOwner { saleAgent = _agent; emit SaleAgent(_agent); } /** * @dev Handle ICO end */ function finishSale() public onlyOwnerOrSaleAgent { saleAgent = address(0); emit SaleAgent(saleAgent); saleFinished = true; } /** * @dev Overrides default ERC20 */ function transfer(address _to, uint256 _value) public whenSaleFinished returns (bool) { return super.transfer(_to, _value); } /** * @dev Overrides default ERC20 */ function transferFrom(address _from, address _to, uint256 _value) public whenSaleFinished returns (bool) { return super.transferFrom(_from, _to, _value); } } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.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 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 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: contracts/lib/TimedCrowdsale.sol /** * @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 { 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: contracts/lib/WhitelistedCrowdsale.sol /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; /** * @dev Minimal contract to whitelisted addresses */ struct Contract { uint256 rate; // Token rate uint256 minInvestment; // Minimal investment } mapping(address => bool) public whitelist; mapping(address => Contract) public contracts; /** * @dev Reverts if beneficiary is not whitelisted. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Reverts if beneficiary is not invests minimal ether amount. */ modifier isMinimalInvestment(address _beneficiary, uint256 _weiAmount) { require(_weiAmount >= contracts[_beneficiary].minInvestment); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist * @param _bonus Token bonus from 0% to 300% * @param _minInvestment Minimal investment */ function addToWhitelist(address _beneficiary, uint16 _bonus, uint256 _minInvestment) external onlyOwner { require(_bonus <= 300); whitelist[_beneficiary] = true; Contract storage beneficiaryContract = contracts[_beneficiary]; beneficiaryContract.rate = rate.add(rate.mul(_bonus).div(100)); beneficiaryContract.minInvestment = _minInvestment.mul(1 ether); } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist * @param _bonus Token bonus from 0% to 300% * @param _minInvestment Minimal investment */ function addManyToWhitelist(address[] _beneficiaries, uint16 _bonus, uint256 _minInvestment) external onlyOwner { require(_bonus <= 300); for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; Contract storage beneficiaryContract = contracts[_beneficiaries[i]]; beneficiaryContract.rate = rate.add(rate.mul(_bonus).div(100)); beneficiaryContract.minInvestment = _minInvestment.mul(1 ether); } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal isWhitelisted(_beneficiary) isMinimalInvestment(_beneficiary, _weiAmount) { super._preValidatePurchase(_beneficiary, _weiAmount); } /** * @dev The way in which ether is converted to tokens. Overrides default function. * @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(contracts[msg.sender].rate); } } // File: openzeppelin-solidity/contracts/crowdsale/emission/AllowanceCrowdsale.sol /** * @title AllowanceCrowdsale * @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale. */ contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; address public tokenWallet; /** * @dev Constructor, takes token wallet address. * @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale */ constructor(address _tokenWallet) public { require(_tokenWallet != address(0)); tokenWallet = _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return token.allowance(tokenWallet, this); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transferFrom(tokenWallet, _beneficiary, _tokenAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } // File: contracts/ChartPresale.sol contract ChartPresale is WhitelistedCrowdsale, AllowanceCrowdsale, TimedCrowdsale, CappedCrowdsale { using SafeMath for uint256; string public constant name = "BetOnChart token presale"; constructor(uint256 _rate, address _tokenWallet, address _ethWallet, ChartToken _token, uint256 _cap, uint256 _openingTime, uint256 _closingTime) public Crowdsale(_rate, _ethWallet, _token) AllowanceCrowdsale(_tokenWallet) TimedCrowdsale(_openingTime, _closingTime) CappedCrowdsale(_cap) {} }
* @dev Extend parent behavior requiring beneficiary to be in whitelist. @param _beneficiary Token beneficiary @param _weiAmount Amount of wei contributed/
function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal isWhitelisted(_beneficiary) isMinimalInvestment(_beneficiary, _weiAmount) { super._preValidatePurchase(_beneficiary, _weiAmount); }
1,221,715
[ 1, 16675, 982, 6885, 29468, 27641, 74, 14463, 814, 358, 506, 316, 10734, 18, 225, 389, 70, 4009, 74, 14463, 814, 3155, 27641, 74, 14463, 814, 225, 389, 1814, 77, 6275, 16811, 434, 732, 77, 356, 11050, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1484, 4270, 23164, 12, 203, 3639, 1758, 389, 70, 4009, 74, 14463, 814, 16, 203, 3639, 2254, 5034, 389, 1814, 77, 6275, 203, 565, 262, 203, 565, 2713, 203, 565, 353, 18927, 329, 24899, 70, 4009, 74, 14463, 814, 13, 203, 565, 353, 2930, 2840, 3605, 395, 475, 24899, 70, 4009, 74, 14463, 814, 16, 389, 1814, 77, 6275, 13, 203, 565, 288, 203, 3639, 2240, 6315, 1484, 4270, 23164, 24899, 70, 4009, 74, 14463, 814, 16, 389, 1814, 77, 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 ]
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require (msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { owner = newOwner; } } contract PowerBall is owned { using Strings for string; using SafeMath for uint256; struct Ticket { address player; uint32 drawDate; uint64 price; uint8 ball1; uint8 ball2; uint8 ball3; uint8 ball4; uint8 redBall; } struct Draws{ uint32 count; uint32[500000] tickets; } struct CurrentPrizes{ address special; address first; address second; address third; } struct Prize{ address[] winners; uint amout; } struct LotteryResults{ Prize special; Prize first; Prize second; Prize third; uint8[5] result; bool hadDraws; bool hadAward; } struct TicketInfo{ uint64 priceTicket; uint8 specialPrize; uint8 firstPrize; uint8 secondPrize; uint8 thirdPrize; uint8 commission; uint8 sales; } TicketInfo public ticketInfo; CurrentPrizes public prizes; address SystemSale; mapping(address => uint256) private balances; mapping (uint => Ticket) private tickets; mapping (uint32 => Draws) _draws; mapping (uint32 => LotteryResults) _results; uint32 idTicket; event logBuyTicketSumary( address user, uint32[] ticketId, uint drawDate ); event logGetPrize( string prize, uint drawDate, uint amout, address[] winners, uint8[5] result ); event logAward( string prize, uint drawDate, uint amout, address[] winners, uint8[5] result ); event logWithdraw( address account, uint amout ); constructor() public{ ticketInfo.priceTicket = 10000; //10 GM ticketInfo.specialPrize = 30; //30 percent ticketInfo.firstPrize = 2; //2 percent ticketInfo.secondPrize = 5; //5 percent ticketInfo.thirdPrize = 8; //8 percent ticketInfo.commission = 10; //10 percent ticketInfo.sales = 45; //45 percent prizes.special = 0x374cC1ed754A448276380872786659ab532CD7fC; //account 3 prizes.first = 0xF73823D62f8006E8cBF39Ba630479EFDA59419C9; //account 4 prizes.second = 0x0b744af1F0E55AFBeAb8212B00bBf2586F0EBB8F; //account 5 prizes.third = 0x6dD465891AcB3570F122f5E7E52eeAA406992Dcf; //account 6 SystemSale = 0xbD6E06b04c2582c4373741ef6EDf39AB37Eb964C; //account 8 } function setTicketInfo( uint64 _priceTicket, uint8 _specialPrize, uint8 _firstPrize, uint8 _secondPrize, uint8 _thirdPrize, uint8 _commission, uint8 _sales ) public onlyOwner { ticketInfo.priceTicket = _priceTicket; ticketInfo.specialPrize = _specialPrize; ticketInfo.firstPrize = _firstPrize; ticketInfo.secondPrize = _secondPrize; ticketInfo.thirdPrize = _thirdPrize; ticketInfo.commission = _commission; ticketInfo.sales = _sales; } function cumulativeAward(uint _special, uint _first, uint _second, uint _third) public onlyOwner { setBalance(prizes.special,_special); setBalance(prizes.first,_first); setBalance(prizes.second,_second); setBalance(prizes.third,_third); } /** * @dev giveTickets buy ticket and give it to another player * @param _user The address of the player that will receive the ticket. * @param _drawDate The draw date of tickets. * @param _balls The ball numbers of the tickets. */ function giveTickets(address _user,uint32 _drawDate, uint8[] _balls) onlyOwner public { require(!_results[_drawDate].hadDraws); uint32[] memory _idTickets = new uint32[](_balls.length/5); uint32 id = idTicket; for(uint8 i = 0; i< _balls.length; i+=5){ require(checkRedBall(_balls[i+4])); require(checkBall(_balls[i])); require(checkBall(_balls[i+1])); require(checkBall(_balls[i+2])); require(checkBall(_balls[i+3])); id++; tickets[id].player = _user; tickets[id].drawDate = _drawDate; tickets[id].price = ticketInfo.priceTicket; tickets[id].redBall = _balls[i+4]; tickets[id].ball1 = _balls[i]; tickets[id].ball2 = _balls[i + 1]; tickets[id].ball3 = _balls[i +2]; tickets[id].ball4 = _balls[i + 3]; _draws[_drawDate].tickets[_draws[_drawDate].count] = id; _draws[_drawDate].count ++; _idTickets[i/5] = id; } idTicket = id; emit logBuyTicketSumary(_user,_idTickets,_drawDate); } /** * @dev addTickets allow admin add ticket to player for buy ticket fail * @param _user The address of the player that will receive the ticket. * @param _drawDate The draw date of tickets. * @param _balls The ball numbers of the tickets. * @param _price The price of the tickets. */ function addTickets(address _user,uint32 _drawDate, uint64 _price, uint8[] _balls) onlyOwner public { require(!_results[_drawDate].hadDraws); uint32[] memory _idTickets = new uint32[](_balls.length/5); uint32 id = idTicket; for(uint8 i = 0; i< _balls.length; i+=5){ require(checkRedBall(_balls[i+4])); require(checkBall(_balls[i])); require(checkBall(_balls[i+1])); require(checkBall(_balls[i+2])); require(checkBall(_balls[i+3])); id++; tickets[id].player = _user; tickets[id].drawDate = _drawDate; tickets[id].price = _price; tickets[id].redBall = _balls[i+4]; tickets[id].ball1 = _balls[i]; tickets[id].ball2 = _balls[i + 1]; tickets[id].ball3 = _balls[i +2]; tickets[id].ball4 = _balls[i + 3]; _draws[_drawDate].tickets[_draws[_drawDate].count] = id; _draws[_drawDate].count ++; _idTickets[i/5] = id; } idTicket = id; emit logBuyTicketSumary(_user,_idTickets,_drawDate); } function checkBall(uint8 ball) private pure returns (bool){ return ball > 0 && ball <= 70; } function checkRedBall(uint8 ball) private pure returns (bool){ return ball > 0 && ball <= 26; } /** * @dev doDraws buy ticket and give it to another player * @param _drawDate The draw date of tickets. * @param _result The result of draw. */ function doDraws(uint32 _drawDate, uint8[5] _result) public onlyOwner returns (bool success) { require (_draws[_drawDate].count > 0); require(!_results[_drawDate].hadDraws); _results[_drawDate].hadDraws =true; for(uint32 i=0; i<_draws[_drawDate].count;i++){ uint8 _prize = checkTicket(_draws[_drawDate].tickets[i],_result); if(_prize==5){ //special _results[_drawDate].special.winners.push(address(0)); _results[_drawDate].special.winners[_results[_drawDate].special.winners.length-1] = tickets[_draws[_drawDate].tickets[i]].player; }else if(_prize == 4){ //First _results[_drawDate].first.winners.push(address(0)); _results[_drawDate].first.winners[_results[_drawDate].first.winners.length-1] = tickets[_draws[_drawDate].tickets[i]].player; }else if(_prize == 3){ //Second _results[_drawDate].second.winners.push(address(0)); _results[_drawDate].second.winners[_results[_drawDate].second.winners.length-1] = tickets[_draws[_drawDate].tickets[i]].player; }else if(_prize == 2){ //Third _results[_drawDate].third.winners.push(address(0)); _results[_drawDate].third.winners[_results[_drawDate].third.winners.length-1] = tickets[_draws[_drawDate].tickets[i]].player; } } _results[_drawDate].result =_result; setAmoutPrize(_drawDate,_result); return true; } function setDrawsResult(uint32 _drawDate, uint8[5] _result,address[] _special, address[] _first, address[] _second, address[] _third) public onlyOwner returns (bool success) { require (_draws[_drawDate].count > 0); require(!_results[_drawDate].hadDraws); _results[_drawDate].hadDraws =true; _results[_drawDate].special.winners = _special; _results[_drawDate].first.winners = _first; _results[_drawDate].second.winners = _second; _results[_drawDate].third.winners = _third; _results[_drawDate].result =_result; setAmoutPrize(_drawDate,_result); return true; } function doAward(uint32 _drawDate) public onlyOwner { require(_results[_drawDate].hadDraws); require(!_results[_drawDate].hadAward); //uint revenue = getRevenue(_drawDate); uint _prize=0; if(_results[_drawDate].special.winners.length>0){ _prize = _results[_drawDate].special.amout / _results[_drawDate].special.winners.length; for(uint i=0;i< _results[_drawDate].special.winners.length; i++){ transfer(_results[_drawDate].special.winners[i], _prize); } emit logAward( "Special prize", _drawDate, _prize, _results[_drawDate].special.winners, _results[_drawDate].result ); } if( _results[_drawDate].first.winners.length > 0){ _prize = _results[_drawDate].first.amout / _results[_drawDate].first.winners.length; for(i=0;i< _results[_drawDate].first.winners.length; i++){ transfer(_results[_drawDate].first.winners[i], _prize); } emit logAward( "First prize", _drawDate, _prize, _results[_drawDate].first.winners, _results[_drawDate].result ); } if( _results[_drawDate].second.winners.length > 0){ _prize = _results[_drawDate].second.amout / _results[_drawDate].second.winners.length; for(i=0;i< _results[_drawDate].second.winners.length; i++){ transfer(_results[_drawDate].second.winners[i], _prize); } emit logAward( "Second prize", _drawDate, _prize, _results[_drawDate].second.winners, _results[_drawDate].result ); } if( _results[_drawDate].third.winners.length > 0){ _prize = _results[_drawDate].third.amout / _results[_drawDate].third.winners.length; for(i=0;i< _results[_drawDate].third.winners.length; i++){ transfer(_results[_drawDate].third.winners[i], _prize); } emit logAward( "Third prize", _drawDate, _prize, _results[_drawDate].third.winners, _results[_drawDate].result ); } _results[_drawDate].hadAward = true; } function getRevenue(uint32 _drawDate) private view returns(uint _revenue){ for(uint i=0; i< _draws[_drawDate].count; i++){ _revenue += tickets[_draws[_drawDate].tickets[i]].price; } } function resetDraws(uint32 _drawDate) onlyOwner public { require(_results[_drawDate].hadDraws); require(!_results[_drawDate].hadAward); delete _results[_drawDate]; } function setAmoutPrize(uint32 _drawDate,uint8[5] _result) private { //send coin to prize wallets uint revenue = getRevenue(_drawDate); uint _prizeAmout; //send value to system sale transfer(SystemSale,(revenue * ticketInfo.sales / 100)); //if had special prize _prizeAmout = (revenue * ticketInfo.specialPrize / 100); if( _results[_drawDate].special.winners.length == 0){ transfer(prizes.special,_prizeAmout); }else{ _results[_drawDate].special.amout = _prizeAmout + balanceOf(prizes.special); clear(prizes.special); emit logGetPrize( "Special", _drawDate, _results[_drawDate].special.amout, _results[_drawDate].special.winners, _result ); } //if had First prize _prizeAmout = (revenue * ticketInfo.firstPrize / 100); if( _results[_drawDate].first.winners.length == 0){ transfer(prizes.first,_prizeAmout); }else{ _results[_drawDate].first.amout = _prizeAmout + balanceOf(prizes.first); clear(prizes.first); emit logGetPrize( "First prize", _drawDate, _results[_drawDate].first.amout, _results[_drawDate].first.winners, _result ); } //if had seconds prize _prizeAmout = (revenue * ticketInfo.secondPrize / 100); if( _results[_drawDate].second.winners.length == 0){ transfer(prizes.second,_prizeAmout); }else{ _results[_drawDate].second.amout = _prizeAmout + balanceOf(prizes.second); clear(prizes.second); emit logGetPrize( "Second prize", _drawDate, _results[_drawDate].second.amout, _results[_drawDate].second.winners, _result ); } //if had third prize _prizeAmout = (revenue * ticketInfo.thirdPrize / 100); if( _results[_drawDate].third.winners.length == 0){ transfer(prizes.third,_prizeAmout); }else{ _results[_drawDate].third.amout = _prizeAmout + balanceOf(prizes.third); clear(prizes.third); emit logGetPrize( "Third prize", _drawDate, _results[_drawDate].third.amout, _results[_drawDate].third.winners, _result ); } } function checkTicket(uint32 _ticketId, uint8[5] _result) private view returns(uint8 _prize) { //check red ball if(_result[4] != tickets[_ticketId].redBall){ _prize = 0; return _prize; } _prize = 1; //check white ball 1 for(uint8 i=0;i<4; i++){ if(_result[i] == tickets[_ticketId].ball1){ _prize ++; break; } } //check white ball 2 for(i=0;i<4; i++){ if(_result[i] == tickets[_ticketId].ball2){ _prize ++; break; } } //check white ball 3 for(i=0;i<4; i++){ if(_result[i] == tickets[_ticketId].ball3){ _prize ++; break; } } //check white ball 4 for(i=0;i<4; i++){ if(_result[i] == tickets[_ticketId].ball4){ _prize ++; break; } } return _prize; } function viewResult(uint32 _drawDate) public view returns(uint _revenue, string _special, string _first, string _second,string _third, string _result, bool _wasDrawn, bool _wasAwarded) { LotteryResults memory dr = _results[_drawDate]; uint8 i; _revenue = getRevenue(_drawDate); _special = _special.add(uint2str(dr.special.amout)).add(" / ").add(uint2str(dr.special.winners.length)); _first = _first.add(uint2str(dr.first.amout)).add(" / ").add(uint2str(dr.first.winners.length)); _second = _second.add(uint2str(dr.second.amout)).add(" / ").add(uint2str(dr.second.winners.length)); _third = _third.add(uint2str(dr.third.amout)).add(" / ").add(uint2str(dr.third.winners.length)); for(i=0; i< dr.result.length; i++){ _result = _result.append(uint2str(dr.result[i])); } _wasDrawn = dr.hadDraws; _wasAwarded = dr.hadAward; } function ViewCumulativeAward() public view returns(uint _special, uint _first, uint _second, uint _third) { _special = balanceOf(prizes.special); _first = balanceOf(prizes.first); _second = balanceOf(prizes.second); _third = balanceOf(prizes.third); } function viewTicketsInRound(uint32 _drawDate) public view returns (uint32 _count, string _tickets, uint _revenue) { _count = _draws[_drawDate].count; for(uint i=0; i< _count;i++){ _tickets = _tickets.append(uint2str(_draws[_drawDate].tickets[i])); _revenue+= tickets[_draws[_drawDate].tickets[i]].price; } return (_count,_tickets,_revenue); } function ticketsOfPlayer(address _player, uint32 _drawDate) public view returns (uint32 _count, string _tickets) { for(uint i=0; i< _draws[_drawDate].count;i++){ if(tickets[_draws[_drawDate].tickets[i]].player == _player){ _count++; _tickets = _tickets.append(uint2str(_draws[_drawDate].tickets[i])); } } return (_count,_tickets); } function ticket(uint _ticketID) public view returns(address _player, uint32 _drawDate, uint64 _price, string _balls) { _player = tickets[_ticketID].player; _drawDate = tickets[_ticketID].drawDate; _price = tickets[_ticketID].price; _balls = _balls.append(uint2str(tickets[_ticketID].ball1)) .append(uint2str(tickets[_ticketID].ball2)) .append(uint2str(tickets[_ticketID].ball3)) .append(uint2str(tickets[_ticketID].ball4)); _balls = _balls.append(uint2str(tickets[_ticketID].redBall)); } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer( address _to, uint256 _value) private returns (bool) { require(_to != address(0)); balances[_to] = balances[_to].add(_value); return true; } /** * @dev setBalance token for a specified address * @param _to The address to set balances to. * @param _value The amount to be set balances. */ function setBalance( address _to, uint256 _value) private returns (bool) { require(_to != address(0)); balances[_to] = _value; return true; } /** * @dev withdraw token for a specified address * @param _from The address to withdraw from. * @param _value The amount to be withdraw. */ function withdraw( address _from, uint256 _value) public onlyOwner returns (bool) { require(_from != address(0)); balances[_from] = balances[_from].sub(_value); emit logWithdraw(_from, _value); return true; } /** * @dev clear reset token for a specified address to zero * @param _from The address to withdraw from. */ function clear( address _from) private onlyOwner returns (bool) { require(_from != address(0)); balances[_from] = 0; return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } library Strings { function append(string _base, string _value) internal pure returns (string) { return string(abi.encodePacked(_base,"[",_value,"]"," ")); } function add(string _base, string _value) internal pure returns (string) { return string(abi.encodePacked(_base,_value," ")); } }
* @dev withdraw token for a specified address @param _from The address to withdraw from. @param _value The amount to be withdraw./
returns (bool) { require(_from != address(0)); balances[_from] = balances[_from].sub(_value); emit logWithdraw(_from, _value); return true; }
6,407,754
[ 1, 1918, 9446, 1147, 364, 279, 1269, 1758, 225, 389, 2080, 1021, 1758, 358, 598, 9446, 628, 18, 225, 389, 1132, 1021, 3844, 358, 506, 598, 9446, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 2080, 480, 1758, 12, 20, 10019, 203, 202, 202, 70, 26488, 63, 67, 2080, 65, 273, 324, 26488, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 202, 202, 18356, 613, 1190, 9446, 24899, 2080, 16, 389, 1132, 1769, 203, 3639, 327, 638, 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 ]
./partial_match/3/0xf9DeFC04A80F53074D55999DCCFFB1185bb388d8/sources/NNT3_Exchange.sol
require(_tokensToSell <= tokenSupply_);
function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { uint256 _tokenToBurn=_tokensToSell*burnpercent/100; if(_tokenToBurn ==0) { _tokenToBurn=1; } uint256 _tokenTosellOut = SafeMath.sub(_tokensToSell, _tokenToBurn); uint256 _ethereum = getTokensToEthereum_(_tokenTosellOut); return _ethereum; }
5,080,638
[ 1, 6528, 24899, 7860, 774, 55, 1165, 1648, 1147, 3088, 1283, 67, 1769, 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 ]
[ 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 ]
[ 1, 565, 445, 4604, 41, 18664, 379, 8872, 12, 11890, 5034, 389, 7860, 774, 55, 1165, 13, 203, 540, 1071, 1476, 203, 540, 203, 3639, 1135, 12, 11890, 5034, 13, 203, 565, 288, 203, 1082, 203, 202, 202, 11890, 5034, 389, 2316, 774, 38, 321, 33, 67, 7860, 774, 55, 1165, 14, 70, 321, 8849, 19, 6625, 31, 203, 202, 202, 430, 24899, 2316, 774, 38, 321, 422, 20, 13, 203, 202, 202, 95, 203, 1082, 202, 67, 2316, 774, 38, 321, 33, 21, 31, 203, 202, 202, 97, 203, 1082, 203, 202, 202, 11890, 5034, 389, 2316, 56, 538, 1165, 1182, 273, 14060, 10477, 18, 1717, 24899, 7860, 774, 55, 1165, 16, 389, 2316, 774, 38, 321, 1769, 203, 3639, 2254, 5034, 389, 546, 822, 379, 273, 18349, 774, 41, 18664, 379, 67, 24899, 2316, 56, 538, 1165, 1182, 1769, 203, 3639, 203, 3639, 327, 389, 546, 822, 379, 31, 203, 565, 289, 203, 27699, 27699, 1377, 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 ]
./full_match/3/0x1177Bc87cF577fd6Db2c9E4EC25d6E4Dbe09c423/sources/qsyhuniswapcall.sol
获取Qsyh价格uint256 qsyhPrice18 = qsyhPrice.mul(10 ** 18);
function getQsyhPrice(address[] memory ethpath, address[] memory btcpath) public view returns (uint256) { require(ethpath[0] == uniswapRouter.WETH()); require(ethpath[ethpath.length - 1] == USDC_ADDRESS); require(btcpath[0] == currency_address["btc"]); require(btcpath[btcpath.length - 1] == USDC_ADDRESS); uint256 qsyhPrice; uint256 btcPrice = getBTCPrice(btcpath); uint256 ethPrice = getETHPrice(ethpath); uint256 peie1 = (btcPrice.mul(currency_mapping["btc"])).div(100); uint256 peie2 = (ethPrice.mul(currency_mapping["eth"])).div(100); qsyhPrice = (peie1.add(peie2)).div(10000); return qsyhPrice; }
8,274,886
[ 1, 169, 241, 120, 166, 242, 249, 53, 9009, 76, 165, 124, 120, 167, 259, 125, 11890, 5034, 8719, 93, 76, 5147, 2643, 273, 8719, 93, 76, 5147, 18, 16411, 12, 2163, 225, 6549, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 23413, 9009, 76, 5147, 12, 2867, 8526, 3778, 13750, 803, 16, 1758, 8526, 3778, 12798, 803, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 27699, 1377, 2583, 12, 546, 803, 63, 20, 65, 422, 640, 291, 91, 438, 8259, 18, 59, 1584, 44, 10663, 203, 1377, 2583, 12, 546, 803, 63, 546, 803, 18, 2469, 300, 404, 65, 422, 11836, 5528, 67, 15140, 1769, 203, 1377, 2583, 12, 70, 5111, 803, 63, 20, 65, 422, 5462, 67, 2867, 9614, 70, 5111, 11929, 1769, 203, 1377, 2583, 12, 70, 5111, 803, 63, 70, 5111, 803, 18, 2469, 300, 404, 65, 422, 11836, 5528, 67, 15140, 1769, 203, 1377, 203, 1377, 2254, 5034, 8719, 93, 76, 5147, 31, 7010, 1377, 2254, 5034, 12798, 5147, 273, 2882, 13891, 3057, 12, 70, 5111, 803, 1769, 203, 1377, 2254, 5034, 13750, 5147, 273, 336, 1584, 2500, 3057, 12, 546, 803, 1769, 203, 1377, 2254, 5034, 2804, 1385, 21, 273, 261, 70, 5111, 5147, 18, 16411, 12, 7095, 67, 6770, 9614, 70, 5111, 6, 5717, 2934, 2892, 12, 6625, 1769, 203, 1377, 2254, 5034, 2804, 1385, 22, 273, 261, 546, 5147, 18, 16411, 12, 7095, 67, 6770, 9614, 546, 6, 5717, 2934, 2892, 12, 6625, 1769, 203, 1377, 8719, 93, 76, 5147, 273, 261, 347, 1385, 21, 18, 1289, 12, 347, 1385, 22, 13, 2934, 2892, 12, 23899, 1769, 203, 4202, 327, 8719, 93, 76, 5147, 31, 203, 282, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x074895060e319f78e93688629d8497c58542733F/sources/contracts/FlyzLOOKSCapacitorV3.sol
* @notice Stake LOOKS tokens @param amount amount of LOOKS to stake/
function _stake(uint256 amount) internal { require(amount <= IERC20(looks).balanceOf(address(this)), "Capacitor: over balance"); ILooksStakingV2(looksStaking).deposit(amount); }
5,007,175
[ 1, 510, 911, 1806, 3141, 55, 2430, 225, 3844, 3844, 434, 1806, 3141, 55, 358, 384, 911, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 334, 911, 12, 11890, 5034, 3844, 13, 2713, 288, 203, 3639, 2583, 12, 8949, 1648, 467, 654, 39, 3462, 12, 7330, 87, 2934, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 315, 4664, 1077, 1811, 30, 1879, 11013, 8863, 203, 3639, 467, 20475, 510, 6159, 58, 22, 12, 7330, 87, 510, 6159, 2934, 323, 1724, 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 ]
//Address: 0x86d108d1EeF9AD9F71D1b7080B172085d871CBC4 //Contract name: NeuroSale //Balance: 0 Ether //Verification Date: 1/7/2018 //Transacion Count: 3226 // CODE STARTS HERE pragma solidity ^0.4.18; contract Token { function transfer(address _to, uint _value) public returns(bool); function burn(uint _value) public; function balanceOf(address _owner) view public returns(uint); function decimals() view public returns(uint8); function transferOwnership(address _newOwner) public; } library SafeMath { function add(uint _a, uint _b) internal pure returns(uint) { uint c = _a + _b; assert(c >= _a); return c; } function mul(uint _a, uint _b) internal pure returns(uint) { if (_a == 0) { return 0; } uint c = _a * _b; assert(c / _a == _b); return c; } function div(uint _a, uint _b) internal pure returns(uint) { return _a / _b; } function sub(uint _a, uint _b) internal pure returns (uint) { assert(_b <= _a); return _a - _b; } } contract Owned { address public contractOwner; address public pendingContractOwner; event LogContractOwnershipChangeInitiated(address to); event LogContractOwnershipChangeCompleted(address to); function Owned() public { contractOwner = msg.sender; } modifier onlyContractOwner() { require(contractOwner == msg.sender); _; } function changeContractOwnership(address _to) onlyContractOwner() public returns(bool) { pendingContractOwner = _to; LogContractOwnershipChangeInitiated(_to); return true; } function claimContractOwnership() public returns(bool) { if (pendingContractOwner != msg.sender) { return false; } contractOwner = pendingContractOwner; delete pendingContractOwner; LogContractOwnershipChangeCompleted(contractOwner); return true; } function forceChangeContractOwnership(address _to) onlyContractOwner() public returns(bool) { contractOwner = _to; LogContractOwnershipChangeCompleted(contractOwner); return true; } } contract NeuroSale is Owned { using SafeMath for uint; mapping(address => uint) public totalSpentEth; mapping(address => uint) public totalTokensWithoutBonuses; mapping(address => uint) public volumeBonusesTokens; uint public constant TOKEN_PRICE = 0.001 ether; uint public constant MULTIPLIER = uint(10) ** uint(18); uint public salesStart; uint public salesDeadline; Token public token; address public wallet; bool public salePaused; event LogBought(address indexed receiver, uint contribution, uint reward, uint128 customerId); event LogPaused(bool isPaused); event LogWalletUpdated(address to); modifier notPaused() { require(!salePaused); _; } // Can be iniitialized only once. function init(Token _token, address _wallet, uint _start, uint _deadline) onlyContractOwner() public returns(bool) { require(address(token) == 0); require(_wallet != 0); token = _token; wallet = _wallet; salesStart = _start; salesDeadline = _deadline; return true; } function setSalePause(bool _value) onlyContractOwner() public returns(bool) { salePaused = _value; LogPaused(_value); return true; } function setWallet(address _wallet) onlyContractOwner() public returns(bool) { require(_wallet != 0); wallet = _wallet; LogWalletUpdated(_wallet); return true; } function transferOwnership() onlyContractOwner() public returns(bool) { token.transferOwnership(contractOwner); return true; } function burnUnsold() onlyContractOwner() public returns(bool) { uint tokensToBurn = token.balanceOf(address(this)); token.burn(tokensToBurn); return true; } function buy() payable notPaused() public returns(bool) { require(now >= salesStart); require(now < salesDeadline); // Overflow is impossible because amounts are calculated based on actual ETH being sent. // There is no division remainder. uint tokensToBuy = msg.value * MULTIPLIER / TOKEN_PRICE; require(tokensToBuy > 0); uint timeBonus = _calculateTimeBonus(tokensToBuy, now); uint volumeBonus = _calculateVolumeBonus(tokensToBuy, msg.sender, msg.value); // Overflow is impossible because amounts are calculated based on actual ETH being sent. uint totalTokensToTransfer = tokensToBuy + timeBonus + volumeBonus; require(token.transfer(msg.sender, totalTokensToTransfer)); LogBought(msg.sender, msg.value, totalTokensToTransfer, 0); // Call is performed as the last action, no threats. require(wallet.call.value(msg.value)()); return true; } function buyWithCustomerId(address _beneficiary, uint _value, uint _amount, uint128 _customerId, uint _date, bool _autobonus) onlyContractOwner() public returns(bool) { uint totalTokensToTransfer; uint volumeBonus; if (_autobonus) { uint tokensToBuy = _value.mul(MULTIPLIER).div(TOKEN_PRICE); require(tokensToBuy > 0); uint timeBonus = _calculateTimeBonus(tokensToBuy, _date); volumeBonus = _calculateVolumeBonus(tokensToBuy, _beneficiary, _value); // Overflow is possible because value is specified in the input. totalTokensToTransfer = tokensToBuy.add(timeBonus).add(volumeBonus); } else { totalTokensToTransfer = _amount; } require(token.transfer(_beneficiary, totalTokensToTransfer)); LogBought(_beneficiary, _value, totalTokensToTransfer, _customerId); return true; } function _calculateTimeBonus(uint _value, uint _date) view internal returns(uint) { // Overflows are possible because value is specified in the input. if (_date < salesStart) { return 0; } // between 07.01.2018 00:00:00 UTC and 14.01.2018 00:00:00 UTC +15% if (_date < salesStart + 1 weeks) { return _value.mul(150).div(1000); } // between 14.01.2018 00:00:00 UTC and 21.01.2018 00:00:00 UTC +10% if (_date < salesStart + 2 weeks) { return _value.mul(100).div(1000); } // between 21.01.2018 00:00:00 UTC and 28.01.2018 00:00:00 UTC +7% if (_date < salesStart + 3 weeks) { return _value.mul(70).div(1000); } // between 28.01.2018 00:00:00 UTC and 04.02.2018 00:00:00 UTC +4% if (_date < salesStart + 4 weeks) { return _value.mul(40).div(1000); } // between 04.02.2018 00:00:00 UTC and 11.02.2018 00:00:00 UTC +2% if (_date < salesStart + 5 weeks) { return _value.mul(20).div(1000); } // between 11.02.2018 00:00:00 UTC and 15.02.2018 23:59:59 UTC +1% if (_date < salesDeadline) { return _value.mul(10).div(1000); } return 0; } function _calculateVolumeBonus(uint _amount, address _receiver, uint _value) internal returns(uint) { // Overflows are possible because amount and value are specified in the input. uint totalCollected = totalTokensWithoutBonuses[_receiver].add(_amount); uint totalEth = totalSpentEth[_receiver].add(_value); uint totalBonus; if (totalEth < 30 ether) { totalBonus = 0; } else if (totalEth < 50 ether) { totalBonus = totalCollected.mul(10).div(1000); } else if (totalEth < 100 ether) { totalBonus = totalCollected.mul(25).div(1000); } else if (totalEth < 300 ether) { totalBonus = totalCollected.mul(50).div(1000); } else if (totalEth < 500 ether) { totalBonus = totalCollected.mul(80).div(1000); } else if (totalEth < 1000 ether) { totalBonus = totalCollected.mul(150).div(1000); } else if (totalEth < 2000 ether) { totalBonus = totalCollected.mul(200).div(1000); } else if (totalEth < 3000 ether) { totalBonus = totalCollected.mul(300).div(1000); } else if (totalEth >= 3000 ether) { totalBonus = totalCollected.mul(400).div(1000); } // Overflow is impossible because totalBonus is always >= volumeBonusesTokens[_receiver]; uint bonusToPay = totalBonus - volumeBonusesTokens[_receiver]; volumeBonusesTokens[_receiver] = totalBonus; totalSpentEth[_receiver] = totalEth; totalTokensWithoutBonuses[_receiver] = totalCollected; return bonusToPay; } function () payable public { buy(); } // In case somebody sends tokens here. function recoverTokens(Token _token, uint _amount) onlyContractOwner() public returns(bool) { return _token.transfer(contractOwner, _amount); } }
Overflows are possible because value is specified in the input. between 07.01.2018 00:00:00 UTC and 14.01.2018 00:00:00 UTC +15% between 14.01.2018 00:00:00 UTC and 21.01.2018 00:00:00 UTC +10% between 21.01.2018 00:00:00 UTC and 28.01.2018 00:00:00 UTC +7% between 28.01.2018 00:00:00 UTC and 04.02.2018 00:00:00 UTC +4% between 04.02.2018 00:00:00 UTC and 11.02.2018 00:00:00 UTC +2% between 11.02.2018 00:00:00 UTC and 15.02.2018 23:59:59 UTC +1%
function _calculateTimeBonus(uint _value, uint _date) view internal returns(uint) { if (_date < salesStart) { return 0; } if (_date < salesStart + 1 weeks) { return _value.mul(150).div(1000); } if (_date < salesStart + 2 weeks) { return _value.mul(100).div(1000); } if (_date < salesStart + 3 weeks) { return _value.mul(70).div(1000); } if (_date < salesStart + 4 weeks) { return _value.mul(40).div(1000); } if (_date < salesStart + 5 weeks) { return _value.mul(20).div(1000); } if (_date < salesDeadline) { return _value.mul(10).div(1000); } return 0; }
6,381,819
[ 1, 15526, 87, 854, 3323, 2724, 460, 353, 1269, 316, 326, 810, 18, 3086, 10934, 18, 1611, 18, 21849, 9631, 30, 713, 30, 713, 9951, 471, 5045, 18, 1611, 18, 21849, 9631, 30, 713, 30, 713, 9951, 397, 3600, 9, 3086, 5045, 18, 1611, 18, 21849, 9631, 30, 713, 30, 713, 9951, 471, 9035, 18, 1611, 18, 21849, 9631, 30, 713, 30, 713, 9951, 397, 2163, 9, 3086, 9035, 18, 1611, 18, 21849, 9631, 30, 713, 30, 713, 9951, 471, 9131, 18, 1611, 18, 21849, 9631, 30, 713, 30, 713, 9951, 397, 27, 9, 3086, 9131, 18, 1611, 18, 21849, 9631, 30, 713, 30, 713, 9951, 471, 16486, 18, 3103, 18, 21849, 9631, 30, 713, 30, 713, 9951, 397, 24, 9, 3086, 16486, 18, 3103, 18, 21849, 9631, 30, 713, 30, 713, 9951, 471, 4648, 18, 3103, 18, 21849, 9631, 30, 713, 30, 713, 9951, 397, 22, 9, 3086, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 11162, 950, 38, 22889, 12, 11890, 389, 1132, 16, 2254, 389, 712, 13, 1476, 2713, 1135, 12, 11890, 13, 288, 203, 3639, 309, 261, 67, 712, 411, 272, 5408, 1685, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 309, 261, 67, 712, 411, 272, 5408, 1685, 397, 404, 17314, 13, 288, 203, 5411, 327, 389, 1132, 18, 16411, 12, 23014, 2934, 2892, 12, 18088, 1769, 203, 3639, 289, 203, 3639, 309, 261, 67, 712, 411, 272, 5408, 1685, 397, 576, 17314, 13, 288, 203, 5411, 327, 389, 1132, 18, 16411, 12, 6625, 2934, 2892, 12, 18088, 1769, 203, 3639, 289, 203, 3639, 309, 261, 67, 712, 411, 272, 5408, 1685, 397, 890, 17314, 13, 288, 203, 5411, 327, 389, 1132, 18, 16411, 12, 7301, 2934, 2892, 12, 18088, 1769, 203, 3639, 289, 203, 3639, 309, 261, 67, 712, 411, 272, 5408, 1685, 397, 1059, 17314, 13, 288, 203, 5411, 327, 389, 1132, 18, 16411, 12, 7132, 2934, 2892, 12, 18088, 1769, 203, 3639, 289, 203, 3639, 309, 261, 67, 712, 411, 272, 5408, 1685, 397, 1381, 17314, 13, 288, 203, 5411, 327, 389, 1132, 18, 16411, 12, 3462, 2934, 2892, 12, 18088, 1769, 203, 3639, 289, 203, 3639, 309, 261, 67, 712, 411, 272, 5408, 15839, 13, 288, 203, 5411, 327, 389, 1132, 18, 16411, 12, 2163, 2934, 2892, 12, 18088, 1769, 203, 3639, 289, 203, 203, 3639, 327, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // Solidity files have to start with this pragma. // It will be used by the Solidity compiler to validate its version. pragma solidity ^0.6.12; import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol"; import '@openzeppelin/contracts/access/AccessControl.sol'; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/payment/escrow/Escrow.sol"; // This is the main building block for smart contracts. contract Listing is Ownable, AccessControl, ChainlinkClient { using Chainlink for Chainlink.Request; enum ListingState { Open, Locked, SellerUnlocked, BuyerUnlocked, Canceled, Completed } ListingState public listingState; // Listing information string public listingImageLink; string public listingTitle; string public listingDescription; string public listingLocation; string public listingContact; uint256 public listingMinEscrow; uint256 public listingPrice; // Listing transaction participants address public sellerAddress; address public buyerAddress; // Listing hash values bytes32 public hashSellerCode; bytes32 public hashBuyerCode; uint256 public numOffers; mapping (uint => address) public offerIndexes; // Maps address of buyer to amount they are willing to escrow mapping (address => uint256) public listingOffers; uint256 public numListingOffers; bytes32 public constant SELLER_ROLE = keccak256("SELLER_ROLE"); bytes32 public constant BUYER_ROLE = keccak256("BUYER_ROLE"); event BuyerOfferAccepted(address buyer); event BuyerOfferCancelled(address buyer); event ListingCancelled(); event SellerUnlocked(); event BuyerUnlocked(); event ListingCompleted(address listing); // EA Information address private linkToken = 0x326C977E6efc84E512bB9C30f76E30c160eD06FB; address private oracle = 0xc4bE487753B9861ecC52fbcE5B91B766A2D8127d; bytes32 private eaJobId = "9502ee7cd408427c99b243d2cce9028e"; uint256 private fee = 0.1 * 10 ** 18; Escrow escrow; constructor( address _sellerAddress, string memory _listingImageLink, string memory _listingTitle, string memory _listingDescription, string memory _listingLocation, string memory _listingContact, uint256 _listingMinEscrow, uint256 _listingPrice, bytes32 _hashSellerCode ) public { // Sets the gateway as the admin role for access control _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); // Sets the seller as the seller role _setupRole(SELLER_ROLE, _sellerAddress); // Sets constructor variables sellerAddress = _sellerAddress; listingImageLink = _listingImageLink; listingTitle = _listingTitle; listingDescription = _listingDescription; listingLocation = _listingLocation; listingContact = _listingContact; listingMinEscrow = _listingMinEscrow; listingPrice = _listingPrice; hashSellerCode = _hashSellerCode; numOffers = 0; listingState = ListingState.Open; escrow = new Escrow(); } /********************** * General view methods **********************/ /* * Gets the current listing offers and returns an array of address and array of offer amounts */ function getListingOffers() external view returns (address[] memory, uint256[] memory){ address[] memory _offerAddresses = new address[](numOffers); uint256[] memory _offerAmounts = new uint256[](numOffers); for (uint256 i = 0; i < numOffers; i++) { _offerAddresses[i] = offerIndexes[i]; _offerAmounts[i] = listingOffers[offerIndexes[i]]; } return (_offerAddresses, _offerAmounts); } /********************** * Seller facing methods **********************/ /* * Accepts offer from a buyer on a listing, must be seller to call this method * Seller deposits escrow offered by buyer */ function acceptOffer(address _buyerAddress) external payable { require(hasRole(SELLER_ROLE, msg.sender), "You are not the seller, cannot accept offer"); require(escrow.depositsOf(_buyerAddress) >= listingMinEscrow , "Error buyer does not have the minimum amount deposited"); require(msg.value == listingOffers[_buyerAddress], "You must deposit the amount commited to by the buyer"); buyerAddress = _buyerAddress; listingState = ListingState.Locked; // TODO: can you send a transaction with a prefilled out amount? escrow.deposit{value: msg.value}(msg.sender); } function cancelListing() external { require(hasRole(SELLER_ROLE, msg.sender), "You are not the seller, cannot accept offer"); listingState = ListingState.Canceled; // TODO: Upon seller initiation, listing is canceled, marks Listing as Canceled or Completed } function unlockListingSeller(string memory buyerUnlockCode) external { bytes32 hashBuyerUnlockCode = keccak256(abi.encodePacked(buyerUnlockCode)); require(hashBuyerUnlockCode == hashBuyerCode, "Incorrect buyer unlock code"); // If buyer has not yet unlocked the listing if (listingState == ListingState.Locked) { listingState = ListingState.SellerUnlocked; // If buyer has unlocked the listing, transaction complete and enable refunds } else if (listingState == ListingState.BuyerUnlocked) { listingState = ListingState.Completed; } } function sellerWithdraw() public { require(hasRole(SELLER_ROLE, msg.sender), "You are not the seller, cannot withdraw"); if (listingState == ListingState.Canceled || listingState == ListingState.Completed) { escrow.withdraw(msg.sender); } else { revert("Seller withdrawal not allowed"); } } /* * Buyer facing methods */ function submitOffer(address _buyerAddress, bytes32 _hashBuyerCode) external payable onlyOwner { require(msg.value >= listingMinEscrow, "You must meet the minimum escrow amount"); hashBuyerCode = _hashBuyerCode; listingOffers[_buyerAddress] = msg.value; offerIndexes[numOffers] = _buyerAddress; // TODO: can you send a transaction with a prefilled out amount? escrow.deposit{value: msg.value}(_buyerAddress); numOffers++; } function cancelOffer(address payable _buyerAddress) external onlyOwner { if (_buyerAddress == sellerAddress) { revert("Seller cancel offer not allowed"); } if (_buyerAddress == buyerAddress) { if (listingState == ListingState.Canceled || listingState == ListingState.Completed) { delete(listingOffers[_buyerAddress]); numOffers--; listingOffers[_buyerAddress] = 0; escrow.withdraw(_buyerAddress); } else { revert("Buyer withdrawal not allowed"); } } else { delete(listingOffers[_buyerAddress]); numOffers--; listingOffers[_buyerAddress] = 0; escrow.withdraw(_buyerAddress); } // TODO: removes buyer address from listing offers } function unlockListingBuyer(string memory sellerUnlockCode) external { bytes32 hashSellerUnlockCode = keccak256(abi.encodePacked(sellerUnlockCode)); require(hashSellerUnlockCode == hashSellerCode, "Incorrect seller unlock code"); // If buyer has not yet unlocked the listing if (listingState == ListingState.Locked) { listingState = ListingState.BuyerUnlocked; // If buyer has unlocked the listing, transaction complete and enable refunds } else if (listingState == ListingState.SellerUnlocked) { listingState = ListingState.Completed; } } function buyerWithdraw() public { require(msg.sender != sellerAddress, "seller cannot call buyer method to withdraw"); if (msg.sender == buyerAddress) { if (listingState == ListingState.Canceled || listingState == ListingState.Completed) { listingOffers[msg.sender] = 0; escrow.withdraw(msg.sender); } else { revert("Buyer withdrawal not allowed"); } } else { listingOffers[msg.sender] = 0; escrow.withdraw(msg.sender); } } /** * @dev * Create a Chainlink request to query whether or not buyer and seller are nearby */ function requestUserLocation() public returns (bytes32 requestId) { Chainlink.Request memory req = buildChainlinkRequest(eaJobId, address(this), this.fulfillUserLocationRequest.selector); req.add("buyerAddress", addressToString(buyerAddress)); req.add("sellerAddress", addressToString(sellerAddress)); // Sends the request bytes32 _requestId = sendChainlinkRequestTo(oracle, req, fee); return _requestId; } /** * @dev * Receive the response in the form of bool if they're nearby */ function fulfillUserLocationRequest(bytes32 requestId, bool nearby) public recordChainlinkFulfillment(requestId) { // If nearby is true we unlock the pact if (nearby) { listingState = ListingState.Completed; emit ListingCompleted(address(this)); } } function addressToString(address _address) public pure returns(string memory) { bytes32 _bytes = bytes32(uint256(uint160(_address))); bytes memory HEX = "0123456789abcdef"; bytes memory _string = new bytes(42); _string[0] = '0'; _string[1] = 'x'; for(uint i = 0; i < 20; i++) { _string[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _string[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_string); } }
If buyer has not yet unlocked the listing If buyer has unlocked the listing, transaction complete and enable refunds
function unlockListingBuyer(string memory sellerUnlockCode) external { bytes32 hashSellerUnlockCode = keccak256(abi.encodePacked(sellerUnlockCode)); require(hashSellerUnlockCode == hashSellerCode, "Incorrect seller unlock code"); if (listingState == ListingState.Locked) { listingState = ListingState.BuyerUnlocked; listingState = ListingState.Completed; } }
1,773,512
[ 1, 2047, 27037, 711, 486, 4671, 25966, 326, 11591, 971, 27037, 711, 25966, 326, 11591, 16, 2492, 3912, 471, 4237, 16255, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7186, 19081, 38, 16213, 12, 1080, 3778, 29804, 7087, 1085, 13, 3903, 288, 203, 3639, 1731, 1578, 1651, 22050, 7087, 1085, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 1786, 749, 7087, 1085, 10019, 203, 3639, 2583, 12, 2816, 22050, 7087, 1085, 422, 1651, 22050, 1085, 16, 315, 16268, 29804, 7186, 981, 8863, 203, 203, 3639, 309, 261, 21228, 1119, 422, 987, 310, 1119, 18, 8966, 13, 288, 203, 5411, 11591, 1119, 273, 987, 310, 1119, 18, 38, 16213, 7087, 329, 31, 203, 5411, 11591, 1119, 273, 987, 310, 1119, 18, 9556, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "../proxy/Proxy.sol"; import "../PolymathRegistry.sol"; import "../interfaces/IModule.sol"; import "./SecurityTokenStorage.sol"; import "../libraries/TokenLib.sol"; import "../interfaces/IDataStore.sol"; import "../interfaces/IUpgradableTokenFactory.sol"; import "../interfaces/IModuleFactory.sol"; import "../interfaces/token/IERC1410.sol"; import "../interfaces/token/IERC1594.sol"; import "../interfaces/token/IERC1643.sol"; import "../interfaces/token/IERC1644.sol"; import "../interfaces/IModuleRegistry.sol"; import "../interfaces/ITransferManager.sol"; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /** * @title Security Token contract * @notice SecurityToken is an ERC1400 token with added capabilities: * @notice - Implements the ERC1400 Interface * @notice - Transfers are restricted * @notice - Modules can be attached to it to control its behaviour * @notice - ST should not be deployed directly, but rather the SecurityTokenRegistry should be used * @notice - ST does not inherit from ISecurityToken due to: * @notice - https://github.com/ethereum/solidity/issues/4847 */ contract SecurityToken is ERC20, ReentrancyGuard, SecurityTokenStorage, IERC1594, IERC1643, IERC1644, IERC1410, Proxy { using SafeMath for uint256; // Emit at the time when module get added event ModuleAdded( uint8[] _types, bytes32 indexed _name, address indexed _moduleFactory, address _module, uint256 _moduleCost, uint256 _budget, bytes32 _label, bool _archived ); // Emit when the token details get updated event UpdateTokenDetails(string _oldDetails, string _newDetails); // Emit when the token name get updated event UpdateTokenName(string _oldName, string _newName); // Emit when the granularity get changed event GranularityChanged(uint256 _oldGranularity, uint256 _newGranularity); // Emit when is permanently frozen by the issuer event FreezeIssuance(); // Emit when transfers are frozen or unfrozen event FreezeTransfers(bool _status); // Emit when new checkpoint created event CheckpointCreated(uint256 indexed _checkpointId, uint256 _investorLength); // Events to log controller actions event SetController(address indexed _oldController, address indexed _newController); //Event emit when the global treasury wallet address get changed event TreasuryWalletChanged(address _oldTreasuryWallet, address _newTreasuryWallet); event DisableController(); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event TokenUpgraded(uint8 _major, uint8 _minor, uint8 _patch); // Emit when Module get archived from the securityToken event ModuleArchived(uint8[] _types, address _module); //Event emitted by the tokenLib. // Emit when Module get unarchived from the securityToken event ModuleUnarchived(uint8[] _types, address _module); //Event emitted by the tokenLib. // Emit when Module get removed from the securityToken event ModuleRemoved(uint8[] _types, address _module); //Event emitted by the tokenLib. // Emit when the budget allocated to a module is changed event ModuleBudgetChanged(uint8[] _moduleTypes, address _module, uint256 _oldBudget, uint256 _budget); //Event emitted by the tokenLib. /** * @notice Initialization function * @dev Expected to be called atomically with the proxy being created, by the owner of the token * @dev Can only be called once */ function initialize(address _getterDelegate) public { //Expected to be called atomically with the proxy being created require(!initialized, "Already initialized"); getterDelegate = _getterDelegate; securityTokenVersion = SemanticVersion(3, 0, 0); updateFromRegistry(); tokenFactory = msg.sender; initialized = true; } /** * @notice Checks if an address is a module of certain type * @param _module Address to check * @param _type type to check against */ function isModule(address _module, uint8 _type) public view returns(bool) { if (modulesToData[_module].module != _module || modulesToData[_module].isArchived) return false; for (uint256 i = 0; i < modulesToData[_module].moduleTypes.length; i++) { if (modulesToData[_module].moduleTypes[i] == _type) { return true; } } return false; } // Require msg.sender to be the specified module type or the owner of the token function _onlyModuleOrOwner(uint8 _type) internal view { if (msg.sender != owner()) require(isModule(msg.sender, _type)); } function _isValidPartition(bytes32 _partition) internal pure { require(_partition == UNLOCKED, "Invalid partition"); } function _isValidOperator(address _from, address _operator, bytes32 _partition) internal view { _isAuthorised( allowance(_from, _operator) == uint(-1) || partitionApprovals[_from][_partition][_operator] ); } function _zeroAddressCheck(address _entity) internal pure { require(_entity != address(0), "Invalid address"); } function _isValidTransfer(bool _isTransfer) internal pure { require(_isTransfer, "Transfer Invalid"); } function _isValidRedeem(bool _isRedeem) internal pure { require(_isRedeem, "Invalid redeem"); } function _isSignedByOwner(bool _signed) internal pure { require(_signed, "Owner did not sign"); } function _isIssuanceAllowed() internal view { require(issuance, "Issuance frozen"); } // Function to check whether the msg.sender is authorised or not function _onlyController() internal view { _isAuthorised(msg.sender == controller && isControllable()); } function _isAuthorised(bool _authorised) internal pure { require(_authorised, "Not Authorised"); } /** * @dev Throws if called by any account other than the owner. * @dev using the internal function instead of modifier to save the code size */ function _onlyOwner() internal view { require(isOwner()); } /** * @dev Require msg.sender to be the specified module type */ function _onlyModule(uint8 _type) internal view { require(isModule(msg.sender, _type)); } /** * @dev Throws if called by any account other than the STFactory. */ modifier onlyTokenFactory() { require(msg.sender == tokenFactory); _; } modifier checkGranularity(uint256 _value) { require(_value % granularity == 0, "Invalid granularity"); _; } /** * @notice Attachs a module to the SecurityToken * @dev E.G.: On deployment (through the STR) ST gets a TransferManager module attached to it * @dev to control restrictions on transfers. * @param _moduleFactory is the address of the module factory to be added * @param _data is data packed into bytes used to further configure the module (See STO usage) * @param _maxCost max amount of POLY willing to pay to the module. * @param _budget max amount of ongoing POLY willing to assign to the module. * @param _label custom module label. */ function addModuleWithLabel( address _moduleFactory, bytes memory _data, uint256 _maxCost, uint256 _budget, bytes32 _label, bool _archived ) public nonReentrant { _onlyOwner(); //Check that the module factory exists in the ModuleRegistry - will throw otherwise IModuleRegistry(moduleRegistry).useModule(_moduleFactory, false); IModuleFactory moduleFactory = IModuleFactory(_moduleFactory); uint8[] memory moduleTypes = moduleFactory.types(); uint256 moduleCost = moduleFactory.setupCostInPoly(); require(moduleCost <= _maxCost, "Invalid cost"); //Approve fee for module ERC20(polyToken).approve(_moduleFactory, moduleCost); //Creates instance of module from factory address module = moduleFactory.deploy(_data); require(modulesToData[module].module == address(0), "Module exists"); //Approve ongoing budget ERC20(polyToken).approve(module, _budget); _addModuleData(moduleTypes, _moduleFactory, module, moduleCost, _budget, _label, _archived); } function _addModuleData( uint8[] memory _moduleTypes, address _moduleFactory, address _module, uint256 _moduleCost, uint256 _budget, bytes32 _label, bool _archived ) internal { bytes32 moduleName = IModuleFactory(_moduleFactory).name(); uint256[] memory moduleIndexes = new uint256[](_moduleTypes.length); uint256 i; for (i = 0; i < _moduleTypes.length; i++) { moduleIndexes[i] = modules[_moduleTypes[i]].length; modules[_moduleTypes[i]].push(_module); } modulesToData[_module] = ModuleData( moduleName, _module, _moduleFactory, _archived, _moduleTypes, moduleIndexes, names[moduleName].length, _label ); names[moduleName].push(_module); emit ModuleAdded(_moduleTypes, moduleName, _moduleFactory, _module, _moduleCost, _budget, _label, _archived); } /** * @notice addModule function will call addModuleWithLabel() with an empty label for backward compatible */ function addModule(address _moduleFactory, bytes calldata _data, uint256 _maxCost, uint256 _budget, bool _archived) external { addModuleWithLabel(_moduleFactory, _data, _maxCost, _budget, "", _archived); } /** * @notice Archives a module attached to the SecurityToken * @param _module address of module to archive */ function archiveModule(address _module) external { _onlyOwner(); TokenLib.archiveModule(modulesToData[_module]); } /** * @notice Upgrades a module attached to the SecurityToken * @param _module address of module to archive */ function upgradeModule(address _module) external { _onlyOwner(); TokenLib.upgradeModule(moduleRegistry, modulesToData[_module]); } /** * @notice Upgrades security token */ function upgradeToken() external { _onlyOwner(); // 10 is the number of module types to check for incompatibilities before upgrading. // The number is hard coded and kept low to keep usage low. // We currently have 7 module types. If we ever create more than 3 new module types, // We will upgrade the implementation accordinly. We understand the limitations of this approach. IUpgradableTokenFactory(tokenFactory).upgradeToken(10); emit TokenUpgraded(securityTokenVersion.major, securityTokenVersion.minor, securityTokenVersion.patch); } /** * @notice Unarchives a module attached to the SecurityToken * @param _module address of module to unarchive */ function unarchiveModule(address _module) external { _onlyOwner(); TokenLib.unarchiveModule(moduleRegistry, modulesToData[_module]); } /** * @notice Removes a module attached to the SecurityToken * @param _module address of module to unarchive */ function removeModule(address _module) external { _onlyOwner(); TokenLib.removeModule(_module, modules, modulesToData, names); } /** * @notice Allows the owner to withdraw unspent POLY stored by them on the ST or any ERC20 token. * @dev Owner can transfer POLY to the ST which will be used to pay for modules that require a POLY fee. * @param _tokenContract Address of the ERC20Basic compliance token * @param _value amount of POLY to withdraw */ function withdrawERC20(address _tokenContract, uint256 _value) external { _onlyOwner(); IERC20 token = IERC20(_tokenContract); require(token.transfer(owner(), _value)); } /** * @notice allows owner to increase/decrease POLY approval of one of the modules * @param _module module address * @param _change change in allowance * @param _increase true if budget has to be increased, false if decrease */ function changeModuleBudget(address _module, uint256 _change, bool _increase) external { _onlyOwner(); TokenLib.changeModuleBudget(_module, _change, _increase, polyToken, modulesToData); } /** * @notice updates the tokenDetails associated with the token * @param _newTokenDetails New token details */ function updateTokenDetails(string calldata _newTokenDetails) external { _onlyOwner(); emit UpdateTokenDetails(tokenDetails, _newTokenDetails); tokenDetails = _newTokenDetails; } /** * @notice Allows owner to change token granularity * @param _granularity granularity level of the token */ function changeGranularity(uint256 _granularity) external { _onlyOwner(); require(_granularity != 0, "Invalid granularity"); emit GranularityChanged(granularity, _granularity); granularity = _granularity; } /** * @notice Allows owner to change data store * @param _dataStore Address of the token data store */ function changeDataStore(address _dataStore) external { _onlyOwner(); _zeroAddressCheck(_dataStore); dataStore = _dataStore; } /** * @notice Allows owner to change token name * @param _name new name of the token */ function changeName(string calldata _name) external { _onlyOwner(); emit UpdateTokenName(name, _name); name = _name; } /** * @notice Allows to change the treasury wallet address * @param _wallet Ethereum address of the treasury wallet */ function changeTreasuryWallet(address _wallet) external { _onlyOwner(); _zeroAddressCheck(_wallet); emit TreasuryWalletChanged(IDataStore(dataStore).getAddress(TREASURY), _wallet); IDataStore(dataStore).setAddress(TREASURY, _wallet); } /** * @notice Keeps track of the number of non-zero token holders * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer */ function _adjustInvestorCount(address _from, address _to, uint256 _value) internal { holderCount = TokenLib.adjustInvestorCount(holderCount, _from, _to, _value, balanceOf(_to), balanceOf(_from), dataStore); } /** * @notice freezes transfers */ function freezeTransfers() external { _onlyOwner(); require(!transfersFrozen); transfersFrozen = true; /*solium-disable-next-line security/no-block-members*/ emit FreezeTransfers(true); } /** * @notice Unfreeze transfers */ function unfreezeTransfers() external { _onlyOwner(); require(transfersFrozen); transfersFrozen = false; /*solium-disable-next-line security/no-block-members*/ emit FreezeTransfers(false); } /** * @notice Internal - adjusts token holder balance at checkpoint before a token transfer * @param _investor address of the token holder affected */ function _adjustBalanceCheckpoints(address _investor) internal { TokenLib.adjustCheckpoints(checkpointBalances[_investor], balanceOf(_investor), currentCheckpointId); } /** * @notice Overloaded version of the transfer function * @param _to receiver of transfer * @param _value value of transfer * @return bool success */ function transfer(address _to, uint256 _value) public returns(bool success) { transferWithData(_to, _value, ""); return true; } /** * @notice Transfer restrictions can take many forms and typically involve on-chain rules or whitelists. * However for many types of approved transfers, maintaining an on-chain list of approved transfers can be * cumbersome and expensive. An alternative is the co-signing approach, where in addition to the token holder * approving a token transfer, and authorised entity provides signed data which further validates the transfer. * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred * @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer. * for the token contract to interpret or record. This could be signed data authorising the transfer * (e.g. a dynamic whitelist) but is flexible enough to accomadate other use-cases. */ function transferWithData(address _to, uint256 _value, bytes memory _data) public { _transferWithData(msg.sender, _to, _value, _data); } function _transferWithData(address _from, address _to, uint256 _value, bytes memory _data) internal { _isValidTransfer(_updateTransfer(_from, _to, _value, _data)); // Using the internal function instead of super.transfer() in the favour of reducing the code size _transfer(_from, _to, _value); } /** * @notice Overloaded version of the transferFrom function * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { transferFromWithData(_from, _to, _value, ""); return true; } /** * @notice Transfer restrictions can take many forms and typically involve on-chain rules or whitelists. * However for many types of approved transfers, maintaining an on-chain list of approved transfers can be * cumbersome and expensive. An alternative is the co-signing approach, where in addition to the token holder * approving a token transfer, and authorised entity provides signed data which further validates the transfer. * @dev `msg.sender` MUST have a sufficient `allowance` set and this `allowance` must be debited by the `_value`. * @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 * @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer. * for the token contract to interpret or record. This could be signed data authorising the transfer * (e.g. a dynamic whitelist) but is flexible enough to accomadate other use-cases. */ function transferFromWithData(address _from, address _to, uint256 _value, bytes memory _data) public { _isValidTransfer(_updateTransfer(_from, _to, _value, _data)); require(super.transferFrom(_from, _to, _value)); } /** * @notice Get the balance according to the provided partitions * @param _partition Partition which differentiate the tokens. * @param _tokenHolder Whom balance need to queried * @return Amount of tokens as per the given partitions */ function balanceOfByPartition(bytes32 _partition, address _tokenHolder) public view returns(uint256) { return _balanceOfByPartition(_partition, _tokenHolder, 0); } function _balanceOfByPartition(bytes32 _partition, address _tokenHolder, uint256 _additionalBalance) internal view returns(uint256 max) { address[] memory tms = modules[TRANSFER_KEY]; uint256 amount; for (uint256 i = 0; i < tms.length; i++) { amount = ITransferManager(tms[i]).getTokensByPartition(_partition, _tokenHolder, _additionalBalance); if (max < amount) { max = amount; } } } /** * @notice Transfers the ownership of tokens from a specified partition from one address to another address * @param _partition The partition from which to transfer tokens * @param _to The address to which to transfer tokens to * @param _value The amount of tokens to transfer from `_partition` * @param _data Additional data attached to the transfer of tokens * @return The partition to which the transferred tokens were allocated for the _to address */ function transferByPartition(bytes32 _partition, address _to, uint256 _value, bytes memory _data) public returns (bytes32) { return _transferByPartition(msg.sender, _to, _value, _partition, _data, address(0), ""); } function _transferByPartition( address _from, address _to, uint256 _value, bytes32 _partition, bytes memory _data, address _operator, bytes memory _operatorData ) internal returns(bytes32 toPartition) { _isValidPartition(_partition); // Avoiding to add this check // require(balanceOfByPartition(_partition, msg.sender) >= _value); // NB - Above condition will be automatically checked using the executeTransfer() function execution. // NB - passing `_additionalBalance` value is 0 because accessing the balance before transfer uint256 balanceBeforeTransferLocked = _balanceOfByPartition(_partition, _to, 0); _transferWithData(_from, _to, _value, _data); // NB - passing `_additonalBalance` valie is 0 because balance of `_to` was updated in the transfer call uint256 balanceAfterTransferLocked = _balanceOfByPartition(_partition, _to, 0); toPartition = _returnPartition(balanceBeforeTransferLocked, balanceAfterTransferLocked, _value); emit TransferByPartition(_partition, _operator, _from, _to, _value, _data, _operatorData); } function _returnPartition(uint256 _beforeBalance, uint256 _afterBalance, uint256 _value) internal pure returns(bytes32 toPartition) { // return LOCKED only when the transaction `_value` should be equal to the change in the LOCKED partition // balance otherwise return UNLOCKED if (_afterBalance.sub(_beforeBalance) == _value) toPartition = LOCKED; // Returning the same partition UNLOCKED toPartition = UNLOCKED; } /////////////////////// /// Operator Management /////////////////////// /** * @notice Authorises an operator for all partitions of `msg.sender`. * NB - Allowing investors to authorize an investor to be an operator of all partitions * but it doesn't mean we operator is allowed to transfer the LOCKED partition values. * Logic for this restriction is written in `operatorTransferByPartition()` function. * @param _operator An address which is being authorised. */ function authorizeOperator(address _operator) public { _approve(msg.sender, _operator, uint(-1)); emit AuthorizedOperator(_operator, msg.sender); } /** * @notice Revokes authorisation of an operator previously given for all partitions of `msg.sender`. * NB - Allowing investors to authorize an investor to be an operator of all partitions * but it doesn't mean we operator is allowed to transfer the LOCKED partition values. * Logic for this restriction is written in `operatorTransferByPartition()` function. * @param _operator An address which is being de-authorised */ function revokeOperator(address _operator) public { _approve(msg.sender, _operator, 0); emit RevokedOperator(_operator, msg.sender); } /** * @notice Authorises an operator for a given partition of `msg.sender` * @param _partition The partition to which the operator is authorised * @param _operator An address which is being authorised */ function authorizeOperatorByPartition(bytes32 _partition, address _operator) public { _isValidPartition(_partition); partitionApprovals[msg.sender][_partition][_operator] = true; emit AuthorizedOperatorByPartition(_partition, _operator, msg.sender); } /** * @notice Revokes authorisation of an operator previously given for a specified partition of `msg.sender` * @param _partition The partition to which the operator is de-authorised * @param _operator An address which is being de-authorised */ function revokeOperatorByPartition(bytes32 _partition, address _operator) public { _isValidPartition(_partition); partitionApprovals[msg.sender][_partition][_operator] = false; emit RevokedOperatorByPartition(_partition, _operator, msg.sender); } /** * @notice Transfers the ownership of tokens from a specified partition from one address to another address * @param _partition The partition from which to transfer tokens. * @param _from The address from which to transfer tokens from * @param _to The address to which to transfer tokens to * @param _value The amount of tokens to transfer from `_partition` * @param _data Additional data attached to the transfer of tokens * @param _operatorData Additional data attached to the transfer of tokens by the operator * @return The partition to which the transferred tokens were allocated for the _to address */ function operatorTransferByPartition( bytes32 _partition, address _from, address _to, uint256 _value, bytes calldata _data, bytes calldata _operatorData ) external returns (bytes32) { // For the current release we are only allowing UNLOCKED partition tokens to transact _validateOperatorAndPartition(_partition, _from, msg.sender); require(_operatorData[0] != 0); return _transferByPartition(_from, _to, _value, _partition, _data, msg.sender, _operatorData); } function _validateOperatorAndPartition(bytes32 _partition, address _from, address _operator) internal view { _isValidPartition(_partition); _isValidOperator(_from, _operator, _partition); } /** * @notice Updates internal variables when performing a transfer * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer * @param _data data to indicate validation * @return bool success */ function _updateTransfer(address _from, address _to, uint256 _value, bytes memory _data) internal nonReentrant returns(bool verified) { // NB - the ordering in this function implies the following: // - investor counts are updated before transfer managers are called - i.e. transfer managers will see //investor counts including the current transfer. // - checkpoints are updated after the transfer managers are called. This allows TMs to create //checkpoints as though they have been created before the current transactions, // - to avoid the situation where a transfer manager transfers tokens, and this function is called recursively, //the function is marked as nonReentrant. This means that no TM can transfer (or mint / burn) tokens in the execute transfer function. _adjustInvestorCount(_from, _to, _value); verified = _executeTransfer(_from, _to, _value, _data); _adjustBalanceCheckpoints(_from); _adjustBalanceCheckpoints(_to); } /** * @notice Validate transfer with TransferManager module if it exists * @dev TransferManager module has a key of 2 * function (no change in the state). * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer * @param _data data to indicate validation * @return bool */ function _executeTransfer( address _from, address _to, uint256 _value, bytes memory _data ) internal checkGranularity(_value) returns(bool) { if (!transfersFrozen) { bool isInvalid; bool isValid; bool isForceValid; bool unarchived; address module; uint256 tmLength = modules[TRANSFER_KEY].length; for (uint256 i = 0; i < tmLength; i++) { module = modules[TRANSFER_KEY][i]; if (!modulesToData[module].isArchived) { unarchived = true; ITransferManager.Result valid = ITransferManager(module).executeTransfer(_from, _to, _value, _data); if (valid == ITransferManager.Result.INVALID) { isInvalid = true; } else if (valid == ITransferManager.Result.VALID) { isValid = true; } else if (valid == ITransferManager.Result.FORCE_VALID) { isForceValid = true; } } } // If no unarchived modules, return true by default return unarchived ? (isForceValid ? true : (isInvalid ? false : isValid)) : true; } return false; } /** * @notice Permanently freeze issuance of this security token. * @dev It MUST NOT be possible to increase `totalSuppy` after this function is called. */ function freezeIssuance(bytes calldata _signature) external { _onlyOwner(); _isIssuanceAllowed(); _isSignedByOwner(owner() == TokenLib.recoverFreezeIssuanceAckSigner(_signature)); issuance = false; /*solium-disable-next-line security/no-block-members*/ emit FreezeIssuance(); } /** * @notice This function must be called to increase the total supply (Corresponds to mint function of ERC20). * @dev It only be called by the token issuer or the operator defined by the issuer. ERC1594 doesn't have * have the any logic related to operator but its superset ERC1400 have the operator logic and this function * is allowed to call by the operator. * @param _tokenHolder The account that will receive the created tokens (account should be whitelisted or KYCed). * @param _value The amount of tokens need to be issued * @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer. */ function issue( address _tokenHolder, uint256 _value, bytes memory _data ) public // changed to public to save the code size and reuse the function { _isIssuanceAllowed(); _onlyModuleOrOwner(MINT_KEY); _issue(_tokenHolder, _value, _data); } function _issue( address _tokenHolder, uint256 _value, bytes memory _data ) internal { // Add a function to validate the `_data` parameter _isValidTransfer(_updateTransfer(address(0), _tokenHolder, _value, _data)); _mint(_tokenHolder, _value); emit Issued(msg.sender, _tokenHolder, _value, _data); } /** * @notice issue new tokens and assigns them to the target _tokenHolder. * @dev Can only be called by the issuer or STO attached to the token. * @param _tokenHolders A list of addresses to whom the minted tokens will be dilivered * @param _values A list of number of tokens get minted and transfer to corresponding address of the investor from _tokenHolders[] list * @return success */ function issueMulti(address[] memory _tokenHolders, uint256[] memory _values) public { _isIssuanceAllowed(); _onlyModuleOrOwner(MINT_KEY); // Remove reason string to reduce the code size require(_tokenHolders.length == _values.length); for (uint256 i = 0; i < _tokenHolders.length; i++) { _issue(_tokenHolders[i], _values[i], ""); } } /** * @notice Increases totalSupply and the corresponding amount of the specified owners partition * @param _partition The partition to allocate the increase in balance * @param _tokenHolder The token holder whose balance should be increased * @param _value The amount by which to increase the balance * @param _data Additional data attached to the minting of tokens */ function issueByPartition(bytes32 _partition, address _tokenHolder, uint256 _value, bytes calldata _data) external { _isValidPartition(_partition); //Use issue instead of _issue function in the favour to saving code size issue(_tokenHolder, _value, _data); emit IssuedByPartition(_partition, _tokenHolder, _value, _data); } /** * @notice This function redeem an amount of the token of a msg.sender. For doing so msg.sender may incentivize * using different ways that could be implemented with in the `redeem` function definition. But those implementations * are out of the scope of the ERC1594. * @param _value The amount of tokens need to be redeemed * @param _data The `bytes _data` it can be used in the token contract to authenticate the redemption. */ function redeem(uint256 _value, bytes calldata _data) external { _onlyModule(BURN_KEY); _redeem(msg.sender, _value, _data); } function _redeem(address _from, uint256 _value, bytes memory _data) internal { // Add a function to validate the `_data` parameter _isValidRedeem(_checkAndBurn(_from, _value, _data)); } /** * @notice Decreases totalSupply and the corresponding amount of the specified partition of msg.sender * @param _partition The partition to allocate the decrease in balance * @param _value The amount by which to decrease the balance * @param _data Additional data attached to the burning of tokens */ function redeemByPartition(bytes32 _partition, uint256 _value, bytes calldata _data) external { _onlyModule(BURN_KEY); _isValidPartition(_partition); _redeemByPartition(_partition, msg.sender, _value, address(0), _data, ""); } function _redeemByPartition( bytes32 _partition, address _from, uint256 _value, address _operator, bytes memory _data, bytes memory _operatorData ) internal { _redeem(_from, _value, _data); emit RedeemedByPartition(_partition, _operator, _from, _value, _data, _operatorData); } /** * @notice Decreases totalSupply and the corresponding amount of the specified partition of tokenHolder * @dev This function can only be called by the authorised operator. * @param _partition The partition to allocate the decrease in balance. * @param _tokenHolder The token holder whose balance should be decreased * @param _value The amount by which to decrease the balance * @param _data Additional data attached to the burning of tokens * @param _operatorData Additional data attached to the transfer of tokens by the operator */ function operatorRedeemByPartition( bytes32 _partition, address _tokenHolder, uint256 _value, bytes calldata _data, bytes calldata _operatorData ) external { _onlyModule(BURN_KEY); require(_operatorData[0] != 0); _zeroAddressCheck(_tokenHolder); _validateOperatorAndPartition(_partition, _tokenHolder, msg.sender); _redeemByPartition(_partition, _tokenHolder, _value, msg.sender, _data, _operatorData); } function _checkAndBurn(address _from, uint256 _value, bytes memory _data) internal returns(bool verified) { verified = _updateTransfer(_from, address(0), _value, _data); _burn(_from, _value); emit Redeemed(address(0), msg.sender, _value, _data); } /** * @notice This function redeem an amount of the token of a msg.sender. For doing so msg.sender may incentivize * using different ways that could be implemented with in the `redeem` function definition. But those implementations * are out of the scope of the ERC1594. * @dev It is analogy to `transferFrom` * @param _tokenHolder The account whose tokens gets redeemed. * @param _value The amount of tokens need to be redeemed * @param _data The `bytes _data` it can be used in the token contract to authenticate the redemption. */ function redeemFrom(address _tokenHolder, uint256 _value, bytes calldata _data) external { _onlyModule(BURN_KEY); // Add a function to validate the `_data` parameter _isValidRedeem(_updateTransfer(_tokenHolder, address(0), _value, _data)); _burnFrom(_tokenHolder, _value); emit Redeemed(msg.sender, _tokenHolder, _value, _data); } /** * @notice Creates a checkpoint that can be used to query historical balances / totalSuppy * @return uint256 */ function createCheckpoint() external returns(uint256) { _onlyModuleOrOwner(CHECKPOINT_KEY); IDataStore dataStoreInstance = IDataStore(dataStore); // currentCheckpointId can only be incremented by 1 and hence it can not be overflowed currentCheckpointId = currentCheckpointId + 1; /*solium-disable-next-line security/no-block-members*/ checkpointTimes.push(now); checkpointTotalSupply[currentCheckpointId] = totalSupply(); emit CheckpointCreated(currentCheckpointId, dataStoreInstance.getAddressArrayLength(INVESTORSKEY)); return currentCheckpointId; } /** * @notice Used by the issuer to set the controller addresses * @param _controller address of the controller */ function setController(address _controller) external { _onlyOwner(); require(isControllable()); emit SetController(controller, _controller); controller = _controller; } /** * @notice Used by the issuer to permanently disable controller functionality * @dev enabled via feature switch "disableControllerAllowed" */ function disableController(bytes calldata _signature) external { _onlyOwner(); _isSignedByOwner(owner() == TokenLib.recoverDisableControllerAckSigner(_signature)); require(isControllable()); controllerDisabled = true; delete controller; emit DisableController(); } /** * @notice Transfers of securities may fail for a number of reasons. So this function will used to understand the * cause of failure by getting the byte value. Which will be the ESC that follows the EIP 1066. ESC can be mapped * with a reson string to understand the failure cause, table of Ethereum status code will always reside off-chain * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred * @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer. * @return bool It signifies whether the transaction will be executed or not. * @return byte Ethereum status code (ESC) * @return bytes32 Application specific reason code */ function canTransfer(address _to, uint256 _value, bytes calldata _data) external view returns (bool, byte, bytes32) { return _canTransfer(msg.sender, _to, _value, _data); } /** * @notice Transfers of securities may fail for a number of reasons. So this function will used to understand the * cause of failure by getting the byte value. Which will be the ESC that follows the EIP 1066. ESC can be mapped * with a reson string to understand the failure cause, table of Ethereum status code will always reside off-chain * @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 * @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer. * @return bool It signifies whether the transaction will be executed or not. * @return byte Ethereum status code (ESC) * @return bytes32 Application specific reason code */ function canTransferFrom(address _from, address _to, uint256 _value, bytes calldata _data) external view returns (bool success, byte reasonCode, bytes32 appCode) { (success, reasonCode, appCode) = _canTransfer(_from, _to, _value, _data); if (success && _value > allowance(_from, msg.sender)) { return (false, 0x53, bytes32(0)); } } function _canTransfer(address _from, address _to, uint256 _value, bytes memory _data) internal view returns (bool, byte, bytes32) { bytes32 appCode; bool success; if (_value % granularity != 0) { return (false, 0x50, bytes32(0)); } (success, appCode) = TokenLib.verifyTransfer(modules[TRANSFER_KEY], modulesToData, _from, _to, _value, _data, transfersFrozen); return TokenLib.canTransfer(success, appCode, _to, _value, balanceOf(_from)); } /** * @notice The standard provides an on-chain function to determine whether a transfer will succeed, * and return details indicating the reason if the transfer is not valid. * @param _from The address from whom the tokens get transferred. * @param _to The address to which to transfer tokens to. * @param _partition The partition from which to transfer tokens * @param _value The amount of tokens to transfer from `_partition` * @param _data Additional data attached to the transfer of tokens * @return ESC (Ethereum Status Code) following the EIP-1066 standard * @return Application specific reason codes with additional details * @return The partition to which the transferred tokens were allocated for the _to address */ function canTransferByPartition( address _from, address _to, bytes32 _partition, uint256 _value, bytes calldata _data ) external view returns (byte esc, bytes32 appStatusCode, bytes32 toPartition) { if (_partition == UNLOCKED) { bool success; (success, esc, appStatusCode) = _canTransfer(_from, _to, _value, _data); if (success) { uint256 beforeBalance = _balanceOfByPartition(_partition, _to, 0); uint256 afterbalance = _balanceOfByPartition(_partition, _to, _value); toPartition = _returnPartition(beforeBalance, afterbalance, _value); } return (esc, appStatusCode, toPartition); } return (0x50, bytes32(0), bytes32(0)); } /** * @notice Used to attach a new document to the contract, or update the URI or hash of an existing attached document * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always * @param _uri Off-chain uri of the document from where it is accessible to investors/advisors to read. * @param _documentHash hash (of the contents) of the document. */ function setDocument(bytes32 _name, string calldata _uri, bytes32 _documentHash) external { _onlyOwner(); TokenLib.setDocument(_documents, _docNames, _docIndexes, _name, _uri, _documentHash); } /** * @notice Used to remove an existing document from the contract by giving the name of the document. * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always */ function removeDocument(bytes32 _name) external { _onlyOwner(); TokenLib.removeDocument(_documents, _docNames, _docIndexes, _name); } /** * @notice In order to provide transparency over whether `controllerTransfer` / `controllerRedeem` are useable * or not `isControllable` function will be used. * @dev If `isControllable` returns `false` then it always return `false` and * `controllerTransfer` / `controllerRedeem` will always revert. * @return bool `true` when controller address is non-zero otherwise return `false`. */ function isControllable() public view returns (bool) { return !controllerDisabled; } /** * @notice This function allows an authorised address to transfer tokens between any two token holders. * The transfer must still respect the balances of the token holders (so the transfer must be for at most * `balanceOf(_from)` tokens) and potentially also need to respect other transfer restrictions. * @dev This function can only be executed by the `controller` address. * @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 * @param _data data to validate the transfer. (It is not used in this reference implementation * because use of `_data` parameter is implementation specific). * @param _operatorData data attached to the transfer by controller to emit in event. (It is more like a reason string * for calling this function (aka force transfer) which provides the transparency on-chain). */ function controllerTransfer(address _from, address _to, uint256 _value, bytes calldata _data, bytes calldata _operatorData) external { _onlyController(); _updateTransfer(_from, _to, _value, _data); _transfer(_from, _to, _value); emit ControllerTransfer(msg.sender, _from, _to, _value, _data, _operatorData); } /** * @notice This function allows an authorised address to redeem tokens for any token holder. * The redemption must still respect the balances of the token holder (so the redemption must be for at most * `balanceOf(_tokenHolder)` tokens) and potentially also need to respect other transfer restrictions. * @dev This function can only be executed by the `controller` address. * @param _tokenHolder The account whose tokens will be redeemed. * @param _value uint256 the amount of tokens need to be redeemed. * @param _data data to validate the transfer. (It is not used in this reference implementation * because use of `_data` parameter is implementation specific). * @param _operatorData data attached to the transfer by controller to emit in event. (It is more like a reason string * for calling this function (aka force transfer) which provides the transparency on-chain). */ function controllerRedeem(address _tokenHolder, uint256 _value, bytes calldata _data, bytes calldata _operatorData) external { _onlyController(); _checkAndBurn(_tokenHolder, _value, _data); emit ControllerRedemption(msg.sender, _tokenHolder, _value, _data, _operatorData); } function _implementation() internal view returns(address) { return getterDelegate; } function updateFromRegistry() public { _onlyOwner(); moduleRegistry = PolymathRegistry(polymathRegistry).getAddress("ModuleRegistry"); securityTokenRegistry = PolymathRegistry(polymathRegistry).getAddress("SecurityTokenRegistry"); polyToken = PolymathRegistry(polymathRegistry).getAddress("PolyToken"); } //Ownable Functions /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) external { _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; } }
* @notice Authorises an operator for a given partition of `msg.sender` @param _partition The partition to which the operator is authorised @param _operator An address which is being authorised/
function authorizeOperatorByPartition(bytes32 _partition, address _operator) public { _isValidPartition(_partition); partitionApprovals[msg.sender][_partition][_operator] = true; emit AuthorizedOperatorByPartition(_partition, _operator, msg.sender); }
5,505,188
[ 1, 3594, 6141, 392, 3726, 364, 279, 864, 3590, 434, 1375, 3576, 18, 15330, 68, 225, 389, 10534, 1021, 3590, 358, 1492, 326, 3726, 353, 2869, 5918, 225, 389, 9497, 1922, 1758, 1492, 353, 3832, 2869, 5918, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12229, 5592, 858, 7003, 12, 3890, 1578, 389, 10534, 16, 1758, 389, 9497, 13, 1071, 288, 203, 3639, 389, 26810, 7003, 24899, 10534, 1769, 203, 3639, 3590, 12053, 4524, 63, 3576, 18, 15330, 6362, 67, 10534, 6362, 67, 9497, 65, 273, 638, 31, 203, 3639, 3626, 6712, 1235, 5592, 858, 7003, 24899, 10534, 16, 389, 9497, 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 ]
//Address: 0xdf203118a954c918b967a94e51f3570a2faba4ac //Contract name: SuperCountriesEth //Balance: 1.696874206974341727 Ether //Verification Date: 6/7/2018 //Transacion Count: 994 // CODE STARTS HERE pragma solidity ^0.4.24; /* ███████╗██╗ ██╗██████╗ ███████╗██████╗ ██╔════╝██║ ██║██╔══██╗██╔════╝██╔══██╗ ███████╗██║ ██║██████╔╝█████╗ ██████╔╝ ╚════██║██║ ██║██╔═══╝ ██╔══╝ ██╔══██╗ ███████║╚██████╔╝██║ ███████╗██║ ██║ ╚══════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ██████╗ ██████╗ ██╗ ██╗███╗ ██╗████████╗██████╗ ██╗███████╗███████╗ ██╔════╝██╔═══██╗██║ ██║████╗ ██║╚══██╔══╝██╔══██╗██║██╔════╝██╔════╝ ██║ ██║ ██║██║ ██║██╔██╗ ██║ ██║ ██████╔╝██║█████╗ ███████╗ ██║ ██║ ██║██║ ██║██║╚██╗██║ ██║ ██╔══██╗██║██╔══╝ ╚════██║ ╚██████╗╚██████╔╝╚██████╔╝██║ ╚████║ ██║ ██║ ██║██║███████╗███████║ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚══════╝ © 2018 SuperCountries 所有权 - 4CE434B6058EC7C24889EC2512734B5DBA26E39891C09DF50C3CE3191CE9C51E Xuxuxu - LB - Xufo */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract SuperCountriesEth { using SafeMath for uint256; //////////////////////////// /// CONSTRUCTOR /// //////////////////////////// constructor () public { owner = msg.sender; } address public owner; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); //////////////////////// /// EVENTS /// //////////////////////// event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price); event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price); event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event SetReferrerEvent(address indexed referral, address indexed referrer); event PayReferrerEvent(address indexed oldOwner, address indexed referrer1, address indexed referrer2, uint256 referralPart); event BonusConstant(uint256 bonusToDispatch_, uint256 bonusDispatched_, uint256 notYetDispatched_, uint256 indexed _itemSoldId_, uint256 kBonus, uint256 indexed countryScore); event BonusDispatch(uint256 bonusToGet_, uint256 indexed playerScoreForThisCountry_, address indexed player_, uint256 pendingBalanceTotal_, uint256 indexed _itemSoldId); event DivsDispatch(uint256 dividendsCut_, uint256 dividendsScore, uint256 indexed _itemId, uint256 price, uint256 worldScore_); event newRichest(address indexed richest_, uint256 richestScore_, uint256 indexed blocktimestamp_, uint256 indexed blocknumber_); event Withdrawal(address indexed playerAddress, uint256 indexed ethereumWithdrawn, uint256 indexed potVersion_); event ConfirmWithdraw(address indexed playerAddress, uint256 refbonus_, uint256 divs_, uint256 totalPending_, uint256 playerSc_, uint256 _handicap_); event ConfirmPotWithdraw(uint256 contractBalance, address indexed richest_, uint256 richestBalance_, address indexed lastBuyer_, uint256 lastBalance_, uint256 indexed potVersion); event PotWithdrawConstant(uint256 indexed blocktimestamp_, uint256 indexed timestamplimit_, uint256 dividendsScore_, uint256 indexed potVersion, uint256 lastWithdrawPotVersion_); event WithdrawOwner(uint256 indexed potVersion, uint256 indexed lastWithdrawPotVersion_, uint256 indexed balance_); /////////////////////////////////////////// /// VARIABLES, MAPPINGS, STRUCTS /// /////////////////////////////////////////// bool private erc721Enabled = false; /// Price increase limits uint256 private increaseLimit1 = 0.04 ether; uint256 private increaseLimit2 = 0.6 ether; uint256 private increaseLimit3 = 2.5 ether; uint256 private increaseLimit4 = 7.0 ether; /// All countries uint256[] private listedItems; mapping (uint256 => address) private ownerOfItem; mapping (uint256 => uint256) private priceOfItem; mapping (uint256 => uint256) private previousPriceOfItem; mapping (uint256 => address) private approvedOfItem; /// Referrals and their referrers mapping(address => address) public referrerOf; /// Dividends and score uint256 private worldScore ; /// Worldscore = cumulated price of all owned countries + all spent ethers in this game mapping (address => uint256) private playerScore; /// For each player, the sum of each owned country + the sum of all spent ethers since the beginning of the game uint256 private dividendsScore ; /// Balance of dividends divided by the worldScore mapping(uint256 => mapping(address => uint256)) private pendingBalance; /// Divs from referrals, bonus and dividends calculated after the playerScore change ; if the playerScore didn't change recently, there are some pending divs that can be calculated using dividendsScore and playerScore. The first mapping (uint256) is the jackpot version to use, the value goes up after each pot distribution and the previous pendingBalance are reseted. mapping(uint256 => mapping(address => uint256)) private handicap; /// a player cannot claim a % of all dividends but a % of the cumulated dividends after his join date, this is a handicap mapping(uint256 => mapping(address => uint256)) private balanceToWithdraw; /// A player cannot withdraw pending divs, he must request a withdraw first (pending divs move to balanceToWithdraw) then withdraw. uint256 private potVersion = 1; /// Number of jackpots uint256 private lastWithdrawPotVersion = 1; /// Latest withdraw in the game (pot version) address private richestBuyer ; /// current player with the highest PlayerScore address private lastBuyer ; /// current latest buyer in the game uint256 private timestampLimit = 1528108990; /// after this timestamp, the richestBuyer and the lastBuyer will be allowed to withdraw 1/2 of the contract balance (1/4 each) struct CountryStruct { address[] itemToAddressArray; /// addresses that owned the same country uint256 priceHistory; /// cumulated price of the country uint256 startingPrice; /// starting price of the country } mapping (uint256 => CountryStruct) public countryStructs; mapping (uint256 => mapping(address => uint256)) private itemHistory; /// Store price history (cumulated) for each address for each country uint256 private HUGE = 1e13; //////////////////////////////// /// USEFUL MODIFIER /// //////////////////////////////// modifier onlyRealAddress() { require(msg.sender != address(0)); _; } //////////////////////////////// /// ERC721 PRIVILEGES /// //////////////////////////////// modifier onlyERC721() { require(erc721Enabled); _; } /** * @dev Unlocks ERC721 behaviour, allowing for trading on third party platforms. */ function enableERC721 () onlyOwner() public { erc721Enabled = true; } /////////////////////////////////// /// LISTING NEW COUNTRIES /// /////////////////////////////////// function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner) onlyOwner() external { for (uint256 i = 0; i < _itemIds.length; i++) { listItem(_itemIds[i], _price, _owner); } } function listItem (uint256 _itemId, uint256 _price, address _owner) onlyOwner() public { require(_price > 0); require(priceOfItem[_itemId] == 0); require(ownerOfItem[_itemId] == address(0)); ownerOfItem[_itemId] = _owner; priceOfItem[_itemId] = _price; previousPriceOfItem[_itemId] = 0; listedItems.push(_itemId); newEntity(_itemId, _price); } /** * @dev Creates new Struct for a country each time a new country is listed. */ function newEntity(uint256 countryId, uint256 startPrice) private returns(bool success) { countryStructs[countryId].startingPrice = startPrice; return true; } /** * @dev Update the Struc each time a country is sold. * Push the newOwner, update the price history */ function updateEntity(uint256 countryId, address newOwner, uint256 priceUpdate) internal { countryStructs[countryId].priceHistory += priceUpdate; if (itemHistory[countryId][newOwner] == 0 ){ countryStructs[countryId].itemToAddressArray.push(newOwner); } } /////////////////////// /// CALCULATE PRICE /// /////////////////////// function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) { if (_price < increaseLimit1) { return _price.mul(200).div(95); } else if (_price < increaseLimit2) { return _price.mul(160).div(96); } else if (_price < increaseLimit3) { return _price.mul(148).div(97); } else if (_price < increaseLimit4) { return _price.mul(136).div(97); } else { return _price.mul(124).div(98); } } function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) { if (_price < increaseLimit1) { return _price.mul(5).div(100); // 5% } else if (_price < increaseLimit2) { return _price.mul(4).div(100); // 4% } else if (_price < increaseLimit4) { return _price.mul(3).div(100); // 3% } else { return _price.mul(2).div(100); // 2% } } ////////////////////////////// /// BALANCES & WITHDRAWALS /// ////////////////////////////// function getBalance(address _playerAddress) public view returns(uint256 pendingRefBonus_, uint256 pendingFromScore_, uint256 totalPending_, uint256 balanceReadyToWithdraw_, uint256 playerScore_, uint256 handicap_, uint256 dividendsScore_) { uint256 refbonus = pendingBalance[potVersion][_playerAddress]; uint256 playerSc = playerScore[_playerAddress]; uint256 playerHandicap = handicap[potVersion][_playerAddress]; uint256 divs = playerSc.mul(dividendsScore.sub(playerHandicap)).div(HUGE); uint256 totalPending = refbonus.add(divs); uint256 ready = balanceToWithdraw[potVersion][_playerAddress]; return (refbonus, divs, totalPending, ready, playerSc, playerHandicap, dividendsScore); } function getOldBalance(uint256 _potVersion, address _playerAddress) public view returns(uint256 oldPendingRefBonus_, uint256 oldHandicap_, uint256 oldReadyToWithdraw_) { uint256 oldRefBonus = pendingBalance[_potVersion][_playerAddress]; uint256 oldPlayerHandicap = handicap[_potVersion][_playerAddress]; uint256 oldReady = balanceToWithdraw[_potVersion][_playerAddress]; return (oldRefBonus, oldPlayerHandicap, oldReady); } /** * @dev First step to withdraw : players must confirm their pending Divs before withdrawing * this function sums the pending balances (pendingDividends and the pending divs from playerScore) * Then this sum moves to balanceReadyToWithdraw, the player can call the next function and withdraw divs */ function confirmDividends() public onlyRealAddress { require(playerScore[msg.sender] > 0);/// the player exists require (dividendsScore >= handicap[potVersion][msg.sender]); require (dividendsScore >= 0); address _playerAddress = msg.sender; uint256 playerSc = playerScore[_playerAddress]; uint256 handicap_ = handicap[potVersion][_playerAddress]; uint256 refbonus = pendingBalance[potVersion][_playerAddress]; uint256 divs = playerSc.mul(dividendsScore.sub(handicap_)).div(HUGE); uint256 totalPending = refbonus.add(divs); /// Reset the values pendingBalance[potVersion][_playerAddress] = 0; /// Reset the pending balance handicap[potVersion][_playerAddress] = dividendsScore; /// Now the player is ready to withdraw /// balanceToWithdraw[potVersion][_playerAddress] += totalPending; // fire event emit ConfirmWithdraw(_playerAddress, refbonus, divs, totalPending, playerSc, handicap_); } /** * @dev Second step to withdraw : after confirming divs, players can withdraw divs to their wallet */ function withdraw() public onlyRealAddress { require(balanceOf(msg.sender) > 0); require(balanceToWithdraw[potVersion][msg.sender] > 0); address _playerAddress = msg.sender; if (lastWithdrawPotVersion != potVersion){ lastWithdrawPotVersion = potVersion; } /// Add referrals earnings, bonus and divs uint256 divToTransfer = balanceToWithdraw[potVersion][_playerAddress]; balanceToWithdraw[potVersion][_playerAddress] = 0; _playerAddress.transfer(divToTransfer); /// fire event emit Withdrawal(_playerAddress, divToTransfer, potVersion); } /** * @dev After 7 days without any buy, the richest user and the latest player will share the contract balance ! */ function confirmDividendsFromPot() public { require(richestBuyer != address(0) && lastBuyer != address(0)) ; require(address(this).balance > 100000000); /// mini 1e8 wei require(block.timestamp > timestampLimit); uint256 confirmation_TimeStamp = timestampLimit; potVersion ++; uint256 balance = address(this).balance; uint256 balanceQuarter = balance.div(4); dividendsScore = 0; /// reset dividends updateTimestampLimit(); /// Reset the timer, if no new buys, the richest and the last buyers will be able to withdraw the left quarter in a week or so balanceToWithdraw[potVersion][richestBuyer] = balanceQuarter; balanceToWithdraw[potVersion][lastBuyer] += balanceQuarter; /// if the richest = last, dividends cumulate // fire events emit ConfirmPotWithdraw( balance, richestBuyer, balanceToWithdraw[potVersion][richestBuyer], lastBuyer, balanceToWithdraw[potVersion][lastBuyer], potVersion ); emit PotWithdrawConstant( block.timestamp, confirmation_TimeStamp, dividendsScore, potVersion, lastWithdrawPotVersion ); } /** * @dev If no new buys occur (dividendsScore = 0) and the richest and latest players don't withdraw their dividends after 3 jackpots, the game can be stuck forever * Prevent from jackpot vicious circle : same dividends are shared between latest and richest users again and again * If the richest and/or the latest player withdraw(s) at least once between 3 jackpots, it means the game is alive * Or if contract balance drops down to 1e8 wei (that means many successful jackpots and that a current withdrawal could cost too much gas for players) */ function withdrawAll() public onlyOwner { require((potVersion > lastWithdrawPotVersion.add(3) && dividendsScore == 0) || (address(this).balance < 100000001) ); require (address(this).balance >0); potVersion ++; updateTimestampLimit(); uint256 balance = address(this).balance; owner.transfer(balance); // fire event emit WithdrawOwner(potVersion, lastWithdrawPotVersion, balance); } /////////////////////////////////////// /// REFERRERS - Setting and payment /// /////////////////////////////////////// /** * @dev Get the referrer of a player. * @param player The address of the player to get the referrer of. */ function getReferrerOf(address player) public view returns (address) { return referrerOf[player]; } /** * @dev Set a referrer. * @param newReferral The address to set the referrer for. * @param referrer The address of the referrer to set. * The referrer must own at least one country to keep his reflink active * Referrals got with an active link are forever, even if all the referrer's countries are sold */ function setReferrer(address newReferral, address referrer) internal { if (getReferrerOf(newReferral) == address(0x0) && newReferral != referrer && balanceOf(referrer) > 0 && playerScore[newReferral] == 0) { /// Set the referrer, if no referrer has been set yet, and the player /// and referrer are not the same address. referrerOf[newReferral] = referrer; /// Emit event. emit SetReferrerEvent(newReferral, referrer); } } /** * @dev Dispatch the referrer bonus when a country is sold * @param referralDivToPay which dividends percentage will be dispatched to refererrs : 0 if no referrer, 2.5% if 1 referrer, 5% if 2 */ function payReferrer (address _oldOwner, uint256 _netProfit) internal returns (uint256 referralDivToPay) { address referrer_1 = referrerOf[_oldOwner]; if (referrer_1 != 0x0) { referralDivToPay = _netProfit.mul(25).div(1000); pendingBalance[potVersion][referrer_1] += referralDivToPay; /// 2.5% for the first referrer address referrer_2 = referrerOf[referrer_1]; if (referrer_2 != 0x0) { pendingBalance[potVersion][referrer_2] += referralDivToPay; /// 2.5% for the 2nd referrer referralDivToPay += referralDivToPay; } } emit PayReferrerEvent(_oldOwner, referrer_1, referrer_2, referralDivToPay); return referralDivToPay; } /////////////////////////////////// /// INTERNAL FUNCTIONS WHEN BUY /// /////////////////////////////////// /** * @dev Dispatch dividends to former owners of a country */ function bonusPreviousOwner(uint256 _itemSoldId, uint256 _paidPrice, uint256 _bonusToDispatch) private { require(_bonusToDispatch < (_paidPrice.mul(5).div(100))); require(countryStructs[_itemSoldId].priceHistory > 0); CountryStruct storage c = countryStructs[_itemSoldId]; uint256 countryScore = c.priceHistory; uint256 kBonus = _bonusToDispatch.mul(HUGE).div(countryScore); uint256 bonusDispatched = 0; for (uint256 i = 0; i < c.itemToAddressArray.length && bonusDispatched < _bonusToDispatch ; i++) { address listedBonusPlayer = c.itemToAddressArray[i]; uint256 playerBonusScore = itemHistory[_itemSoldId][listedBonusPlayer]; uint256 bonusToGet = playerBonusScore.mul(kBonus).div(HUGE); if (bonusDispatched.add(bonusToGet) <= _bonusToDispatch) { pendingBalance[potVersion][listedBonusPlayer] += bonusToGet; bonusDispatched += bonusToGet; emitInfo(bonusToGet, playerBonusScore, listedBonusPlayer, pendingBalance[potVersion][listedBonusPlayer], _itemSoldId); } } emit BonusConstant(_bonusToDispatch, bonusDispatched, _bonusToDispatch.sub(bonusDispatched), _itemSoldId, kBonus, countryScore); } function emitInfo(uint256 dividendsToG_, uint256 playerSc_, address player_, uint256 divsBalance_, uint256 itemId_) private { emit BonusDispatch(dividendsToG_, playerSc_, player_, divsBalance_, itemId_); } /** * @dev we need to update the oldOwner and newOwner balances each time a country is sold, their handicap and playerscore will also change * Worldscore and dividendscore : we don't care, it will be updated later. * If accurate, set a new richest player */ function updateScoreAndBalance(uint256 _paidPrice, uint256 _itemId, address _oldOwner, address _newOwner) internal { uint256 _previousPaidPrice = previousPriceOfItem[_itemId]; assert (_paidPrice > _previousPaidPrice); /// OLD OWNER /// uint256 scoreSubHandicap = dividendsScore.sub(handicap[potVersion][_oldOwner]); uint256 playerScore_ = playerScore[_oldOwner]; /// If the old owner is the owner of this contract, we skip this part, the owner of the contract won't get dividends if (_oldOwner != owner && scoreSubHandicap >= 0 && playerScore_ > _previousPaidPrice) { pendingBalance[potVersion][_oldOwner] += playerScore_.mul(scoreSubHandicap).div(HUGE); playerScore[_oldOwner] -= _previousPaidPrice; ///for the oldOwner, the playerScore goes down the previous price handicap[potVersion][_oldOwner] = dividendsScore; /// and setting his handicap to dividendsScore after updating his balance } /// NEW OWNER /// scoreSubHandicap = dividendsScore.sub(handicap[potVersion][_newOwner]); /// Rewrite the var with the newOwner values playerScore_ = playerScore[_newOwner]; /// Rewrite the var playerScore with the newOwner PlayerScore /// If new player, his playerscore = 0, handicap = 0, so the pendingBalance math = 0 if (scoreSubHandicap >= 0) { pendingBalance[potVersion][_newOwner] += playerScore_.mul(scoreSubHandicap).div(HUGE); playerScore[_newOwner] += _paidPrice.mul(2); ///for the newOwner, the playerScore goes up twice the value of the purchase price handicap[potVersion][_newOwner] = dividendsScore; /// and setting his handicap to dividendsScore after updating his balance } /// Change the richest user if this is the case... if (playerScore[_newOwner] > playerScore[richestBuyer]) { richestBuyer = _newOwner; emit newRichest(_newOwner, playerScore[_newOwner], block.timestamp, block.number); } /// Change the last Buyer in any case lastBuyer = _newOwner; } /** * @dev Update the worldScore * After each buy, the worldscore increases : 2x current purchase price - 1x previousPrice */ function updateWorldScore(uint256 _countryId, uint256 _price) internal { worldScore += _price.mul(2).sub(previousPriceOfItem[_countryId]); } /** * @dev Update timestampLimit : the date on which the richest player and the last buyer will be able to share the contract balance (1/4 each) */ function updateTimestampLimit() internal { timestampLimit = block.timestamp.add(604800).add(potVersion.mul(28800)); /// add 7 days + (pot version * X 8hrs) } /** * @dev Refund the buyer if excess */ function excessRefund(address _newOwner, uint256 _price) internal { uint256 excess = msg.value.sub(_price); if (excess > 0) { _newOwner.transfer(excess); } } /////////////////////////// /// BUY A COUNTRY /// /////////////////////////// /* Buy a country directly from the contract for the calculated price which ensures that the owner gets a profit. All countries that have been listed can be bought by this method. User funds are sent directly to the previous owner and are never stored in the contract. */ function buy (uint256 _itemId, address referrerAddress) payable public onlyRealAddress { require(priceOf(_itemId) > 0); require(ownerOf(_itemId) != address(0)); require(msg.value >= priceOf(_itemId)); require(ownerOf(_itemId) != msg.sender); require(!isContract(msg.sender)); require(msg.sender != owner); require(block.timestamp < timestampLimit || block.timestamp > timestampLimit.add(3600)); address oldOwner = ownerOf(_itemId); address newOwner = msg.sender; uint256 price = priceOf(_itemId); //////////////////////// /// Set the referrer /// //////////////////////// setReferrer(newOwner, referrerAddress); /////////////////////////////////// /// Update scores and timestamp /// /////////////////////////////////// /// Dividends are dispatched among players accordingly to their "playerScore". /// The playerScore equals the sum of all their countries (owned now, paid price) + sum of all their previously owned countries /// After each sell / buy, players that owned at least one country can claim dividends /// DIVS of a player = playerScore * DIVS to dispatch / worldScore /// If a player is a seller or a buyer, his playerScore will change, we need to adjust his parameters /// If a player is not a buyer / seller, his playerScore doesn't change, no need to adjust updateScoreAndBalance(price, _itemId, oldOwner, newOwner); /// worldScore change after each flip, we need to adjust /// To calculate the worldScore after a flip: add buy price x 2, subtract previous price updateWorldScore(_itemId, price); /// If 7 days with no buys, the richest player and the last buyer win the jackpot (1/2 of contract balance ; 1/4 each) /// Waiting time increases after each pot distribution updateTimestampLimit(); /////////////////////// /// Who earns what? /// /////////////////////// /// When a country flips, who earns how much? /// Devs : 2% to 5% of country price /// Seller's reward : current paidPrice - previousPrice - devsCut = net profit. The seller gets the previous Price + ca.65% of net Profit /// The referrers of the seller : % of netProfit from their referrals R+1 & R+2. If no referrers, all the referrers' cut goes to dividends to all players. /// All players, with or without a country now : dividends (% of netProfit) /// All previous owners of the flipped country : a special part of dividends called Bonus. If no previous buyer, all the bonus is also added up to dividends to all players. /// Calculate the devs cut uint256 devCut_ = calculateDevCut(price); /// Calculate the netProfit uint256 netProfit = price.sub(devCut_).sub(previousPriceOfItem[_itemId]); /// Calculate dividends cut from netProfit and what referrers left uint256 dividendsCut_ = netProfit.mul(30).div(100); /// Calculate the seller's reward /// Price sub the cuts : dev cut and 35% including referrer cut (5% max), 30% (25% if referrers) dividends (including 80% divs / 20% bonus max) and 5% (jackpot) uint256 oldOwnerReward = price.sub(devCut_).sub(netProfit.mul(35).div(100)); /// Calculate the referrers cut and store the referrer's cut in the referrer's pending balance /// /// Update dividend's cut : 30% max ; 27,5% if 1 referrer ; 25% if 2 referrers uint256 refCut = payReferrer(oldOwner, netProfit); dividendsCut_ -= refCut; //////////////////////////////////////////////////////////// /// Dispatch dividends to all players /// /// Dispatch bonuses to previous owners of this country /// //////////////////////////////////////////////////////////// /// Dividends = 80% to all country owners (previous and current owners, no matter the country) + 20% bonus to previous owners of this country /// If no previous owners, 100% to all countries owners /// Are there previous owners for the current flipped country? if (price > countryStructs[_itemId].startingPrice && dividendsCut_ > 1000000 && worldScore > 0) { /// Yes, there are previous owners, they will get 20% of dividends of this country bonusPreviousOwner(_itemId, price, dividendsCut_.mul(20).div(100)); /// So dividends for all the country owners are 100% - 20% = 80% dividendsCut_ = dividendsCut_.mul(80).div(100); } /// If else... nothing special to do, there are no previous owners, dividends remain 100% /// Dispatch dividends to all country owners, no matter the country /// Note : to avoid floating numbers, we divide a constant called HUGE (1e13) by worldScore, of course we will multiply by HUGE when retrieving if (worldScore > 0) { /// worldScore must be greater than 0, the opposite is impossible and dividends are not calculated dividendsScore += HUGE.mul(dividendsCut_).div(worldScore); } //////////////////////////////////////////////// /// Update the price history of the newOwner /// //////////////////////////////////////////////// /// The newOwner is now known as an OWNER for this country /// We'll store his cumulated buy price for this country in a mapping /// Bonus : each time a country is flipped, players that previously owned this country get bonuses proportionally to the sum of their buys updateEntity(_itemId, newOwner, price); itemHistory[_itemId][newOwner] += price; //////////////////////// /// Update the price /// //////////////////////// /// The price of purchase becomes the "previousPrice", and the "price" is the next price previousPriceOfItem[_itemId] = price; priceOfItem[_itemId] = nextPriceOf(_itemId); ///////////////////////////////////////// /// Transfer the reward to the seller /// ///////////////////////////////////////// /// The seller's reward is transfered automatically to his wallet /// The dev cut is transfered automatically out the contract /// The other rewards (bonus, dividends, referrer's cut) will be stored in a pending balance oldOwner.transfer(oldOwnerReward); owner.transfer(devCut_); /// Transfer the token from oldOwner to newOwner _transfer(oldOwner, newOwner, _itemId); /// Emit the events emit Bought(_itemId, newOwner, price); emit Sold(_itemId, oldOwner, price); /////////////////////////////////////////// /// Transfer the excess to the newOwner /// /////////////////////////////////////////// /// If the newOwner sent a higher price than the asked price, the excess is refunded excessRefund(newOwner, price); /// Send informations emit DivsDispatch(dividendsCut_, dividendsScore, _itemId, price, worldScore); /// END OF THE BUY FUNCTION /// } ////////////////////////////// /// Practical informations /// ////////////////////////////// function itemHistoryOfPlayer(uint256 _itemId, address _owner) public view returns (uint256 _valueAddressOne) { return itemHistory[_itemId][_owner]; } function implementsERC721() public view returns (bool _implements) { return erc721Enabled; } function name() public pure returns (string _name) { return "SuperCountries"; } function symbol() public pure returns (string _symbol) { return "SUP"; } function totalSupply() public view returns (uint256 _totalSupply) { return listedItems.length; } function balanceOf (address _owner) public view returns (uint256 _balance) { uint256 counter = 0; for (uint256 i = 0; i < listedItems.length; i++) { if (ownerOf(listedItems[i]) == _owner) { counter++; } } return counter; } function ownerOf (uint256 _itemId) public view returns (address _owner) { return ownerOfItem[_itemId]; } function tokensOf (address _owner) public view returns (uint256[] _tokenIds) { uint256[] memory items = new uint256[](balanceOf(_owner)); uint256 itemCounter = 0; for (uint256 i = 0; i < listedItems.length; i++) { if (ownerOf(listedItems[i]) == _owner) { items[itemCounter] = listedItems[i]; itemCounter += 1; } } return items; } function tokenExists (uint256 _itemId) public view returns (bool _exists) { return priceOf(_itemId) > 0; } function approvedFor(uint256 _itemId) public view returns (address _approved) { return approvedOfItem[_itemId]; } function approve(address _to, uint256 _itemId) onlyERC721() public { require(msg.sender != _to); require(tokenExists(_itemId)); require(ownerOf(_itemId) == msg.sender); if (_to == 0) { if (approvedOfItem[_itemId] != 0) { delete approvedOfItem[_itemId]; emit Approval(msg.sender, 0, _itemId); } } else { approvedOfItem[_itemId] = _to; emit Approval(msg.sender, _to, _itemId); } } /* Transferring a country to another owner will entitle the new owner the profits from `buy` */ function transfer(address _to, uint256 _itemId) onlyERC721() public { require(msg.sender == ownerOf(_itemId)); _transfer(msg.sender, _to, _itemId); } function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public { require(approvedFor(_itemId) == msg.sender); _transfer(_from, _to, _itemId); } function _transfer(address _from, address _to, uint256 _itemId) internal { require(tokenExists(_itemId)); require(ownerOf(_itemId) == _from); require(_to != address(0)); require(_to != address(this)); ownerOfItem[_itemId] = _to; approvedOfItem[_itemId] = 0; emit Transfer(_from, _to, _itemId); } /////////////////////////// /// READ ONLY FUNCTIONS /// /////////////////////////// function gameInfo() public view returns (address richestPlayer_, address lastBuyer_, uint256 thisBalance_, uint256 lastWithdrawPotVersion_, uint256 worldScore_, uint256 potVersion_, uint256 timestampLimit_) { return (richestBuyer, lastBuyer, address(this).balance, lastWithdrawPotVersion, worldScore, potVersion, timestampLimit); } function priceOf(uint256 _itemId) public view returns (uint256 _price) { return priceOfItem[_itemId]; } function nextPriceOf(uint256 _itemId) public view returns (uint256 _nextPrice) { return calculateNextPrice(priceOf(_itemId)); } function allOf(uint256 _itemId) external view returns (address _owner, uint256 _price, uint256 previous_, uint256 _nextPrice) { return (ownerOf(_itemId), priceOf(_itemId), previousPriceOfItem[_itemId], nextPriceOf(_itemId)); } /// is Contract /// function isContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } // solium-disable-line return size > 0; } //////////////////////// /// USEFUL FUNCTIONS /// //////////////////////// /** * @dev Fallback function to accept all ether sent directly to the contract * Nothing is lost, it will raise the jackpot ! */ function() payable public { } }
/ Number of jackpots
uint256 private potVersion = 1;
2,504,856
[ 1, 19, 3588, 434, 525, 484, 84, 6968, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 3238, 5974, 1444, 273, 404, 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 ]
./full_match/1/0xC681443668CAB4057A99c2ABEB8CE98b459c1F56/sources/contract.sol
* @dev Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); pragma abicoder v2; }
16,433,312
[ 1, 1358, 434, 326, 4232, 39, 28275, 4529, 16, 487, 2553, 316, 326, 10886, 414, 848, 14196, 2865, 434, 6835, 7349, 16, 1492, 848, 1508, 506, 23264, 635, 10654, 10797, 654, 39, 28275, 8847, 97, 2934, 2457, 392, 4471, 16, 2621, 288, 654, 39, 28275, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 28275, 288, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 683, 9454, 1223, 335, 5350, 331, 22, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xeD46905dCf00f7234F6BD90Fa58F38c10a2F8852/sources/browser/URNC.sol
* Token name : UrgentRN Coin Symbol : URNC Total Supply : 2640M decimals : 0/
contract UrgentRN 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; } constructor () public { _name = "UrgentRN Coin"; _symbol = "URNC"; _decimals = 0; _totalSupply = 2640000000; _balances[_msgSender()] = _totalSupply; emit Transfer(address(0),_msgSender(), _totalSupply); } 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"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, 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); } }
4,948,997
[ 1, 1345, 508, 282, 294, 587, 26876, 319, 54, 50, 28932, 8565, 4202, 294, 1618, 10346, 10710, 3425, 1283, 294, 576, 1105, 20, 49, 15105, 377, 294, 374, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 587, 26876, 319, 54, 50, 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, 97, 203, 565, 3885, 1832, 1071, 288, 203, 3639, 389, 529, 273, 315, 57, 26876, 319, 54, 50, 28932, 14432, 203, 3639, 389, 7175, 273, 315, 8521, 39, 14432, 203, 3639, 389, 31734, 273, 374, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 576, 1105, 17877, 31, 203, 203, 3639, 389, 70, 26488, 63, 67, 3576, 12021, 1435, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 67, 3576, 12021, 9334, 389, 4963, 3088, 1283, 1769, 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, 2 ]
// SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 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.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../errors/LibMetaTransactionsRichErrors.sol"; import "../fixins/FixinCommon.sol"; import "../fixins/FixinReentrancyGuard.sol"; import "../fixins/FixinTokenSpender.sol"; import "../fixins/FixinEIP712.sol"; import "../migrations/LibMigrate.sol"; import "../storage/LibMetaTransactionsStorage.sol"; import "./interfaces/IFeature.sol"; import "./interfaces/IMetaTransactionsFeature.sol"; import "./interfaces/INativeOrdersFeature.sol"; import "./interfaces/ITransformERC20Feature.sol"; import "./libs/LibSignature.sol"; /// @dev MetaTransactions feature. contract MetaTransactionsFeature is IFeature, IMetaTransactionsFeature, FixinCommon, FixinReentrancyGuard, FixinEIP712, FixinTokenSpender { using LibBytesV06 for bytes; using LibRichErrorsV06 for bytes; /// @dev Describes the state of a meta transaction. struct ExecuteState { // Sender of the meta-transaction. address sender; // Hash of the meta-transaction data. bytes32 hash; // The meta-transaction data. MetaTransactionData mtx; // The meta-transaction signature (by `mtx.signer`). LibSignature.Signature signature; // The selector of the function being called. bytes4 selector; // The ETH balance of this contract before performing the call. uint256 selfBalance; // The block number at which the meta-transaction was executed. uint256 executedBlockNumber; } /// @dev Arguments for a `TransformERC20.transformERC20()` call. struct ExternalTransformERC20Args { IERC20TokenV06 inputToken; IERC20TokenV06 outputToken; uint256 inputTokenAmount; uint256 minOutputTokenAmount; ITransformERC20Feature.Transformation[] transformations; } /// @dev Name of this feature. string public constant override FEATURE_NAME = "MetaTransactions"; /// @dev Version of this feature. uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 2, 1); /// @dev EIP712 typehash of the `MetaTransactionData` struct. bytes32 public immutable MTX_EIP712_TYPEHASH = keccak256( "MetaTransactionData(" "address signer," "address sender," "uint256 minGasPrice," "uint256 maxGasPrice," "uint256 expirationTimeSeconds," "uint256 salt," "bytes callData," "uint256 value," "address feeToken," "uint256 feeAmount" ")" ); /// @dev Refunds up to `msg.value` leftover ETH at the end of the call. modifier refundsAttachedEth() { _; uint256 remainingBalance = LibSafeMathV06.min256(msg.value, address(this).balance); if (remainingBalance > 0) { msg.sender.transfer(remainingBalance); } } /// @dev Ensures that the ETH balance of `this` does not go below the /// initial ETH balance before the call (excluding ETH attached to the call). modifier doesNotReduceEthBalance() { uint256 initialBalance = address(this).balance - msg.value; _; require( initialBalance <= address(this).balance, "MetaTransactionsFeature/ETH_LEAK" ); } constructor(address zeroExAddress) public FixinCommon() FixinEIP712(zeroExAddress) { // solhint-disable-next-line no-empty-blocks } /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.executeMetaTransaction.selector); _registerFeatureFunction(this.batchExecuteMetaTransactions.selector); _registerFeatureFunction(this.getMetaTransactionExecutedBlock.selector); _registerFeatureFunction(this.getMetaTransactionHashExecutedBlock.selector); _registerFeatureFunction(this.getMetaTransactionHash.selector); return LibMigrate.MIGRATE_SUCCESS; } /// @dev Execute a single meta-transaction. /// @param mtx The meta-transaction. /// @param signature The signature by `mtx.signer`. /// @return returnResult The ABI-encoded result of the underlying call. function executeMetaTransaction( MetaTransactionData memory mtx, LibSignature.Signature memory signature ) public payable override nonReentrant(REENTRANCY_MTX) doesNotReduceEthBalance refundsAttachedEth returns (bytes memory returnResult) { ExecuteState memory state; state.sender = msg.sender; state.mtx = mtx; state.hash = getMetaTransactionHash(mtx); state.signature = signature; returnResult = _executeMetaTransactionPrivate(state); } /// @dev Execute multiple meta-transactions. /// @param mtxs The meta-transactions. /// @param signatures The signature by each respective `mtx.signer`. /// @return returnResults The ABI-encoded results of the underlying calls. function batchExecuteMetaTransactions( MetaTransactionData[] memory mtxs, LibSignature.Signature[] memory signatures ) public payable override nonReentrant(REENTRANCY_MTX) doesNotReduceEthBalance refundsAttachedEth returns (bytes[] memory returnResults) { if (mtxs.length != signatures.length) { LibMetaTransactionsRichErrors.InvalidMetaTransactionsArrayLengthsError( mtxs.length, signatures.length ).rrevert(); } returnResults = new bytes[](mtxs.length); for (uint256 i = 0; i < mtxs.length; ++i) { ExecuteState memory state; state.sender = msg.sender; state.mtx = mtxs[i]; state.hash = getMetaTransactionHash(mtxs[i]); state.signature = signatures[i]; returnResults[i] = _executeMetaTransactionPrivate(state); } } /// @dev Get the block at which a meta-transaction has been executed. /// @param mtx The meta-transaction. /// @return blockNumber The block height when the meta-transactioin was executed. function getMetaTransactionExecutedBlock(MetaTransactionData memory mtx) public override view returns (uint256 blockNumber) { return getMetaTransactionHashExecutedBlock(getMetaTransactionHash(mtx)); } /// @dev Get the block at which a meta-transaction hash has been executed. /// @param mtxHash The meta-transaction hash. /// @return blockNumber The block height when the meta-transactioin was executed. function getMetaTransactionHashExecutedBlock(bytes32 mtxHash) public override view returns (uint256 blockNumber) { return LibMetaTransactionsStorage.getStorage().mtxHashToExecutedBlockNumber[mtxHash]; } /// @dev Get the EIP712 hash of a meta-transaction. /// @param mtx The meta-transaction. /// @return mtxHash The EIP712 hash of `mtx`. function getMetaTransactionHash(MetaTransactionData memory mtx) public override view returns (bytes32 mtxHash) { return _getEIP712Hash(keccak256(abi.encode( MTX_EIP712_TYPEHASH, mtx.signer, mtx.sender, mtx.minGasPrice, mtx.maxGasPrice, mtx.expirationTimeSeconds, mtx.salt, keccak256(mtx.callData), mtx.value, mtx.feeToken, mtx.feeAmount ))); } /// @dev Execute a meta-transaction by `sender`. Low-level, hidden variant. /// @param state The `ExecuteState` for this metatransaction, with `sender`, /// `hash`, `mtx`, and `signature` fields filled. /// @return returnResult The ABI-encoded result of the underlying call. function _executeMetaTransactionPrivate(ExecuteState memory state) private returns (bytes memory returnResult) { _validateMetaTransaction(state); // Mark the transaction executed by storing the block at which it was executed. // Currently the block number just indicates that the mtx was executed and // serves no other purpose from within this contract. LibMetaTransactionsStorage.getStorage() .mtxHashToExecutedBlockNumber[state.hash] = block.number; // Pay the fee to the sender. if (state.mtx.feeAmount > 0) { _transferERC20TokensFrom( state.mtx.feeToken, state.mtx.signer, state.sender, state.mtx.feeAmount ); } // Execute the call based on the selector. state.selector = state.mtx.callData.readBytes4(0); if (state.selector == ITransformERC20Feature.transformERC20.selector) { returnResult = _executeTransformERC20Call(state); } else if (state.selector == INativeOrdersFeature.fillLimitOrder.selector) { returnResult = _executeFillLimitOrderCall(state); } else if (state.selector == INativeOrdersFeature.fillRfqOrder.selector) { returnResult = _executeFillRfqOrderCall(state); } else { LibMetaTransactionsRichErrors .MetaTransactionUnsupportedFunctionError(state.hash, state.selector) .rrevert(); } emit MetaTransactionExecuted( state.hash, state.selector, state.mtx.signer, state.mtx.sender ); } /// @dev Validate that a meta-transaction is executable. function _validateMetaTransaction(ExecuteState memory state) private view { // Must be from the required sender, if set. if (state.mtx.sender != address(0) && state.mtx.sender != state.sender) { LibMetaTransactionsRichErrors .MetaTransactionWrongSenderError( state.hash, state.sender, state.mtx.sender ).rrevert(); } // Must not be expired. if (state.mtx.expirationTimeSeconds <= block.timestamp) { LibMetaTransactionsRichErrors .MetaTransactionExpiredError( state.hash, block.timestamp, state.mtx.expirationTimeSeconds ).rrevert(); } // Must have a valid gas price. if (state.mtx.minGasPrice > tx.gasprice || state.mtx.maxGasPrice < tx.gasprice) { LibMetaTransactionsRichErrors .MetaTransactionGasPriceError( state.hash, tx.gasprice, state.mtx.minGasPrice, state.mtx.maxGasPrice ).rrevert(); } // Must have enough ETH. state.selfBalance = address(this).balance; if (state.mtx.value > state.selfBalance) { LibMetaTransactionsRichErrors .MetaTransactionInsufficientEthError( state.hash, state.selfBalance, state.mtx.value ).rrevert(); } if (LibSignature.getSignerOfHash(state.hash, state.signature) != state.mtx.signer) { LibSignatureRichErrors.SignatureValidationError( LibSignatureRichErrors.SignatureValidationErrorCodes.WRONG_SIGNER, state.hash, state.mtx.signer, // TODO: Remove this field from SignatureValidationError // when rich reverts are part of the protocol repo. "" ).rrevert(); } // Transaction must not have been already executed. state.executedBlockNumber = LibMetaTransactionsStorage .getStorage().mtxHashToExecutedBlockNumber[state.hash]; if (state.executedBlockNumber != 0) { LibMetaTransactionsRichErrors .MetaTransactionAlreadyExecutedError( state.hash, state.executedBlockNumber ).rrevert(); } } /// @dev Execute a `ITransformERC20Feature.transformERC20()` meta-transaction call /// by decoding the call args and translating the call to the internal /// `ITransformERC20Feature._transformERC20()` variant, where we can override /// the taker address. function _executeTransformERC20Call(ExecuteState memory state) private returns (bytes memory returnResult) { // HACK(dorothy-zbornak): `abi.decode()` with the individual args // will cause a stack overflow. But we can prefix the call data with an // offset to transform it into the encoding for the equivalent single struct arg, // since decoding a single struct arg consumes far less stack space than // decoding multiple struct args. // Where the encoding for multiple args (with the selector ommitted) // would typically look like: // | argument | offset | // |--------------------------|---------| // | inputToken | 0 | // | outputToken | 32 | // | inputTokenAmount | 64 | // | minOutputTokenAmount | 96 | // | transformations (offset) | 128 | = 32 // | transformations (data) | 160 | // We will ABI-decode a single struct arg copy with the layout: // | argument | offset | // |--------------------------|---------| // | (arg 1 offset) | 0 | = 32 // | inputToken | 32 | // | outputToken | 64 | // | inputTokenAmount | 96 | // | minOutputTokenAmount | 128 | // | transformations (offset) | 160 | = 32 // | transformations (data) | 192 | ExternalTransformERC20Args memory args; { bytes memory encodedStructArgs = new bytes(state.mtx.callData.length - 4 + 32); // Copy the args data from the original, after the new struct offset prefix. bytes memory fromCallData = state.mtx.callData; assert(fromCallData.length >= 160); uint256 fromMem; uint256 toMem; assembly { // Prefix the calldata with a struct offset, // which points to just one word over. mstore(add(encodedStructArgs, 32), 32) // Copy everything after the selector. fromMem := add(fromCallData, 36) // Start copying after the struct offset. toMem := add(encodedStructArgs, 64) } LibBytesV06.memCopy(toMem, fromMem, fromCallData.length - 4); // Decode call args for `ITransformERC20Feature.transformERC20()` as a struct. args = abi.decode(encodedStructArgs, (ExternalTransformERC20Args)); } // Call `ITransformERC20Feature._transformERC20()` (internal variant). return _callSelf( state.hash, abi.encodeWithSelector( ITransformERC20Feature._transformERC20.selector, ITransformERC20Feature.TransformERC20Args({ taker: state.mtx.signer, // taker is mtx signer inputToken: args.inputToken, outputToken: args.outputToken, inputTokenAmount: args.inputTokenAmount, minOutputTokenAmount: args.minOutputTokenAmount, transformations: args.transformations, useSelfBalance: false, recipient: state.mtx.signer }) ), state.mtx.value ); } /// @dev Extract arguments from call data by copying everything after the /// 4-byte selector into a new byte array. /// @param callData The call data from which arguments are to be extracted. /// @return args The extracted arguments as a byte array. function _extractArgumentsFromCallData( bytes memory callData ) private pure returns (bytes memory args) { args = new bytes(callData.length - 4); uint256 fromMem; uint256 toMem; assembly { fromMem := add(callData, 36) // skip length and 4-byte selector toMem := add(args, 32) // write after length prefix } LibBytesV06.memCopy(toMem, fromMem, args.length); return args; } /// @dev Execute a `INativeOrdersFeature.fillLimitOrder()` meta-transaction call /// by decoding the call args and translating the call to the internal /// `INativeOrdersFeature._fillLimitOrder()` variant, where we can override /// the taker address. function _executeFillLimitOrderCall(ExecuteState memory state) private returns (bytes memory returnResult) { LibNativeOrder.LimitOrder memory order; LibSignature.Signature memory signature; uint128 takerTokenFillAmount; bytes memory args = _extractArgumentsFromCallData(state.mtx.callData); (order, signature, takerTokenFillAmount) = abi.decode(args, (LibNativeOrder.LimitOrder, LibSignature.Signature, uint128)); return _callSelf( state.hash, abi.encodeWithSelector( INativeOrdersFeature._fillLimitOrder.selector, order, signature, takerTokenFillAmount, state.mtx.signer, // taker is mtx signer msg.sender ), state.mtx.value ); } /// @dev Execute a `INativeOrdersFeature.fillRfqOrder()` meta-transaction call /// by decoding the call args and translating the call to the internal /// `INativeOrdersFeature._fillRfqOrder()` variant, where we can overrideunimpleme /// the taker address. function _executeFillRfqOrderCall(ExecuteState memory state) private returns (bytes memory returnResult) { LibNativeOrder.RfqOrder memory order; LibSignature.Signature memory signature; uint128 takerTokenFillAmount; bytes memory args = _extractArgumentsFromCallData(state.mtx.callData); (order, signature, takerTokenFillAmount) = abi.decode(args, (LibNativeOrder.RfqOrder, LibSignature.Signature, uint128)); return _callSelf( state.hash, abi.encodeWithSelector( INativeOrdersFeature._fillRfqOrder.selector, order, signature, takerTokenFillAmount, state.mtx.signer, // taker is mtx signer false, state.mtx.signer ), state.mtx.value ); } /// @dev Make an arbitrary internal, meta-transaction call. /// Warning: Do not let unadulterated `callData` into this function. function _callSelf(bytes32 hash, bytes memory callData, uint256 value) private returns (bytes memory returnResult) { bool success; (success, returnResult) = address(this).call{value: value}(callData); if (!success) { LibMetaTransactionsRichErrors.MetaTransactionCallFailedError( hash, callData, returnResult ).rrevert(); } } }
@dev Execute a `ITransformERC20Feature.transformERC20()` meta-transaction call by decoding the call args and translating the call to the internal `ITransformERC20Feature._transformERC20()` variant, where we can override the taker address. HACK(dorothy-zbornak): `abi.decode()` with the individual args will cause a stack overflow. But we can prefix the call data with an offset to transform it into the encoding for the equivalent single struct arg, since decoding a single struct arg consumes far less stack space than decoding multiple struct args. Where the encoding for multiple args (with the selector ommitted) would typically look like: | argument | offset | |--------------------------|---------| | inputToken | 0 | | outputToken | 32 | | inputTokenAmount | 64 | | minOutputTokenAmount | 96 | | transformations (offset) | 128 | = 32 | transformations (data) | 160 | We will ABI-decode a single struct arg copy with the layout: | argument | offset | |--------------------------|---------| | (arg 1 offset) | 0 | = 32 | inputToken | 32 | | outputToken | 64 | | inputTokenAmount | 96 | | minOutputTokenAmount | 128 | | transformations (offset) | 160 | = 32 | transformations (data) | 192 | Copy the args data from the original, after the new struct offset prefix. Prefix the calldata with a struct offset, which points to just one word over. Copy everything after the selector. Start copying after the struct offset.
function _executeTransformERC20Call(ExecuteState memory state) private returns (bytes memory returnResult) { ExternalTransformERC20Args memory args; { bytes memory encodedStructArgs = new bytes(state.mtx.callData.length - 4 + 32); bytes memory fromCallData = state.mtx.callData; assert(fromCallData.length >= 160); uint256 fromMem; uint256 toMem; assembly { mstore(add(encodedStructArgs, 32), 32) fromMem := add(fromCallData, 36) toMem := add(encodedStructArgs, 64) } LibBytesV06.memCopy(toMem, fromMem, fromCallData.length - 4); } state.hash, abi.encodeWithSelector( ITransformERC20Feature._transformERC20.selector, ITransformERC20Feature.TransformERC20Args({ inputToken: args.inputToken, outputToken: args.outputToken, inputTokenAmount: args.inputTokenAmount, minOutputTokenAmount: args.minOutputTokenAmount, transformations: args.transformations, useSelfBalance: false, recipient: state.mtx.signer }) ), state.mtx.value ); }
14,117,722
[ 1, 5289, 279, 1375, 45, 4059, 654, 39, 3462, 4595, 18, 6547, 654, 39, 3462, 20338, 2191, 17, 7958, 745, 1377, 635, 13547, 326, 745, 833, 471, 2162, 1776, 326, 745, 358, 326, 2713, 1377, 1375, 45, 4059, 654, 39, 3462, 4595, 6315, 6547, 654, 39, 3462, 20338, 5437, 16, 1625, 732, 848, 3849, 1377, 326, 268, 6388, 1758, 18, 670, 3649, 12, 72, 280, 10370, 93, 17, 94, 70, 14245, 581, 4672, 1375, 21457, 18, 3922, 20338, 598, 326, 7327, 833, 903, 4620, 279, 2110, 9391, 18, 12484, 732, 848, 1633, 326, 745, 501, 598, 392, 1384, 358, 2510, 518, 1368, 326, 2688, 364, 326, 7680, 2202, 1958, 1501, 16, 3241, 13547, 279, 2202, 1958, 1501, 25479, 10247, 5242, 2110, 3476, 2353, 13547, 3229, 1958, 833, 18, 12177, 326, 2688, 364, 3229, 833, 261, 1918, 326, 3451, 8068, 7948, 13, 4102, 14755, 2324, 3007, 30, 571, 1237, 1171, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 8837, 4059, 654, 39, 3462, 1477, 12, 5289, 1119, 3778, 919, 13, 203, 3639, 3238, 203, 3639, 1135, 261, 3890, 3778, 327, 1253, 13, 203, 565, 288, 203, 203, 203, 203, 3639, 11352, 4059, 654, 39, 3462, 2615, 3778, 833, 31, 203, 3639, 288, 203, 5411, 1731, 3778, 3749, 3823, 2615, 273, 394, 1731, 12, 2019, 18, 81, 978, 18, 1991, 751, 18, 2469, 300, 1059, 397, 3847, 1769, 203, 5411, 1731, 3778, 628, 1477, 751, 273, 919, 18, 81, 978, 18, 1991, 751, 31, 203, 5411, 1815, 12, 2080, 1477, 751, 18, 2469, 1545, 25430, 1769, 203, 5411, 2254, 5034, 628, 3545, 31, 203, 5411, 2254, 5034, 358, 3545, 31, 203, 5411, 19931, 288, 203, 7734, 312, 2233, 12, 1289, 12, 10787, 3823, 2615, 16, 3847, 3631, 3847, 13, 203, 7734, 628, 3545, 519, 527, 12, 2080, 1477, 751, 16, 6580, 13, 203, 7734, 358, 3545, 519, 527, 12, 10787, 3823, 2615, 16, 5178, 13, 203, 5411, 289, 203, 5411, 10560, 2160, 58, 7677, 18, 3917, 2951, 12, 869, 3545, 16, 628, 3545, 16, 628, 1477, 751, 18, 2469, 300, 1059, 1769, 203, 3639, 289, 203, 5411, 919, 18, 2816, 16, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 203, 7734, 467, 4059, 654, 39, 3462, 4595, 6315, 6547, 654, 39, 3462, 18, 9663, 16, 203, 7734, 467, 4059, 654, 39, 3462, 4595, 18, 4059, 654, 39, 3462, 2615, 12590, 203, 10792, 810, 1345, 30, 833, 18, 2630, 1345, 16, 203, 10792, 876, 1345, 30, 833, 18, 2844, 1345, 16, 2 ]
pragma solidity ^0.5.0; contract CV { // Model a Candidate struct certificate { uint id; string hash; } // Read/write candidates mapping(uint => certificate) public ct; // Store Candidates Count uint public ctCount=0; function addCT (string memory _hash) public { ctCount ++; ct[ctCount] = certificate(ctCount, _hash); //return ctCount; } function checker(string memory inputHash, uint cid) public view returns(bool) { // return (StringUtils.equal(inputHash,storedHash)); bytes memory _inputHash = bytes(inputHash); string memory h = ct[cid].hash; bytes memory _storedHash = bytes(h); if (_inputHash.length != _storedHash.length){ return false; } else{ return keccak256(_inputHash) == keccak256(_storedHash); } } }
Store Candidates Count
uint public ctCount=0;
12,610,888
[ 1, 2257, 385, 12794, 6974, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 2254, 1071, 5691, 1380, 33, 20, 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 ]
// File: contracts\utils\EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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: 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. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts\GSN\Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ 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: contracts\access\AccessControl.sol /** * @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: contracts\math\SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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: contracts\utils\Counters.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); } } // File: contracts\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); } // File: contracts\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; } // File: contracts\token\ERC721\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); } // File: contracts\token\ERC721\IERC721Enumerable.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); } // File: contracts\token\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\introspection\ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ 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 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\utils\EnumerableMap.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.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 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) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ 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(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(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(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // File: contracts\utils\Strings.sol /** * @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--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: contracts\token\ERC721\ERC721.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; mapping (address => bool) public whitelists; // 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 (address => bool) public whitelists; // 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 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 override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).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(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString(), ".json")); } /** * @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 returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view 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 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 = 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 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 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, 0); // _transfer(from, to, 1); // _transfer(from, to, 2); _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, 0, _data); //_safeTransfer(from, to, 1, _data); //_safeTransfer(from, to, 2, _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 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 returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * 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 = ownerOf(tokenId); _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(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); _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(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` 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: contracts\token\ERC721\ERC721Burnable.sol /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // File: contracts\utils\Pausable.sol /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts\token\ERC721\ERC721Pausable.sol /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // File: contracts\presets\NonFungibleToken.sol /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract NonFungibleToken is Context, AccessControl, ERC721, ERC721Pausable { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); address public owner; bool public whitelistingEnabled = true; bool public mintingEnabled = true; uint256 public maxPerWallet = 300; // Owner minting params uint256 public mintingRound = 0; uint256 public maxCalls = 4; uint256 public nftPerCall = 50; // mapping (address => bool) public whitelists; Counters.Counter private _tokenIdTracker; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ constructor(string memory name, string memory symbol, string memory baseURI) public ERC721(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setBaseURI(baseURI); owner = msg.sender; } function mintOwner() public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have minter role to mint"); require(mintingRound < maxCalls, "All owner NFTs have been minted"); for(uint i = 0; i < nftPerCall; i++){ _mint(msg.sender, _tokenIdTracker.current() +1); _tokenIdTracker.increment(); } mintingRound = mintingRound + 1; } function setURI(string memory baseURI) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); _setBaseURI(baseURI); } function setMaxPerWallet(uint256 _maxPerWallet) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have minter role to mint"); maxPerWallet = _maxPerWallet; } function setOwner(address _owner) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role to mint"); owner = _owner; } function toggleMinting(bool _bool) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role to mint"); mintingEnabled = _bool; } function toggleWhitelisting(bool _toggle) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); whitelistingEnabled = _toggle; } function Whitelist(address[] memory _beneficiaries) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelists[_beneficiaries[i]] = true; } } function contractURI() public view returns (string memory) { return string(abi.encodePacked(baseURI(), "contract-metadata.json")); } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "NonFungibleToken: must have minter role to mint"); require(whitelists[to] || ! whitelistingEnabled, "User not whitelisted !"); require(mintingEnabled, "Minting not enabled !"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIdTracker.current()+1); _tokenIdTracker.increment(); require(balanceOf(to) <= maxPerWallet, "Max NFTs reached by wallet"); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } }
* @dev See {IERC721-safeTransferFrom}./_safeTransfer(from, to, 0, _data);_safeTransfer(from, to, 1, _data);_safeTransfer(from, to, 2, _data);
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"); }
391,327
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 4626, 5912, 1265, 5496, 18510, 4626, 5912, 12, 2080, 16, 358, 16, 374, 16, 389, 892, 1769, 67, 4626, 5912, 12, 2080, 16, 358, 16, 404, 16, 389, 892, 1769, 67, 4626, 5912, 12, 2080, 16, 358, 16, 576, 16, 389, 892, 1769, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 5912, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 16, 1731, 3778, 389, 892, 13, 1071, 5024, 3849, 288, 203, 3639, 2583, 24899, 291, 31639, 1162, 5541, 24899, 3576, 12021, 9334, 1147, 548, 3631, 315, 654, 39, 27, 5340, 30, 7412, 4894, 353, 486, 3410, 12517, 20412, 8863, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "./interfaces/IOutboundChannel.sol"; // BasicOutboundChannel is a basic channel that just sends messages with a nonce. contract BasicOutboundChannel is IOutboundChannel { uint64 public nonce; event Message( address source, uint64 nonce, bytes payload ); /** * @dev Sends a message across the channel */ function submit(address, bytes calldata payload) external override { nonce = nonce + 1; emit Message(msg.sender, nonce, payload); } }
BasicOutboundChannel is a basic channel that just sends messages with a nonce.
contract BasicOutboundChannel is IOutboundChannel { uint64 public nonce; event Message( address source, uint64 nonce, bytes payload ); pragma solidity >=0.6.0 <0.7.0; function submit(address, bytes calldata payload) external override { nonce = nonce + 1; emit Message(msg.sender, nonce, payload); } }
13,000,819
[ 1, 8252, 17873, 2909, 353, 279, 5337, 1904, 716, 2537, 9573, 2743, 598, 279, 7448, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7651, 17873, 2909, 353, 467, 17873, 2909, 288, 203, 203, 565, 2254, 1105, 1071, 7448, 31, 203, 203, 565, 871, 2350, 12, 203, 3639, 1758, 1084, 16, 203, 3639, 2254, 1105, 7448, 16, 203, 3639, 1731, 2385, 203, 565, 11272, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 26, 18, 20, 411, 20, 18, 27, 18, 20, 31, 203, 565, 445, 4879, 12, 2867, 16, 1731, 745, 892, 2385, 13, 3903, 3849, 288, 203, 3639, 7448, 273, 7448, 397, 404, 31, 203, 3639, 3626, 2350, 12, 3576, 18, 15330, 16, 7448, 16, 2385, 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 ]
/* NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNDOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN8OOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN8OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOODNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO8NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO8NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOODNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNMOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNMOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNDOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOODNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO7=~~~~~~+$OOOOOOOOOOOOOOOOOOOOOOO8NNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO?~~~~~~~~~~~~~~~~~~~~~~+OOOOOOOOOOOOOOOOOOO8NNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOO==~~~~~~~~~~~~~~~~~~~~~~~~~~~~=$OOOOOOOOOOOOOOOOMNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOI~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~8OOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~OOOOOOOOOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOI=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~OOOOOOOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOZ=~~~~~~~~~~~~~~~+NMMMMMO?~~~~~~~~~~~~~~~~~~~~~~~~~~~ZOOOOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=~NN==~~~~~~~~~~~~~~~~~~~~$ZOOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOO7~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~OOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNDOOOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~OODNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNMMMMMMM8OOOOOOOO=~~~~~~~~~~~~~~~~~~~~~~ONMMMMMMMMMMMMM?==~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMDZ~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMM==~~~~~~~~~~M=~==DMMMMMNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNOOOODMMMMMMMMMMMMMMMMMI~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM~~~~~~~7MMMMMMMMMMMNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNOOOOOOOOOOONMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN~~~~NNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNDOOOOOOOOOOOOOO===~IMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM8~=~~~~~~~~~NNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNOOOOOOOOOOOOOOO~~~~~~~~~~==~~=$MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM?~~~~~~~~~~~~~~~~~~=~NNNNNNNNNNNNNN NNNNNNNNNNNNNNNOOOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM~~~~~~~~~~~~~~~~~~~~~~~?NNNNNNNNNNNN NNNNNNNNNNNNNNNOOOOOOOOOOOOOO$=~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM8~~~~~~~~~~~~~~~~~~~~~~~~+NNNNNNNNNNN NNNNNNNNNNNNNNNOOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNN NNNNNNNNNNNNNNNOOOOOOOOOOOOOI~~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNN NNNNNNNNNNNNNNNOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM=~~~:...........=8MM+=~~~~~~NNNNNNNNNN NNNNNNNNNNNNNNNNOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~=MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM~~~~.....MM?............DN~~MNNNNNNNNN NNNNNNNNNNNNNNNNOOOOOOOOOOO+~~~~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM=~~~~........................MNNNNNNNNN NNNNNNNNNNNNNNNNNOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~?MMMMMMMMMMMMMMMMMMMMMMMMMMMMD~~~~~........................NNNNNNNNNN NNNNNNNNNNNNNNNNNDOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~DMMMMMMMMMMMMMMMMMMMMMMMMMMZ~~~~~~........................NNNNNNNNNN NNNNNNNNNNNNNNNNNNOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~=IMMMMMMMMMMMMMMMMMMMMMMMMO~~~~~~~.......................~NNNNNNNNNN NNNNNNNNNNNNNNNNNNOOOOOOOO7~~~~~~~~~~~~~~~~~~~~~~~~~~~=MMMMMMMMMMMMMMMMMMMMMM~~~~~~~~~=......................NNNNNNNNNNN NNNNNNNNNNNNNNNNNNOOOOOO$~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ZMMMMMMMMMMMMMMMMMM~~~~~~~~~~~~,....................NNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NMMMMMMMMMMMMMM=~~~~~~~~~~~~~~,..................NNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNOOO+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~8MMMMMMMI~~~~~~~~~~~~~~~~M~~~,..............MNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNMOO=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~N~~~~~~........~~~NNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNN8~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~M~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$~~~~~~~M~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MI~~~N~~~~~~~~~~~~~~~~MNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNZ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNDO~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNZ=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=~~~~~~~~~~~~~~~~~~=~NNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=+DM8~~~~~~~$MN~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNM~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNZ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNM~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNZ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~8NNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=MNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN7~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~DNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNM~~~~~~=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNND~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN$~~~~~~~~~~~~~~~~==~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN:~~~~~~~~~~~~~~~~~~~~~~~~~=~~~~~~~~~~~~~=~~~~~NNNNNNNNNNNNNNNNNNNNWE&ARE&LEGIONNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNWE&DO&NOT&FORGIVENNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN8~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNWE&DO&NOT&FORGETNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNM~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNEXPECT&USNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~?NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNM~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNN=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN */ /** * @title Microverse * Given the fact that most of the blockchaaaaains are dogshit wrapped in catshit, we've decided to come down from the * highland, just for a while, though. * Being smart is lonely, being nice is a compromise. * Hello human, we are Evil Morty Fund. * Decentralization is great, while balance must be kept. * Order will change, but never disappear. * We are not building another chain, we are forming a soceity, never seen, never have been. */ // \ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) / // \ (•◡•) / █ █ █░░█ █▀▀▄ █▀▀█ █░░ █░░█ █▀▀▄ █▀▀█ █▀▀▄ █░░█ █▀▀▄ █▀▀▄ █░░█ █▀▀▄ \ (•◡•) / // \ (•◡•) / █ █ █ █░░█ █▀▀▄ █▄▄█ █░░ █░░█ █▀▀▄ █▄▄█ █░░█ █░░█ █▀▀▄ █░░█ █░░█ █▀▀▄ \ (•◡•) / // \ (•◡•) / █▄▀▄█ ░▀▀▀ ▀▀▀░ ▀░░▀ ▀▀▀ ░▀▀▀ ▀▀▀░ ▀░░▀ ▀▀▀░ ░▀▀▀ ▀▀▀░ ▀▀▀░ ░▀▀▀ ▀▀▀░ \ (•◡•) / // \ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) / /** * Created on 2018-08-21 03:28 * @summary: * @author: yong */ pragma solidity ^0.4.23; /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * @dev Supports unlimited numbers of roles and addresses. * @dev See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } } /** * @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; } } /** * @title Superuser * @dev The Superuser contract defines a single superuser who can transfer the ownership * @dev of a contract to a new address, even if he is not the owner. * @dev A superuser can transfer his role to a new address. */ contract Superuser is Ownable, RBAC { string public constant ROLE_SUPERUSER = "superuser"; constructor () public { addRole(msg.sender, ROLE_SUPERUSER); } /** * @dev Throws if called by any account that's not a superuser. */ modifier onlySuperuser() { checkRole(msg.sender, ROLE_SUPERUSER); _; } modifier onlyOwnerOrSuperuser() { require(msg.sender == owner || isSuperuser(msg.sender)); _; } /** * @dev getter to determine if address has superuser role */ function isSuperuser(address _addr) public view returns (bool) { return hasRole(_addr, ROLE_SUPERUSER); } /** * @dev Allows the current superuser to transfer his role to a newSuperuser. * @param _newSuperuser The address to transfer ownership to. */ function transferSuperuser(address _newSuperuser) public onlyOwner { require(_newSuperuser != address(0)); removeRole(msg.sender, ROLE_SUPERUSER); addRole(_newSuperuser, ROLE_SUPERUSER); } } /** * @title MicroverseBase * @dev You are still with us? im almost surprised. * @dev Basic params are defined in this base. */ contract MicroverseBase is Superuser { using SafeMath for uint256; event OpenWormhole(); event CloseWormhole(); event SystemChangePercentWeiDividend(uint256 oldValue, uint256 newValue); event SystemChangePercentWeiJackpot(uint256 oldValue, uint256 newValue); event SystemChangePercentWeiMC(uint256 oldValue, uint256 newValue); uint256 public previousWeiBalance; uint256 public nextSeedHashed; uint256 public percentWeiDividend = 40; // 40% uint256 public percentWeiJackpot = 10; // 10% uint256 public percentWeiMC = 10; // 10% uint256 public FACTOR = 100; // We think it makes perfectly sense that only the owner can open or close the wormhole. bool public wormholeIsOpen = true; modifier wormholeOpened() { require (wormholeIsOpen == true); _; } /** * @dev start game */ function openWormhole() external onlyOwner { wormholeIsOpen = true; emit OpenWormhole(); } /** * @dev stop game */ function closeWormhole() external onlyOwner { wormholeIsOpen = false; emit CloseWormhole(); } /** * @dev reveal the hashed seed to general public * @dev the seed will be hashed twice using keccak256 * @param seedHash The result of keccak256(keccak256(seed)) */ function setNextSeedHash(uint256 seedHash) external onlyOwner { nextSeedHashed = seedHash; } /** * @dev Update dividend percentage, a system event * is sent to capture this change. * @param _value new value */ function setPercentWeiDividend(uint256 _value) external onlyOwner { emit SystemChangePercentWeiDividend(percentWeiDividend, _value); percentWeiDividend = _value; } /** * @dev Update jackpot percentage, a system event * is sent to capture this change. * @param _value new value */ function setPercentWeiJackpot(uint256 _value) external onlyOwner { emit SystemChangePercentWeiJackpot(percentWeiJackpot, _value); percentWeiJackpot = _value; } /** * @dev Update mutual constructor percentage, a system event * is sent to capture this change. * @param _value new value */ function setPercentWeiMC(uint256 _value) external onlyOwner { emit SystemChangePercentWeiMC(percentWeiMC, _value); percentWeiMC = _value; } } /** * Microverse is made up of four components, together managing three ERC223 tokens. * Let us explain. * * ░█▀▀█ █▀▀█ █▀▀█ █▀▀█ █▀▀▀ █▀▀ * ░█─▄▄ █▄▄█ █▄▄▀ █▄▄█ █─▀█ █▀▀ * ░█▄▄█ ▀──▀ ▀─▀▀ ▀──▀ ▀▀▀▀ ▀▀▀ * * Garage manages Evil Morty token (Morty) * It tracks and updates the price, manage the total balance, and timestamp in this universe. * * ░█▀▀█ █▀▀█ █▀▀█ ▀▀█▀▀ █▀▀█ █──   ░█▀▀█ █──█ █▀▀▄ * ░█▄▄█ █──█ █▄▄▀ ──█── █▄▄█ █──   ░█─▄▄ █──█ █──█ * ░█─── ▀▀▀▀ ▀─▀▀ ──▀── ▀──▀ ▀▀▀   ░█▄▄█ ─▀▀▀ ▀──▀ * * Portal Gun manages Evil Morty token (Morty), Rick C137 token (Rick), and Flurbo token (FLB) * It takes care of the random process happened in this universe, in which the sender gets * 20% chance to get Rick, 30% chance to get double Morty, and 50% chance to get FLB, if, * he/she sends EM to the address of this contract. * * ▒█▀▀▀█ █▀▀█ █▀▀█ █▀▀ █▀▀   ▒█▀▀█ █▀▀█ █░░█ ░▀░ █▀▀ █▀▀ * ░▀▀▀▄▄ █░░█ █▄▄█ █░░ █▀▀   ▒█░░░ █▄▄▀ █░░█ ▀█▀ ▀▀█ █▀▀ * ▒█▄▄▄█ █▀▀▀ ▀░░▀ ▀▀▀ ▀▀▀   ▒█▄▄█ ▀░▀▀ ░▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀ * * Spaceship manages Rick C137 tokens (Rick) * It is responsible for sending the dividends. * * ▒█▀▀█ ░▀░ █▀▀█ █▀▀▄ █▀▄▀█ █▀▀█ █▀▀▄ * ▒█▀▀▄ ▀█▀ █▄▄▀ █░░█ █░▀░█ █▄▄█ █░░█ * ▒█▄▄█ ▀▀▀ ▀░▀▀ ▀▀▀░ ▀░░░▀ ▀░░▀ ▀░░▀ * * Birdman helps grow the Microverse community. * This contract sends the fund to birdmen. * */ /** * @title GarageInterface * @dev Housekeeper for Evil Morty token. */ contract GarageInterface { /** * @dev getter for token address */ function getEvilMortyAddress() external view returns (address); /** * @dev proxy/agent to purchase morties on behalf of senders * @param weiAmount The ether amount * @param beneficiary The buyer's address */ function citadelBuy(uint256 weiAmount, address beneficiary) external returns (uint256); } /** * @title PortalGunInterface * @dev Random oracle in this world. */ contract PortalGunInterFace { uint256 public numTickets; /** * @dev Give us morty, let there be rick * @param player The player's address * @param amount Amount morty sent */ function participate(address player, uint256 amount) external; /** * @dev getter to check EM balance * @param sender The sender's address */ function balanceOfMorty(address sender) external view returns (uint256); /** * @dev getter to check C137 balance * @param sender The sender's address */ function balanceOfRick(address sender) external view returns (uint256); /** * @dev getter to check FLB balance * @param sender The sender's address */ function balanceOfFlurbo(address sender) external view returns (uint256); /** * @dev Give back EM, C137, or FLB * @param seed A UUID in expressed in integer */ function redeem(uint256 seed) external; /** * @dev Wake Rick up */ function startRick() external returns (bool); /** * @dev Clean all ricks * @dev Remember, for a given period of time, Rick C137 holders are eligible for receiving ETH dividends. * @dev When the period ends, all ricks will be gone, C137 balance will be reset to zero. * @dev Our strategy is, get ricks as early as possible! */ function resetRick() external; /** * @dev Make portal gun back on fire */ function startPortalGun() external; /** * @dev Cease fire and make Rick drunk */ function stopPortalGunAndRick() external; /** * @dev getter of number of C137 holders */ function getNumOfRickHolders() external view returns (uint256); } /** * @title SpaceshipInterface */ contract SpaceshipInterface { /** * @dev What more can i say @jeff? It starts the spaceship */ function startSpaceship() external returns (bool); /** * @dev Send the eth funds to all C137 holders */ function sendDividends() external; /** * @dev getter of number of dividend rounds */ function getNumDividends() external view returns (uint256); /** * @dev updates the status, that's it */ function updateSpaceshipStatus() external; } /** * ╔═╗╔═╦══╦═══╦═══╦═══╦╗░░╔╦═══╦═══╦═══╦═══╗ * ║║╚╝║╠╣╠╣╔═╗║╔═╗║╔═╗║╚╗╔╝║╔══╣╔═╗║╔═╗║╔══╝ * ║╔╗╔╗║║║║║░╚╣╚═╝║║░║╠╗║║╔╣╚══╣╚═╝║╚══╣╚══╗ * ║║║║║║║║║║░╔╣╔╗╔╣║░║║║╚╝║║╔══╣╔╗╔╩══╗║╔══╝ * ║║║║║╠╣╠╣╚═╝║║║╚╣╚═╝║╚╗╔╝║╚══╣║║╚╣╚═╝║╚══╗ * ╚╝╚╝╚╩══╩═══╩╝╚═╩═══╝░╚╝░╚═══╩╝╚═╩═══╩═══╝ * * It's been a great pleasure coding in solidity! * * @title Microverse * @dev secret: 981ea44275dc95cb74b8f768f82d6debfd2f934adc0125de71762051 * * ██████┼────────────────────────────────────────────────────────────┼██████ * ██████│░░░Ryan░░░░░░░░░░░░░░░░░░░░░░░░░Dan░░░░░░░░░░░░░░░░Justin░░░│██████ * ██████│░Einstein░░░░░░░░░░░░░Satoshi░░░░░░░░░░░░░░░░░Stephen░░░░░░░│██████ * ██████│░░░░░░░░░Shannon░░░░░░░░░░░░░░░░░RSA░░░░░░░░░░░░░░░░░░░░░░░░│██████ * ██████│░░░░░░░░░░░Vitalik░░░░░░░░░░░░░░░░░░░░░All Team Members░░░░░│██████ * ██████│░░░░░░Steve░░░░░░░░░░Mandela░░░░░░░░░░Lennon░░░░░░░░░░░░░░░░│██████ * ██████│░░░░░░░░░░░░░░░░Gabriel░░░░░░░░░Haruki░░░░░░░░░░░░░THANKS░TO│██████ * ██████┼────────────────────────────────────────────────────────────┼██████ * ██████████████████████████████████████████████████████████████████████████ * █████████████████████████ https://microverse.club ████████████████████████ * ██████████████████████████████████████████████████████████████████████████ * ██████████████████████████████████████████████████████████████████████████ */ contract Microverse is MicroverseBase { event Refund(address indexed receiver, uint256 value); event Withdraw(address indexed receiver, uint256 value); GarageInterface internal garageInstance; PortalGunInterFace internal portalGunInstance; SpaceshipInterface internal spaceshipInstance; address internal EvilMortyAddress; address internal MCAddress; modifier isEvilMortyToken() { require(msg.sender == EvilMortyAddress); _; } constructor( address garageAddress, address portalGunAddress, address spaceshipAddress, address MutualConstructorAddress) public { garageInstance = GarageInterface(garageAddress); portalGunInstance = PortalGunInterFace(portalGunAddress); spaceshipInstance = SpaceshipInterface(spaceshipAddress); EvilMortyAddress = garageInstance.getEvilMortyAddress(); MCAddress = MutualConstructorAddress; } /** * @dev Enable sending eth directly */ function () public payable { if (msg.sender == owner) { return; } buyMorty(); } /** * @dev Respond to Evil Morty token transfer * @param _from address * @param _value address * @param _data extra data */ function tokenFallback(address _from, uint _value, bytes _data) public wormholeOpened isEvilMortyToken { if (_from == owner) { return; } portalGunInstance.participate(_from, _value); } /** * @dev Check morty balance of a given address * @param sender address */ function balanceOfMorty(address sender) external view returns (uint256) { return portalGunInstance.balanceOfMorty(sender); } /** * @dev Check rick balance of a given address * @param sender address */ function balanceOfRick(address sender) external view returns (uint256) { return portalGunInstance.balanceOfRick(sender); } /** * @dev Check flurbo of a given address * @param sender address */ function balanceOfFlurbo(address sender) external view returns (uint256) { return portalGunInstance.balanceOfFlurbo(sender); } /** * @dev Agent for buying morties * if the user sends more eth fund than needed, the exceedings will be sent back * i.e., if there are only 1000 morties left, each morty costs 0.001 eth, and the * user sends 3 eth, then, after the purchase (1000 * 0.001 = 1 eth), the remaining * 2 eth will be refunded. */ function buyMorty() public wormholeOpened payable { uint256 weiReturn = garageInstance.citadelBuy(msg.value, msg.sender); if (weiReturn > 0) { msg.sender.transfer(weiReturn); emit Refund(msg.sender, weiReturn); } _addWeiAmount(address(this).balance.sub(previousWeiBalance)); } /** * @dev Transfer jackpot to the winner * @param winner address */ function transferJackpot(address winner) external onlyOwner returns (bool) { uint256 weiJackpot = address(this).balance; emit Withdraw(winner, weiJackpot); winner.transfer(weiJackpot); previousWeiBalance = 0; } /** * @dev Consume tickets to generate morty, rick, or flurbo * @param seed A uuid4 in int format */ function redeemLottery(uint256 seed) external onlyOwnerOrSuperuser { return portalGunInstance.redeem(seed); } /** * @dev Get number of tickets onhold */ function getNumOfLotteryTickets() external view returns (uint256) { return portalGunInstance.numTickets(); } /** * @dev Internal function to update funds for jackpot and dividends * @param weiAmount eth amount in wei */ function _addWeiAmount(uint256 weiAmount) internal returns (bool) { uint256 weiDividendPart = weiAmount.mul(percentWeiDividend).div(FACTOR); // 40% uint256 weiJackpotPart = weiAmount.mul(percentWeiJackpot).div(FACTOR); // 10% uint256 weiMCPart = weiAmount.mul(percentWeiMC).div(FACTOR); // 10% uint256 weiEMFPart = weiAmount.sub(weiDividendPart).sub(weiJackpotPart).sub(weiMCPart); address(spaceshipInstance).transfer(weiDividendPart); MCAddress.transfer(weiMCPart); address(owner).transfer(weiEMFPart); previousWeiBalance = address(this).balance; return true; } /** * @dev Before sending dividends, there are some preparations to be made. * Spaceship needs to know the number of current Rick holders and * the number of total Ricks. Any events causing changes in balance of Ricks * need to be stopped, which means, the Portal Gun service is paused and, * transferring of Ricks are paused. */ function prepareDividends() external onlyOwnerOrSuperuser { spaceshipInstance.updateSpaceshipStatus(); portalGunInstance.stopPortalGunAndRick(); } /** * @dev Send eth to all Rick holders */ function transferDividends() external onlyOwnerOrSuperuser { return spaceshipInstance.sendDividends(); } /** * @dev Get number of Rick holders in Spaceship */ function getNumDividends() external view returns (uint256) { return spaceshipInstance.getNumDividends(); } /** * @dev Once the distribution of dividends is finished * the system will be started */ function finishDividends() external onlyOwnerOrSuperuser { spaceshipInstance.startSpaceship(); portalGunInstance.startPortalGun(); portalGunInstance.startRick(); } /** * @dev Reset all Rick holders */ function resetDividends() external onlyOwnerOrSuperuser { return portalGunInstance.resetRick(); } /** * @dev Get number of Rick holders in Portal Gun */ function getNumOfRickHolders() external view returns (uint256) { return portalGunInstance.getNumOfRickHolders(); } /** * @dev Upgrade Microverse's components * in case of upgrade needed */ function upgradeComponent( uint256 _componentIndex, address _address) external onlyOwner { uint256 codeLength; assembly { codeLength := extcodesize(_address) } if (codeLength == 0) { return; } if (_componentIndex == 1) { garageInstance = GarageInterface(_address); return; } if (_componentIndex == 2) { portalGunInstance = PortalGunInterFace(_address); return; } if (_componentIndex == 3) { spaceshipInstance = SpaceshipInterface(_address); return; } } /** * @dev refresh evil morty's address */ function upgradeEvilMorty() external onlyOwner { EvilMortyAddress = garageInstance.getEvilMortyAddress(); } } /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } /** * @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; } }
* @dev Update jackpot percentage, a system event is sent to capture this change. @param _value new value/
function setPercentWeiJackpot(uint256 _value) external onlyOwner { emit SystemChangePercentWeiJackpot(percentWeiJackpot, _value); percentWeiJackpot = _value; }
14,022,840
[ 1, 1891, 525, 484, 13130, 11622, 16, 279, 2619, 871, 353, 3271, 358, 7477, 333, 2549, 18, 225, 389, 1132, 394, 460, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 8410, 3218, 77, 46, 484, 13130, 12, 11890, 5034, 389, 1132, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 288, 203, 3639, 3626, 2332, 3043, 8410, 3218, 77, 46, 484, 13130, 12, 8849, 3218, 77, 46, 484, 13130, 16, 389, 1132, 1769, 203, 3639, 5551, 3218, 77, 46, 484, 13130, 273, 389, 1132, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.8.4 <0.9.0; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/proxy/Clones.sol'; import '../interfaces/INFT.sol'; import '../libraries/RegistryUser.sol'; import '../libraries/Bytes.sol'; /** * NFT Press * Name: Press * Domain: Infrastructure */ contract Press is RegistryUser { // Allow to clone NFT using Clones for address; // Create new NFT event CreateNewNFT(bytes32 indexed domain, address indexed nftContract, string indexed name); // Pass constructor parameter to User constructor(address registry_, bytes32 domain_) { _registryUserInit(registry_, domain_); } /******************************************************* * Operator section ********************************************************/ // Clone new NFT function createNewNFT( bytes32 domain_, string memory name_, string memory symbol_, string memory uri_ ) external onlyAllowSameDomain('Operator') returns (address) { address newNft = _registry.getAddress(_domain, 'NFT').clone(); INFT(newNft).init(address(_registry), domain_, name_, symbol_, uri_); emit CreateNewNFT(domain_, newNft, name_); return newNft; } }
* NFT Press Name: Press Domain: Infrastructure/ Allow to clone NFT Create new NFT Pass constructor parameter to User
contract Press is RegistryUser { using Clones for address; event CreateNewNFT(bytes32 indexed domain, address indexed nftContract, string indexed name); pragma solidity >=0.8.4 <0.9.0; constructor(address registry_, bytes32 domain_) { _registryUserInit(registry_, domain_); } function createNewNFT( bytes32 domain_, string memory name_, string memory symbol_, string memory uri_ ) external onlyAllowSameDomain('Operator') returns (address) { address newNft = _registry.getAddress(_domain, 'NFT').clone(); INFT(newNft).init(address(_registry), domain_, name_, symbol_, uri_); emit CreateNewNFT(domain_, newNft, name_); return newNft; } }
1,036,151
[ 1, 50, 4464, 29806, 1770, 30, 29806, 6648, 30, 657, 26150, 19, 7852, 358, 3236, 423, 4464, 1788, 394, 423, 4464, 10311, 3885, 1569, 358, 2177, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 29806, 353, 5438, 1299, 288, 203, 225, 1450, 3905, 5322, 364, 1758, 31, 203, 203, 225, 871, 1788, 1908, 50, 4464, 12, 3890, 1578, 8808, 2461, 16, 1758, 8808, 290, 1222, 8924, 16, 533, 8808, 508, 1769, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 24, 411, 20, 18, 29, 18, 20, 31, 203, 225, 3885, 12, 2867, 4023, 67, 16, 1731, 1578, 2461, 67, 13, 288, 203, 565, 389, 9893, 1299, 2570, 12, 9893, 67, 16, 2461, 67, 1769, 203, 225, 289, 203, 203, 203, 225, 445, 15291, 50, 4464, 12, 203, 565, 1731, 1578, 2461, 67, 16, 203, 565, 533, 3778, 508, 67, 16, 203, 565, 533, 3778, 3273, 67, 16, 203, 565, 533, 3778, 2003, 67, 203, 225, 262, 3903, 1338, 7009, 8650, 3748, 2668, 5592, 6134, 1135, 261, 2867, 13, 288, 203, 565, 1758, 394, 50, 1222, 273, 389, 9893, 18, 588, 1887, 24899, 4308, 16, 296, 50, 4464, 16063, 14056, 5621, 203, 565, 2120, 4464, 12, 2704, 50, 1222, 2934, 2738, 12, 2867, 24899, 9893, 3631, 2461, 67, 16, 508, 67, 16, 3273, 67, 16, 2003, 67, 1769, 203, 565, 3626, 1788, 1908, 50, 4464, 12, 4308, 67, 16, 394, 50, 1222, 16, 508, 67, 1769, 203, 565, 327, 394, 50, 1222, 31, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; import "../math/SafeMathUint128.sol"; import "../interfaces/IHEZToken.sol"; import "../interfaces/IHermezAuctionProtocol.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; /** * @dev Hermez will run an auction to incentivise efficiency in coordinators, * meaning that they need to be very effective and include as many transactions * as they can in the slots in order to compensate for their bidding costs, gas * costs and operations costs.The general porpouse of this smartcontract is to * define the rules to coordinate this auction where the bids will be placed * only in HEZ utility token. */ contract HermezAuctionProtocol is Initializable, ReentrancyGuardUpgradeable, IHermezAuctionProtocol { using SafeMath128 for uint128; struct Coordinator { address forger; // Address allowed by the bidder to forge a batch string coordinatorURL; } // The closedMinBid is the minimum bidding with which it has been closed a slot and may be // higher than the bidAmount. This means that the funds must be returned to whoever has bid struct SlotState { address bidder; bool fulfilled; bool forgerCommitment; uint128 bidAmount; // Since the total supply of HEZ will be less than 100M, with 128 bits it is enough to uint128 closedMinBid; // store the bidAmount and closed minBid. bidAmount is the bidding for an specific slot. } // bytes4 private constant _PERMIT_SIGNATURE = // bytes4(keccak256(bytes("permit(address,address,uint256,uint256,uint8,bytes32,bytes32)"))); bytes4 private constant _PERMIT_SIGNATURE = 0xd505accf; // Blocks per slot uint8 public constant BLOCKS_PER_SLOT = 40; // Minimum bid when no one has bid yet uint128 public constant INITIAL_MINIMAL_BIDDING = 1000000 * (1e18); // Hermez Network Token with which the bids will be made IHEZToken public tokenHEZ; // HermezRollup smartcontract address address public hermezRollup; // Hermez Governance smartcontract address who controls some parameters and collects HEZ fee address public governanceAddress; // Boot Donation Address address private _donationAddress; // Boot Coordinator Address address private _bootCoordinator; // boot coordinator URL string public bootCoordinatorURL; // The minimum bid value in a series of 6 slots uint128[6] private _defaultSlotSetBid; // First block where the first slot begins uint128 public genesisBlock; // Number of closed slots after the current slot ( 2 Slots = 2 * 40 Blocks = 20 min ) uint16 private _closedAuctionSlots; // Total number of open slots which you can bid ( 30 days = 4320 slots ) uint16 private _openAuctionSlots; // How the HEZ tokens deposited by the slot winner are distributed ( Burn: 40.00% - Donation: 40.00% - HGT: 20.00% ) uint16[3] private _allocationRatio; // Two decimal precision // Minimum outbid (percentage, two decimal precision) over the previous one to consider it valid uint16 private _outbidding; // Two decimal precision // Number of blocks after the beginning of a slot after which any coordinator can forge if the winner has not forged // any batch in that slot uint8 private _slotDeadline; // Mapping to control slot state mapping(uint128 => SlotState) public slots; // Mapping to control balances pending to claim mapping(address => uint128) public pendingBalances; // Mapping to register all the coordinators. The address used for the mapping is the bidder address mapping(address => Coordinator) public coordinators; event NewBid( uint128 indexed slot, uint128 bidAmount, address indexed bidder ); event NewSlotDeadline(uint8 newSlotDeadline); event NewClosedAuctionSlots(uint16 newClosedAuctionSlots); event NewOutbidding(uint16 newOutbidding); event NewDonationAddress(address indexed newDonationAddress); event NewBootCoordinator( address indexed newBootCoordinator, string newBootCoordinatorURL ); event NewOpenAuctionSlots(uint16 newOpenAuctionSlots); event NewAllocationRatio(uint16[3] newAllocationRatio); event SetCoordinator( address indexed bidder, address indexed forger, string coordinatorURL ); event NewForgeAllocated( address indexed bidder, address indexed forger, uint128 indexed slotToForge, uint128 burnAmount, uint128 donationAmount, uint128 governanceAmount ); event NewDefaultSlotSetBid(uint128 slotSet, uint128 newInitialMinBid); event NewForge(address indexed forger, uint128 indexed slotToForge); event HEZClaimed(address indexed owner, uint128 amount); // Event emitted when the contract is initialized event InitializeHermezAuctionProtocolEvent( address donationAddress, address bootCoordinatorAddress, string bootCoordinatorURL, uint16 outbidding, uint8 slotDeadline, uint16 closedAuctionSlots, uint16 openAuctionSlots, uint16[3] allocationRatio ); modifier onlyGovernance() { require( governanceAddress == msg.sender, "HermezAuctionProtocol::onlyGovernance: ONLY_GOVERNANCE" ); _; } /** * @dev Initializer function (equivalent to the constructor). Since we use * upgradeable smartcontracts the state vars have to be initialized here. * @param token Hermez Network token with which the bids will be made * @param hermezRollupAddress address authorized to forge * @param donationAddress address that can claim donated tokens * @param _governanceAddress Hermez Governance smartcontract * @param bootCoordinatorAddress Boot Coordinator Address */ function hermezAuctionProtocolInitializer( address token, uint128 genesis, address hermezRollupAddress, address _governanceAddress, address donationAddress, address bootCoordinatorAddress, string memory _bootCoordinatorURL ) public initializer { __ReentrancyGuard_init_unchained(); require( hermezRollupAddress != address(0), "HermezAuctionProtocol::hermezAuctionProtocolInitializer ADDRESS_0_NOT_VALID" ); _outbidding = 1000; _slotDeadline = 20; _closedAuctionSlots = 2; _openAuctionSlots = 4320; _allocationRatio = [4000, 4000, 2000]; _defaultSlotSetBid = [ INITIAL_MINIMAL_BIDDING, INITIAL_MINIMAL_BIDDING, INITIAL_MINIMAL_BIDDING, INITIAL_MINIMAL_BIDDING, INITIAL_MINIMAL_BIDDING, INITIAL_MINIMAL_BIDDING ]; require( genesis >= block.number, "HermezAuctionProtocol::hermezAuctionProtocolInitializer GENESIS_BELOW_MINIMAL" ); tokenHEZ = IHEZToken(token); genesisBlock = genesis; hermezRollup = hermezRollupAddress; governanceAddress = _governanceAddress; _donationAddress = donationAddress; _bootCoordinator = bootCoordinatorAddress; bootCoordinatorURL = _bootCoordinatorURL; emit InitializeHermezAuctionProtocolEvent( donationAddress, bootCoordinatorAddress, _bootCoordinatorURL, _outbidding, _slotDeadline, _closedAuctionSlots, _openAuctionSlots, _allocationRatio ); } /** * @notice Getter of the current `_slotDeadline` * @return The `_slotDeadline` value */ function getSlotDeadline() external override view returns (uint8) { return _slotDeadline; } /** * @notice Allows to change the `_slotDeadline` if it's called by the owner * @param newDeadline new `_slotDeadline` * Events: `NewSlotDeadline` */ function setSlotDeadline(uint8 newDeadline) external override onlyGovernance { require( newDeadline <= BLOCKS_PER_SLOT, "HermezAuctionProtocol::setSlotDeadline: GREATER_THAN_BLOCKS_PER_SLOT" ); _slotDeadline = newDeadline; emit NewSlotDeadline(_slotDeadline); } /** * @notice Getter of the current `_openAuctionSlots` * @return The `_openAuctionSlots` value */ function getOpenAuctionSlots() external override view returns (uint16) { return _openAuctionSlots; } /** * @notice Allows to change the `_openAuctionSlots` if it's called by the owner * @dev Max newOpenAuctionSlots = 65536 slots * @param newOpenAuctionSlots new `_openAuctionSlots` * Events: `NewOpenAuctionSlots` * Note: the governance could set this parameter equal to `ClosedAuctionSlots`, this means that it can prevent bids * from being made and that only the boot coordinator can forge */ function setOpenAuctionSlots(uint16 newOpenAuctionSlots) external override onlyGovernance { _openAuctionSlots = newOpenAuctionSlots; emit NewOpenAuctionSlots(_openAuctionSlots); } /** * @notice Getter of the current `_closedAuctionSlots` * @return The `_closedAuctionSlots` value */ function getClosedAuctionSlots() external override view returns (uint16) { return _closedAuctionSlots; } /** * @notice Allows to change the `_closedAuctionSlots` if it's called by the owner * @dev Max newClosedAuctionSlots = 65536 slots * @param newClosedAuctionSlots new `_closedAuctionSlots` * Events: `NewClosedAuctionSlots` * Note: the governance could set this parameter equal to `OpenAuctionSlots`, this means that it can prevent bids * from being made and that only the boot coordinator can forge */ function setClosedAuctionSlots(uint16 newClosedAuctionSlots) external override onlyGovernance { _closedAuctionSlots = newClosedAuctionSlots; emit NewClosedAuctionSlots(_closedAuctionSlots); } /** * @notice Getter of the current `_outbidding` * @return The `_outbidding` value */ function getOutbidding() external override view returns (uint16) { return _outbidding; } /** * @notice Allows to change the `_outbidding` if it's called by the owner * @dev newOutbidding between 0.01% and 100.00% * @param newOutbidding new `_outbidding` * Events: `NewOutbidding` */ function setOutbidding(uint16 newOutbidding) external override onlyGovernance { require( newOutbidding > 1 && newOutbidding < 10000, "HermezAuctionProtocol::setOutbidding: OUTBIDDING_NOT_VALID" ); _outbidding = newOutbidding; emit NewOutbidding(_outbidding); } /** * @notice Getter of the current `_allocationRatio` * @return The `_allocationRatio` array */ function getAllocationRatio() external override view returns (uint16[3] memory) { return _allocationRatio; } /** * @notice Allows to change the `_allocationRatio` array if it's called by the owner * @param newAllocationRatio new `_allocationRatio` uint8[3] array * Events: `NewAllocationRatio` */ function setAllocationRatio(uint16[3] memory newAllocationRatio) external override onlyGovernance { require( newAllocationRatio[0] <= 10000 && newAllocationRatio[1] <= 10000 && newAllocationRatio[2] <= 10000 && newAllocationRatio[0] + newAllocationRatio[1] + newAllocationRatio[2] == 10000, "HermezAuctionProtocol::setAllocationRatio: ALLOCATION_RATIO_NOT_VALID" ); _allocationRatio = newAllocationRatio; emit NewAllocationRatio(_allocationRatio); } /** * @notice Getter of the current `_donationAddress` * @return The `_donationAddress` */ function getDonationAddress() external override view returns (address) { return _donationAddress; } /** * @notice Allows to change the `_donationAddress` if it's called by the owner * @param newDonationAddress new `_donationAddress` * Events: `NewDonationAddress` */ function setDonationAddress(address newDonationAddress) external override onlyGovernance { require( newDonationAddress != address(0), "HermezAuctionProtocol::setDonationAddress: NOT_VALID_ADDRESS" ); _donationAddress = newDonationAddress; emit NewDonationAddress(_donationAddress); } /** * @notice Getter of the current `_bootCoordinator` * @return The `_bootCoordinator` */ function getBootCoordinator() external override view returns (address) { return _bootCoordinator; } /** * @notice Allows to change the `_bootCoordinator` if it's called by the owner * @param newBootCoordinator new `_bootCoordinator` uint8[3] array * Events: `NewBootCoordinator` */ function setBootCoordinator( address newBootCoordinator, string memory newBootCoordinatorURL ) external override onlyGovernance { _bootCoordinator = newBootCoordinator; bootCoordinatorURL = newBootCoordinatorURL; emit NewBootCoordinator(_bootCoordinator, newBootCoordinatorURL); } /** * @notice Returns the minimum default bid for an slotSet * @param slotSet to obtain the minimum default bid * @return the minimum default bid for an slotSet */ function getDefaultSlotSetBid(uint8 slotSet) public view returns (uint128) { return _defaultSlotSetBid[slotSet]; } /** * @notice Allows to change the change the min bid for an slotSet if it's called by the owner. * @dev If an slotSet has the value of 0 it's considered decentralized, so the minbid cannot be modified * @param slotSet the slotSet to update * @param newInitialMinBid the minBid * Events: `NewDefaultSlotSetBid` */ function changeDefaultSlotSetBid(uint128 slotSet, uint128 newInitialMinBid) external override onlyGovernance { require( slotSet < _defaultSlotSetBid.length, "HermezAuctionProtocol::changeDefaultSlotSetBid: NOT_VALID_SLOT_SET" ); require( _defaultSlotSetBid[slotSet] != 0, "HermezAuctionProtocol::changeDefaultSlotSetBid: SLOT_DECENTRALIZED" ); uint128 current = getCurrentSlotNumber(); // This prevents closed bids from being modified for (uint128 i = current; i <= current + _closedAuctionSlots; i++) { // Save the minbid in case it has not been previously set if (slots[i].closedMinBid == 0) { slots[i].closedMinBid = _defaultSlotSetBid[getSlotSet(i)]; } } _defaultSlotSetBid[slotSet] = newInitialMinBid; emit NewDefaultSlotSetBid(slotSet, newInitialMinBid); } /** * @notice Allows to register a new coordinator * @dev The `msg.sender` will be considered the `bidder`, who can change the forger address and the url * @param forger the address allowed to forger batches * @param coordinatorURL endopoint for this coordinator * Events: `NewCoordinator` */ function setCoordinator(address forger, string memory coordinatorURL) external override { require( keccak256(abi.encodePacked(coordinatorURL)) != keccak256(abi.encodePacked("")), "HermezAuctionProtocol::setCoordinator: NOT_VALID_URL" ); coordinators[msg.sender].forger = forger; coordinators[msg.sender].coordinatorURL = coordinatorURL; emit SetCoordinator(msg.sender, forger, coordinatorURL); } /** * @notice Returns the current slot number * @return slotNumber an uint128 with the current slot */ function getCurrentSlotNumber() public view returns (uint128) { return getSlotNumber(uint128(block.number)); } /** * @notice Returns the slot number of a given block * @param blockNumber from which to calculate the slot * @return slotNumber an uint128 with the slot calculated */ function getSlotNumber(uint128 blockNumber) public view returns (uint128) { return (blockNumber >= genesisBlock) ? ((blockNumber - genesisBlock) / BLOCKS_PER_SLOT) : uint128(0); } /** * @notice Returns an slotSet given an slot * @param slot from which to calculate the slotSet * @return the slotSet of the slot */ function getSlotSet(uint128 slot) public view returns (uint128) { return slot.mod(uint128(_defaultSlotSetBid.length)); } /** * @notice gets the minimum bid that someone has to bid to win the slot for a given slot * @dev it will revert in case of trying to obtain the minimum bid for a closed slot * @param slot from which to get the minimum bid * @return the minimum amount to bid */ function getMinBidBySlot(uint128 slot) public view returns (uint128) { require( slot > (getCurrentSlotNumber() + _closedAuctionSlots), "HermezAuctionProtocol::getMinBidBySlot: AUCTION_CLOSED" ); uint128 slotSet = getSlotSet(slot); // If the bidAmount for a slot is 0 it means that it has not yet been bid, so the midBid will be the minimum // bid for the slot time plus the outbidding set, otherwise it will be the bidAmount plus the outbidding return (slots[slot].bidAmount == 0) ? _defaultSlotSetBid[slotSet].add( _defaultSlotSetBid[slotSet].mul(_outbidding).div( uint128(10000) // two decimal precision ) ) : slots[slot].bidAmount.add( slots[slot].bidAmount.mul(_outbidding).div(uint128(10000)) // two decimal precision ); } /** * @notice Function to process a single bid * @dev If the bytes calldata permit parameter is empty the smart contract assume that it has enough allowance to * make the transferFrom. In case you want to use permit, you need to send the data of the permit call in bytes * @param amount the amount of tokens that have been sent * @param slot the slot for which the caller is bidding * @param bidAmount the amount of the bidding */ function processBid( uint128 amount, uint128 slot, uint128 bidAmount, bytes calldata permit ) external override { // To avoid possible mistakes we don't allow anyone to bid without setting a forger require( coordinators[msg.sender].forger != address(0), "HermezAuctionProtocol::processBid: COORDINATOR_NOT_REGISTERED" ); require( slot > (getCurrentSlotNumber() + _closedAuctionSlots), "HermezAuctionProtocol::processBid: AUCTION_CLOSED" ); require( bidAmount >= getMinBidBySlot(slot), "HermezAuctionProtocol::processBid: BELOW_MINIMUM" ); require( slot <= (getCurrentSlotNumber() + _closedAuctionSlots + _openAuctionSlots), "HermezAuctionProtocol::processBid: AUCTION_NOT_OPEN" ); if (permit.length != 0) { _permit(amount, permit); } require( tokenHEZ.transferFrom(msg.sender, address(this), amount), "HermezAuctionProtocol::processBid: TOKEN_TRANSFER_FAILED" ); pendingBalances[msg.sender] = pendingBalances[msg.sender].add(amount); require( pendingBalances[msg.sender] >= bidAmount, "HermezAuctionProtocol::processBid: NOT_ENOUGH_BALANCE" ); _doBid(slot, bidAmount, msg.sender); } /** * @notice function to process a multi bid * @dev If the bytes calldata permit parameter is empty the smart contract assume that it has enough allowance to * make the transferFrom. In case you want to use permit, you need to send the data of the permit call in bytes * @param amount the amount of tokens that have been sent * @param startingSlot the first slot to bid * @param endingSlot the last slot to bid * @param slotSets the set of slots to which the coordinator wants to bid * @param maxBid the maximum bid that is allowed * @param minBid the minimum that you want to bid */ function processMultiBid( uint128 amount, uint128 startingSlot, uint128 endingSlot, bool[6] memory slotSets, uint128 maxBid, uint128 minBid, bytes calldata permit ) external override { require( startingSlot > (getCurrentSlotNumber() + _closedAuctionSlots), "HermezAuctionProtocol::processMultiBid AUCTION_CLOSED" ); require( endingSlot <= (getCurrentSlotNumber() + _closedAuctionSlots + _openAuctionSlots), "HermezAuctionProtocol::processMultiBid AUCTION_NOT_OPEN" ); require( maxBid >= minBid, "HermezAuctionProtocol::processMultiBid MAXBID_GREATER_THAN_MINBID" ); // To avoid possible mistakes we don't allow anyone to bid without setting a forger require( coordinators[msg.sender].forger != address(0), "HermezAuctionProtocol::processMultiBid COORDINATOR_NOT_REGISTERED" ); if (permit.length != 0) { _permit(amount, permit); } require( tokenHEZ.transferFrom(msg.sender, address(this), amount), "HermezAuctionProtocol::processMultiBid: TOKEN_TRANSFER_FAILED" ); pendingBalances[msg.sender] = pendingBalances[msg.sender].add(amount); uint128 bidAmount; for (uint128 slot = startingSlot; slot <= endingSlot; slot++) { uint128 minBidBySlot = getMinBidBySlot(slot); // In case that the minimum bid is below the desired minimum bid, we will use this lower limit as the bid if (minBidBySlot <= minBid) { bidAmount = minBid; // If the `minBidBySlot` is between the upper (`maxBid`) and lower limit (`minBid`) we will use // this value `minBidBySlot` as the bid } else if (minBidBySlot > minBid && minBidBySlot <= maxBid) { bidAmount = minBidBySlot; // if the `minBidBySlot` is higher than the upper limit `maxBid`, we will not bid for this slot } else { continue; } // check if it is a selected slotSet if (slotSets[getSlotSet(slot)]) { require( pendingBalances[msg.sender] >= bidAmount, "HermezAuctionProtocol::processMultiBid NOT_ENOUGH_BALANCE" ); _doBid(slot, bidAmount, msg.sender); } } } /** * @notice function to call token permit function * @param _amount the quantity that is expected to be allowed * @param _permitData the raw data of the call `permit` of the token */ function _permit(uint256 _amount, bytes calldata _permitData) internal { bytes4 sig = abi.decode(_permitData, (bytes4)); require( sig == _PERMIT_SIGNATURE, "HermezAuctionProtocol::_permit: NOT_VALID_CALL" ); ( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) = abi.decode( _permitData[4:], (address, address, uint256, uint256, uint8, bytes32, bytes32) ); require( owner == msg.sender, "HermezAuctionProtocol::_permit: OWNER_NOT_EQUAL_SENDER" ); require( spender == address(this), "HermezAuctionProtocol::_permit: SPENDER_NOT_EQUAL_THIS" ); require( value == _amount, "HermezAuctionProtocol::_permit: WRONG_AMOUNT" ); // we call without checking the result, in case it fails and he doesn't have enough balance // the following transferFrom should be fail. This prevents DoS attacks from using a signature // before the smartcontract call /* solhint-disable avoid-low-level-calls avoid-call-value */ address(tokenHEZ).call( abi.encodeWithSelector( _PERMIT_SIGNATURE, owner, spender, value, deadline, v, r, s ) ); } /** * @notice Internal function to make the bid * @dev will only be called by processBid or processMultiBid * @param slot the slot for which the caller is bidding * @param bidAmount the amount of the bidding * @param bidder the address of the bidder * Events: `NewBid` */ function _doBid( uint128 slot, uint128 bidAmount, address bidder ) private { address prevBidder = slots[slot].bidder; uint128 prevBidValue = slots[slot].bidAmount; require( bidAmount > prevBidValue, "HermezAuctionProtocol::_doBid: BID_MUST_BE_HIGHER" ); pendingBalances[bidder] = pendingBalances[bidder].sub(bidAmount); slots[slot].bidder = bidder; slots[slot].bidAmount = bidAmount; // If there is a previous bid we must return the HEZ tokens if (prevBidder != address(0) && prevBidValue != 0) { pendingBalances[prevBidder] = pendingBalances[prevBidder].add( prevBidValue ); } emit NewBid(slot, bidAmount, bidder); } /** * @notice function to know if a certain address can forge into a certain block * @param forger the address of the coodirnator's forger * @param blockNumber block number to check * @return a bool true in case it can forge, false otherwise */ function canForge(address forger, uint256 blockNumber) external override view returns (bool) { return _canForge(forger, blockNumber); } /** * @notice function to know if a certain address can forge into a certain block * @param forger the address of the coodirnator's forger * @param blockNumber block number to check * @return a bool true in case it can forge, false otherwise */ function _canForge(address forger, uint256 blockNumber) internal view returns (bool) { require( blockNumber < 2**128, "HermezAuctionProtocol::canForge WRONG_BLOCKNUMBER" ); require( blockNumber >= genesisBlock, "HermezAuctionProtocol::canForge AUCTION_NOT_STARTED" ); uint128 slotToForge = getSlotNumber(uint128(blockNumber)); // Get the relativeBlock to check if the slotDeadline has been exceeded uint128 relativeBlock = uint128(blockNumber).sub( (slotToForge.mul(BLOCKS_PER_SLOT)).add(genesisBlock) ); // If the closedMinBid is 0 it means that we have to take as minBid the one that is set for this slot set, // otherwise the one that has been saved will be used uint128 minBid = (slots[slotToForge].closedMinBid == 0) ? _defaultSlotSetBid[getSlotSet(slotToForge)] : slots[slotToForge].closedMinBid; // if the relative block has exceeded the slotDeadline and no batch has been forged, anyone can forge if ( !slots[slotToForge].forgerCommitment && (relativeBlock >= _slotDeadline) ) { return true; //if forger bidAmount has exceeded the minBid it can forge } else if ( (coordinators[slots[slotToForge].bidder].forger == forger) && (slots[slotToForge].bidAmount >= minBid) ) { return true; //if it's the boot coordinator and it has not been bid or the bid is below the minimum it can forge } else if ( (_bootCoordinator == forger) && ((slots[slotToForge].bidAmount < minBid) || (slots[slotToForge].bidAmount == 0)) ) { return true; // if it is not any of these three cases will not be able to forge } else { return false; } } /** * @notice function to process the forging * @param forger the address of the coodirnator's forger * Events: `NewForgeAllocated` and `NewForge` */ function forge(address forger) external override { require( msg.sender == hermezRollup, "HermezAuctionProtocol::forge: ONLY_HERMEZ_ROLLUP" ); require( _canForge(forger, block.number), "HermezAuctionProtocol::forge: CANNOT_FORGE" ); uint128 slotToForge = getCurrentSlotNumber(); if (!slots[slotToForge].forgerCommitment) { // Get the relativeBlock to check if the slotDeadline has been exceeded uint128 relativeBlock = uint128(block.number).sub( (slotToForge.mul(BLOCKS_PER_SLOT)).add(genesisBlock) ); if (relativeBlock < _slotDeadline) { slots[slotToForge].forgerCommitment = true; } } // Default values:** Burn: 40% - Donation: 40% - HGT: 20% // Allocated is used to know if we have already distributed the HEZ tokens if (!slots[slotToForge].fulfilled) { slots[slotToForge].fulfilled = true; if (slots[slotToForge].bidAmount != 0) { // If the closedMinBid is 0 it means that we have to take as minBid the one that is set for this slot set, // otherwise the one that has been saved will be used uint128 minBid = (slots[slotToForge].closedMinBid == 0) ? _defaultSlotSetBid[getSlotSet(slotToForge)] : slots[slotToForge].closedMinBid; // If the bootcoordinator is forging and there has been a previous bid that is lower than the slot min bid, // we must return the tokens to the bidder and the tokens have not been distributed if (slots[slotToForge].bidAmount < minBid) { // We save the minBid that this block has had pendingBalances[slots[slotToForge] .bidder] = pendingBalances[slots[slotToForge].bidder] .add(slots[slotToForge].bidAmount); // In case the winner is forging we have to allocate the tokens according to the desired distribution } else { uint128 bidAmount = slots[slotToForge].bidAmount; // calculation of token distribution uint128 amountToBurn = bidAmount .mul(_allocationRatio[0]) .div(uint128(10000)); // Two decimal precision uint128 donationAmount = bidAmount .mul(_allocationRatio[1]) .div(uint128(10000)); // Two decimal precision uint128 governanceAmount = bidAmount .mul(_allocationRatio[2]) .div(uint128(10000)); // Two decimal precision // Tokens to burn require( tokenHEZ.burn(amountToBurn), "HermezAuctionProtocol::forge: TOKEN_BURN_FAILED" ); // Tokens to donate pendingBalances[_donationAddress] = pendingBalances[_donationAddress] .add(donationAmount); // Tokens for the governace address pendingBalances[governanceAddress] = pendingBalances[governanceAddress] .add(governanceAmount); emit NewForgeAllocated( slots[slotToForge].bidder, forger, slotToForge, amountToBurn, donationAmount, governanceAmount ); } } } emit NewForge(forger, slotToForge); } function claimPendingHEZ(uint128 slot) public { require( slot < getCurrentSlotNumber(), "HermezAuctionProtocol::claimPendingHEZ: ONLY_IF_PREVIOUS_SLOT" ); require( !slots[slot].fulfilled, "HermezAuctionProtocol::claimPendingHEZ: ONLY_IF_NOT_FULFILLED" ); // If the closedMinBid is 0 it means that we have to take as minBid the one that is set for this slot set, // otherwise the one that has been saved will be used uint128 minBid = (slots[slot].closedMinBid == 0) ? _defaultSlotSetBid[getSlotSet(slot)] : slots[slot].closedMinBid; require( slots[slot].bidAmount < minBid, "HermezAuctionProtocol::claimPendingHEZ: ONLY_IF_NOT_FULFILLED" ); slots[slot].closedMinBid = minBid; slots[slot].fulfilled = true; pendingBalances[slots[slot].bidder] = pendingBalances[slots[slot] .bidder] .add(slots[slot].bidAmount); } /** * @notice function to know how much HEZ tokens are pending to be claimed for an address * @param bidder address to query * @return the total claimable HEZ by an address */ function getClaimableHEZ(address bidder) public view returns (uint128) { return pendingBalances[bidder]; } /** * @notice distributes the tokens to msg.sender address * Events: `HEZClaimed` */ function claimHEZ() public nonReentrant { uint128 pending = getClaimableHEZ(msg.sender); require( pending > 0, "HermezAuctionProtocol::claimHEZ: NOT_ENOUGH_BALANCE" ); pendingBalances[msg.sender] = 0; require( tokenHEZ.transfer(msg.sender, pending), "HermezAuctionProtocol::claimHEZ: TOKEN_TRANSFER_FAILED" ); emit HEZClaimed(msg.sender, pending); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; interface IHEZToken { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function burn(uint256 value) external returns (bool); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; /** * @dev Hermez will run an auction to incentivise efficiency in coordinators, * meaning that they need to be very effective and include as many transactions * as they can in the slots in order to compensate for their bidding costs, gas * costs and operations costs.The general porpouse of this smartcontract is to * define the rules to coordinate this auction where the bids will be placed * only in HEZ utility token. */ interface IHermezAuctionProtocol { /** * @notice Getter of the current `_slotDeadline` * @return The `_slotDeadline` value */ function getSlotDeadline() external view returns (uint8); /** * @notice Allows to change the `_slotDeadline` if it's called by the owner * @param newDeadline new `_slotDeadline` * Events: `NewSlotDeadline` */ function setSlotDeadline(uint8 newDeadline) external; /** * @notice Getter of the current `_openAuctionSlots` * @return The `_openAuctionSlots` value */ function getOpenAuctionSlots() external view returns (uint16); /** * @notice Allows to change the `_openAuctionSlots` if it's called by the owner * @dev Max newOpenAuctionSlots = 65536 slots * @param newOpenAuctionSlots new `_openAuctionSlots` * Events: `NewOpenAuctionSlots` * Note: the governance could set this parameter equal to `ClosedAuctionSlots`, this means that it can prevent bids * from being made and that only the boot coordinator can forge */ function setOpenAuctionSlots(uint16 newOpenAuctionSlots) external; /** * @notice Getter of the current `_closedAuctionSlots` * @return The `_closedAuctionSlots` value */ function getClosedAuctionSlots() external view returns (uint16); /** * @notice Allows to change the `_closedAuctionSlots` if it's called by the owner * @dev Max newClosedAuctionSlots = 65536 slots * @param newClosedAuctionSlots new `_closedAuctionSlots` * Events: `NewClosedAuctionSlots` * Note: the governance could set this parameter equal to `OpenAuctionSlots`, this means that it can prevent bids * from being made and that only the boot coordinator can forge */ function setClosedAuctionSlots(uint16 newClosedAuctionSlots) external; /** * @notice Getter of the current `_outbidding` * @return The `_outbidding` value */ function getOutbidding() external view returns (uint16); /** * @notice Allows to change the `_outbidding` if it's called by the owner * @dev newOutbidding between 0.00% and 655.36% * @param newOutbidding new `_outbidding` * Events: `NewOutbidding` */ function setOutbidding(uint16 newOutbidding) external; /** * @notice Getter of the current `_allocationRatio` * @return The `_allocationRatio` array */ function getAllocationRatio() external view returns (uint16[3] memory); /** * @notice Allows to change the `_allocationRatio` array if it's called by the owner * @param newAllocationRatio new `_allocationRatio` uint8[3] array * Events: `NewAllocationRatio` */ function setAllocationRatio(uint16[3] memory newAllocationRatio) external; /** * @notice Getter of the current `_donationAddress` * @return The `_donationAddress` */ function getDonationAddress() external view returns (address); /** * @notice Allows to change the `_donationAddress` if it's called by the owner * @param newDonationAddress new `_donationAddress` * Events: `NewDonationAddress` */ function setDonationAddress(address newDonationAddress) external; /** * @notice Getter of the current `_bootCoordinator` * @return The `_bootCoordinator` */ function getBootCoordinator() external view returns (address); /** * @notice Allows to change the `_bootCoordinator` if it's called by the owner * @param newBootCoordinator new `_bootCoordinator` uint8[3] array * Events: `NewBootCoordinator` */ function setBootCoordinator( address newBootCoordinator, string memory newBootCoordinatorURL ) external; /** * @notice Allows to change the change the min bid for an slotSet if it's called by the owner. * @dev If an slotSet has the value of 0 it's considered decentralized, so the minbid cannot be modified * @param slotSet the slotSet to update * @param newInitialMinBid the minBid * Events: `NewDefaultSlotSetBid` */ function changeDefaultSlotSetBid(uint128 slotSet, uint128 newInitialMinBid) external; /** * @notice Allows to register a new coordinator * @dev The `msg.sender` will be considered the `bidder`, who can change the forger address and the url * @param forger the address allowed to forger batches * @param coordinatorURL endopoint for this coordinator * Events: `NewCoordinator` */ function setCoordinator(address forger, string memory coordinatorURL) external; /** * @notice Function to process a single bid * @dev If the bytes calldata permit parameter is empty the smart contract assume that it has enough allowance to * make the transferFrom. In case you want to use permit, you need to send the data of the permit call in bytes * @param amount the amount of tokens that have been sent * @param slot the slot for which the caller is bidding * @param bidAmount the amount of the bidding */ function processBid( uint128 amount, uint128 slot, uint128 bidAmount, bytes calldata permit ) external; /** * @notice function to process a multi bid * @dev If the bytes calldata permit parameter is empty the smart contract assume that it has enough allowance to * make the transferFrom. In case you want to use permit, you need to send the data of the permit call in bytes * @param amount the amount of tokens that have been sent * @param startingSlot the first slot to bid * @param endingSlot the last slot to bid * @param slotSets the set of slots to which the coordinator wants to bid * @param maxBid the maximum bid that is allowed * @param minBid the minimum that you want to bid */ function processMultiBid( uint128 amount, uint128 startingSlot, uint128 endingSlot, bool[6] memory slotSets, uint128 maxBid, uint128 minBid, bytes calldata permit ) external; /** * @notice function to process the forging * @param forger the address of the coodirnator's forger * Events: `NewForgeAllocated` and `NewForge` */ function forge(address forger) external; /** * @notice function to know if a certain address can forge into a certain block * @param forger the address of the coodirnator's forger * @param blockNumber block number to check * @return a bool true in case it can forge, false otherwise */ function canForge(address forger, uint256 blockNumber) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.24 <0.7.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 {UpgradeableProxy-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 || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../proxy/Initializable.sol"; /** * @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]. */ contract ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; }
* @notice Returns the current slot number @return slotNumber an uint128 with the current slot/
function getCurrentSlotNumber() public view returns (uint128) { return getSlotNumber(uint128(block.number)); }
11,841,102
[ 1, 1356, 326, 783, 4694, 1300, 327, 4694, 1854, 392, 2254, 10392, 598, 326, 783, 4694, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5175, 8764, 1854, 1435, 1071, 1476, 1135, 261, 11890, 10392, 13, 288, 203, 3639, 327, 17718, 352, 1854, 12, 11890, 10392, 12, 2629, 18, 2696, 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 ]
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; contract StarNotary is ERC721 { struct Star { string name; } // Add a name and a symbol for your starNotary tokens string public constant name = "CDC Star Notary"; string public constant symbol = "CSN"; // mapping(uint256 => Star) public tokenIdToStarInfo; mapping(uint256 => uint256) public starsForSale; // uint256[] public tokenIds; // function getTokenIds() public view returns (uint256[]){ // return tokenIds; // } function createStar(string memory _name, uint256 _tokenId) public { Star memory newStar = Star(_name); tokenIdToStarInfo[_tokenId] = newStar; // tokenIds.push(_tokenId); _mint(msg.sender, _tokenId); } // Add a function lookUptokenIdToStarInfo, that looks up the stars using the Token ID, and then returns the name of the star. function lookUptokenIdToStarInfo(uint256 _tokenId) public view returns (string memory) { return tokenIdToStarInfo[_tokenId].name; } // function putStarUpForSale(uint256 _tokenId, uint256 _price) public { require(ownerOf(_tokenId) == msg.sender); starsForSale[_tokenId] = _price; } function buyStar(uint256 _tokenId) public payable { require(starsForSale[_tokenId] > 0); uint256 starCost = starsForSale[_tokenId]; address starOwner = ownerOf(_tokenId); require(msg.value >= starCost); _removeTokenFrom(starOwner, _tokenId); _addTokenTo(msg.sender, _tokenId); // starOwner.transfer(starCost); if(msg.value > starCost) { msg.sender.transfer(msg.value - starCost); } starsForSale[_tokenId] = 0; } // Add a function called exchangeStars, so 2 users can exchange their star tokens... //Do not worry about the price, just write code to exchange stars between users. function exchangeStars(uint256 _token1, uint256 _token2) public { require(ownerOf(_token1) == msg.sender); require(ownerOf(_token2) != msg.sender); address otherParty = ownerOf(_token2); require(ownerOf(_token1) != otherParty); safeTransferFrom(msg.sender, otherParty, _token1); unsafeTransfer(otherParty, msg.sender, _token2); /* for (uint i = 0; i < tokenIds.length; i++) { if(ownerOf(tokenIds[i]) == _address1) { unsafeTransfer(_address1, _address2, tokenIds[i]); } else if(ownerOf(tokenIds[i]) == _address2) { unsafeTransfer(_address2, _address1, tokenIds[i]); } } */ } function unsafeTransfer(address _from, address _to, uint256 _tokenId) private { _removeTokenFrom(_from, _tokenId); _addTokenTo(_to, _tokenId); } // // Write a function to Transfer a Star. The function should transfer a star from the address of the caller. // The function should accept 2 arguments, the address to transfer the star to, and the token ID of the star. // function transferStar(address _to, uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); safeTransferFrom(msg.sender, _to, _tokenId); } }
starOwner.transfer(starCost);
function buyStar(uint256 _tokenId) public payable { require(starsForSale[_tokenId] > 0); uint256 starCost = starsForSale[_tokenId]; address starOwner = ownerOf(_tokenId); require(msg.value >= starCost); _removeTokenFrom(starOwner, _tokenId); _addTokenTo(msg.sender, _tokenId); if(msg.value > starCost) { msg.sender.transfer(msg.value - starCost); } starsForSale[_tokenId] = 0; }
14,082,203
[ 1, 10983, 5541, 18, 13866, 12, 10983, 8018, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 18379, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 334, 5913, 1290, 30746, 63, 67, 2316, 548, 65, 405, 374, 1769, 203, 203, 3639, 2254, 5034, 10443, 8018, 273, 24084, 1290, 30746, 63, 67, 2316, 548, 15533, 203, 3639, 1758, 10443, 5541, 273, 3410, 951, 24899, 2316, 548, 1769, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 10443, 8018, 1769, 203, 203, 3639, 389, 4479, 1345, 1265, 12, 10983, 5541, 16, 389, 2316, 548, 1769, 203, 3639, 389, 1289, 1345, 774, 12, 3576, 18, 15330, 16, 389, 2316, 548, 1769, 203, 203, 203, 3639, 309, 12, 3576, 18, 1132, 405, 10443, 8018, 13, 288, 203, 5411, 1234, 18, 15330, 18, 13866, 12, 3576, 18, 1132, 300, 10443, 8018, 1769, 203, 3639, 289, 203, 3639, 24084, 1290, 30746, 63, 67, 2316, 548, 65, 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 ]
./full_match/1/0xC9Be8544Ce916a194B00151ed3d423E6d51DaAea/sources/DumbMoney.sol
this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer( address sender, address recipient, uint256 amount ) private { if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { removeAllFee(); } uint256 marketingAmt = amount.mul(_marketingPercentage).div(10000); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded( sender, recipient, (amount.sub(burnAmt).sub(marketingAmt)) ); _transferToExcluded( sender, recipient, (amount.sub(burnAmt).sub(marketingAmt)) ); _transferStandard( sender, recipient, (amount.sub(burnAmt).sub(marketingAmt)) ); _transferBothExcluded( sender, recipient, (amount.sub(burnAmt).sub(marketingAmt)) ); _transferStandard( sender, recipient, (amount.sub(burnAmt).sub(marketingAmt)) ); } _liquidityFee = 0; _transferStandard(sender, marketingWallet, marketingAmt); _liquidityFee = _previousLiquidityFee; if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) restoreAllFee(); }
3,848,131
[ 1, 2211, 707, 353, 14549, 364, 13763, 777, 14036, 16, 309, 4862, 14667, 353, 638, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2316, 5912, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3238, 288, 203, 3639, 309, 261, 67, 291, 16461, 1265, 14667, 63, 15330, 65, 747, 389, 291, 16461, 1265, 14667, 63, 20367, 5717, 288, 203, 5411, 12787, 14667, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 13667, 310, 31787, 273, 3844, 18, 16411, 24899, 3355, 21747, 16397, 2934, 2892, 12, 23899, 1769, 203, 203, 3639, 309, 261, 67, 291, 16461, 63, 15330, 65, 597, 401, 67, 291, 16461, 63, 20367, 5717, 288, 203, 5411, 389, 13866, 1265, 16461, 12, 203, 7734, 5793, 16, 203, 7734, 8027, 16, 203, 7734, 261, 8949, 18, 1717, 12, 70, 321, 31787, 2934, 1717, 12, 3355, 21747, 31787, 3719, 203, 5411, 11272, 203, 5411, 389, 13866, 774, 16461, 12, 203, 7734, 5793, 16, 203, 7734, 8027, 16, 203, 7734, 261, 8949, 18, 1717, 12, 70, 321, 31787, 2934, 1717, 12, 3355, 21747, 31787, 3719, 203, 5411, 11272, 203, 5411, 389, 13866, 8336, 12, 203, 7734, 5793, 16, 203, 7734, 8027, 16, 203, 7734, 261, 8949, 18, 1717, 12, 70, 321, 31787, 2934, 1717, 12, 3355, 21747, 31787, 3719, 203, 5411, 11272, 203, 5411, 389, 13866, 20240, 16461, 12, 203, 7734, 5793, 16, 203, 7734, 8027, 16, 203, 7734, 261, 8949, 18, 1717, 12, 70, 321, 31787, 2934, 1717, 12, 3355, 21747, 31787, 3719, 203, 5411, 11272, 203, 5411, 389, 13866, 8336, 12, 203, 7734, 5793, 16, 203, 7734, 8027, 16, 203, 7734, 261, 8949, 18, 2 ]
// Sources flattened with hardhat v2.6.5 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] 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() { _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); } } // File @openzeppelin/contracts/utils/introspection/[email protected] 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/[email protected] 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/[email protected] 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/token/ERC721/extensions/[email protected] 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/utils/[email protected] 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); } } } } // File @openzeppelin/contracts/utils/[email protected] 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); } } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract 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 {} } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] 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/extensions/[email protected] pragma solidity ^0.8.0; /** * @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(); } } // File @openzeppelin/contracts/security/[email protected] 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; } } // File contracts/GenerARTed.sol pragma solidity ^0.8.6; contract GenerARTed is ERC721Enumerable, Ownable, ReentrancyGuard { using Strings for uint256; uint256 public maxSupply = 10_000; uint256 public totalCount; address payable public charityAddress; uint256 public maxBatch = 1000; uint256 public tokensPerAddress = 1000; uint256 public price = 0.05 ether; mapping (address=> uint256) minted; string public baseURI; bool private isStarted; constructor(string memory baseURI_, address payable charityAddress_) ERC721("GenerARTed", "ART") { baseURI = baseURI_; charityAddress = charityAddress_; } function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory existedBaseURI = _baseURI(); return bytes(existedBaseURI).length > 0 ? string(abi.encodePacked(existedBaseURI, tokenId.toString())) : ''; } function setStart(bool _start) public onlyOwner { isStarted = _start; } function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 count = balanceOf(owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } function mint(uint256 _times) payable public nonReentrant { require(isStarted, "Sale ain't started, partner."); require(_times > 0 && _times <= maxBatch, "Too many tokens"); require(totalCount + _times <= maxSupply, "ALL BOUGHT OUT"); require(msg.value == _times * price, "Value error, please check price."); require(minted[msg.sender] + _times <= tokensPerAddress, "Max tokens per address"); minted[msg.sender] = minted[msg.sender] + _times; (bool sent,) = charityAddress.call{value: msg.value}(""); require(sent, "Fail to send"); for(uint256 i = 0; i < _times; i++){ _mint(_msgSender(), 1 + totalCount++); } } }
* @dev Returns the total amount of tokens stored by the contract./* @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./* @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./ File @openzeppelin/contracts/token/ERC721/extensions/[email protected]* @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./ Mapping from owner to list of owned token IDs Mapping from token ID to index of the owner tokens list Array with all token ids, used for enumeration Mapping from token id to position in the allTokens array
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { mapping(address => mapping(uint256 => uint256)) private _ownedTokens; mapping(uint256 => uint256) private _ownedTokensIndex; uint256[] private _allTokens; mapping(uint256 => uint256) private _allTokensIndex; function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } 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]; } function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (from != to) { function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (to != from) { function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } delete _ownedTokensIndex[tokenId]; function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; delete _allTokensIndex[tokenId]; _allTokens.pop(); } }
12,216,840
[ 1, 1356, 326, 2078, 3844, 434, 2430, 4041, 635, 326, 6835, 18, 19, 225, 2860, 279, 1147, 1599, 16199, 635, 1375, 8443, 68, 622, 279, 864, 1375, 1615, 68, 434, 2097, 1147, 666, 18, 2672, 7563, 598, 288, 12296, 951, 97, 358, 4241, 777, 434, 12176, 8443, 10335, 11, 87, 2430, 18, 19, 225, 2860, 279, 1147, 1599, 622, 279, 864, 1375, 1615, 68, 434, 777, 326, 2430, 4041, 635, 326, 6835, 18, 2672, 7563, 598, 288, 4963, 3088, 1283, 97, 358, 4241, 777, 2430, 18, 19, 1387, 632, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 27, 5340, 19, 9489, 19, 654, 39, 27, 5340, 3572, 25121, 18, 18281, 36, 90, 24, 18, 23, 18, 22, 225, 1220, 4792, 392, 3129, 2710, 434, 288, 654, 39, 27, 5340, 97, 2553, 316, 326, 512, 2579, 716, 4831, 3557, 2967, 434, 777, 326, 1147, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 17801, 6835, 4232, 39, 27, 5340, 3572, 25121, 353, 4232, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 3572, 25121, 288, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 3238, 389, 995, 329, 5157, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 995, 329, 5157, 1016, 31, 203, 203, 565, 2254, 5034, 8526, 3238, 389, 454, 5157, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 454, 5157, 1016, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 203, 21281, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 97, 203, 203, 203, 203, 21281, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 12, 45, 654, 39, 28275, 16, 4232, 39, 27, 5340, 13, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 3572, 25121, 2934, 5831, 548, 747, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 1147, 951, 5541, 21268, 12, 2867, 3410, 16, 2254, 5034, 770, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 1615, 411, 4232, 39, 27, 5340, 18, 12296, 951, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import "./base/BaseTest.sol"; import "./mocks/MockERC20.sol"; import "./mocks/MockERC721.sol"; import "../Wallet.sol"; contract WalletTest is BaseTest { MockERC20 mockToken; MockERC721 mockNft; uint256 tokenId; Wallet wallet; // homage to 3Blue1Brown address owner = address(0x3b1b); address newOwner = address(0xdead); function _hashAddr(address addr) internal pure returns (bytes32) { return keccak256(abi.encodePacked(addr)); } // guardians address g1 = address(0x1); address g2 = address(0x2); address g3 = address(0x3); bytes32 g1Hash = _hashAddr(g1); bytes32 g2Hash = _hashAddr(g2); bytes32 g3Hash = _hashAddr(g3); address possibleG = address(0x4); bytes32 possibleGHash = _hashAddr(possibleG); address fakeG; function setUp() public { // Set up wallet bytes32[] memory guardianHashes = new bytes32[](3); guardianHashes[0] = g1Hash; guardianHashes[1] = g2Hash; guardianHashes[2] = g3Hash; // spoof owner hevm.startPrank(owner); wallet = new Wallet(guardianHashes, 2); // Set up utils mockToken = new MockERC20(); mockToken.mint(address(wallet), 100*10**mockToken.decimals()); mockNft = new MockERC721(); tokenId = 1; mockNft.mint(owner, tokenId); } function testExecuteTx() public { uint256 tokensToAdd = 100*10**mockToken.decimals(); bytes memory data = abi.encodeWithSignature("mint(address,uint256)", address(wallet), tokensToAdd); uint256 balanceBefore = mockToken.balanceOf(address(wallet)); wallet.executeExternalTx(address(mockToken), 0, data); // Balance should've increased by 100 uint256 currBalance = mockToken.balanceOf(address(wallet)); assertEq(currBalance, balanceBefore + tokensToAdd); } function testTransfer() public { hevm.deal(address(wallet), 10 ether); address luckyJoe = address(0xfafa); uint256 balanceBefore = luckyJoe.balance; wallet.executeExternalTx(luckyJoe, 1 ether, ""); // Lucky joe got a free one ether uint256 balanceAfter = luckyJoe.balance; assertEq(balanceAfter, balanceBefore + 1 ether); } function testInitiateRecovery() public { hevm.startPrank(g1); wallet.initiateRecovery(newOwner); } function testRevertInitiateRecovery() public { hevm.startPrank(fakeG); hevm.expectRevert(bytes("only guardian")); wallet.initiateRecovery(newOwner); } function testSupportRecovery() public { testInitiateRecovery(); hevm.startPrank(g2); wallet.supportRecovery(newOwner); } function testFullRecovery() public { testSupportRecovery(); address[] memory guardianList = new address[](2); guardianList[0] = g1; guardianList[1] = g2; wallet.executeRecovery(newOwner, guardianList); assertEq(wallet.owner(), newOwner); } function testGuardianRemoval() public { wallet.initiateGuardianRemoval(g3Hash); hevm.warp(block.timestamp + 4 days); wallet.executeGuardianRemoval(g3Hash, possibleGHash); // Check that g3 is not a guardian, and that possibleG is assertTrue(!wallet.isGuardian(g3Hash)); assertTrue(wallet.isGuardian(possibleGHash)); } function testGuardianNoTransferRemoval() public { // ensure that guardian cannot transfer while queued for removal wallet.initiateGuardianRemoval(g3Hash); hevm.startPrank(g3); hevm.expectRevert(bytes("guardian queueud for removal, cannot transfer guardianship")); wallet.transferGuardianship(possibleGHash); } function testERC721Transfer() public { mockNft.approve(address(wallet), tokenId); mockNft.safeTransferFrom(owner, address(wallet), tokenId); } }
Balance should've increased by 100
function testExecuteTx() public { uint256 tokensToAdd = 100*10**mockToken.decimals(); bytes memory data = abi.encodeWithSignature("mint(address,uint256)", address(wallet), tokensToAdd); uint256 balanceBefore = mockToken.balanceOf(address(wallet)); wallet.executeExternalTx(address(mockToken), 0, data); uint256 currBalance = mockToken.balanceOf(address(wallet)); assertEq(currBalance, balanceBefore + tokensToAdd); }
955,682
[ 1, 13937, 1410, 8081, 31383, 635, 2130, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1842, 5289, 4188, 1435, 1071, 288, 203, 203, 3639, 2254, 5034, 2430, 13786, 273, 2130, 14, 2163, 636, 22851, 1345, 18, 31734, 5621, 203, 3639, 1731, 3778, 501, 273, 24126, 18, 3015, 1190, 5374, 2932, 81, 474, 12, 2867, 16, 11890, 5034, 2225, 16, 1758, 12, 19177, 3631, 2430, 13786, 1769, 203, 3639, 2254, 5034, 11013, 4649, 273, 5416, 1345, 18, 12296, 951, 12, 2867, 12, 19177, 10019, 203, 3639, 9230, 18, 8837, 6841, 4188, 12, 2867, 12, 22851, 1345, 3631, 374, 16, 501, 1769, 203, 203, 3639, 2254, 5034, 4306, 13937, 273, 5416, 1345, 18, 12296, 951, 12, 2867, 12, 19177, 10019, 203, 3639, 1815, 19508, 12, 17016, 13937, 16, 11013, 4649, 397, 2430, 13786, 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 ]
// 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 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 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // 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/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 make it better, stronger, faster, else leave it be /*~~~> Thank you Phunks for your inspiration and phriendship. Never stop phighting, never surrender, always stand up for what is right and make the best of all situations towards all people. Phunks are phreedom phighters! "When the power of love overcomes the love of power the world will know peace." - Jimi Hendrix <3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((((((((((((((((((((((@@@@@##############################%%%%%@@@@@((((((((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((((((((((((((((((((((@@@@@##############################%%%%%@@@@@((((((((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((@@@@@########################################%%%%%@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((@@@@@########################################%%%%%@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@###############@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@###############@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@##########@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((@PhunkyJON was here programming trustless, unstoppable [email protected](((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@/////////////////////////////////////////////@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@/////////////////////////////////////////////@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@#PHUNKYJON///////////////#PHUNKYJON//////////@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@#PHUNKYJON///////////////#PHUNKYJON//////////@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@/////@EYES////////////////////@EYES///////////////@@@@@((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@/////@EYES////////////////////@EYES///////////////[email protected]@((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@//////////////////////////////////////////////////[email protected]@((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@//////////////////////////////////////////////////[email protected]@((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@/////////////////////////////////////////////@@@@@@@@@@((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@/////////////////////////////////////////////@@@@@@@@@@((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@//////////[email protected]@////////////////////#####@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((SMOKE((((((((((@@@@@//////////[email protected]@////////////////////#####@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((@@@@@#####//////////////////////////////##########@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((@@@@@#####//////////////////////////////##########@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((@[email protected]@[email protected]@@###################################@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((@[email protected]@[email protected]@@###################################@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((EMBER(((((,,,,,,,,,,,,,,,,,,,,,,,,,@@@@@MOUTH&&&&&####################@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((EMBER(((((,,,,,,,,,,,,,,,,,,,,,,,,,@@@@@MOUTH&&&&&####################@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((@[email protected]@[email protected]@@##############################/////@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((@[email protected]@[email protected]@@##############################/////@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((((((((((((((((((((((@@@@@##############################//////////@@@@@(((((((((((((((((((((((((%%%%% %%%%%(((((((((((((((((((((((((((((((((((@@@@@##############################//////////@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@///////////////@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((@@@@@@@@@@@@@@@@@@@@@@@@@///////////////@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((@@@@@///////////////@@@@@(((((((((((((((((((((((((%%%%% %%%%%((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((@@@@@///////////////@@@@@(((((((((((((((((((((((((%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@///////////////@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@///////////////@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% <~~~*/ pragma solidity 0.8.7; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract MarketRoleProvider is AccessControl, ReentrancyGuard { address public marketplaceAdd; address public daoAdd; address public nftAdd; address public marketMintAdd; address public offersAdd; address public tradesAdd; address public bidsAdd; address public rewardsAdd; address public roleAdd; address public ownerProxyAdd; address public PHUNKYAdd; address public devSig; uint private killswitch; mapping (bytes32 => address) marketBytes; /*~~~> Roles allow for designated accessibility <~~~*/ bytes32 public constant PROXY_ROLE = keccak256("PROXY_ROLE"); //*~~~> For tracking contract addresses bytes32 public constant DAO = keccak256("DAO"); bytes32 public constant DEV = keccak256("DEV"); bytes32 public constant NFT = keccak256("NFT"); bytes32 public constant MINT = keccak256("MINT"); bytes32 public constant BIDS = keccak256("BIDS"); bytes32 public constant ROLE = keccak256("ROLE"); bytes32 public constant PROXY = keccak256("PROXY"); bytes32 public constant OFFERS = keccak256("OFFERS"); bytes32 public constant TRADES = keccak256("TRADES"); bytes32 public constant PHUNKY = keccak256("PHUNKY"); bytes32 public constant MARKET = keccak256("MARKET"); bytes32 public constant REWARDS = keccak256("REWARDS"); /*~~~> Error message for unauthorized access <~~~*/ string Mess = "Ah Ah Ah, you didn't say the magic word!"; /*~~~> Sets deployment address as default admin role <~~~*/ constructor() { _setupRole(DEFAULT_ADMIN_ROLE,msg.sender); _setupRole(PROXY_ROLE, msg.sender); _setupRole(DEV, msg.sender); killswitch = block.timestamp; } // We've got 30 ether days modifier hasAdmin(){ require(block.timestamp < killswitch + 172800); require(hasRole(PROXY_ROLE, msg.sender), Mess); _; } modifier hasDevAdmin(){ require(hasTheRole(DEV, msg.sender), "DOES NOT HAVE DEV ROLE"); _; } ///@notice For setting new proxy role /* address _sig: address of the contract to be assigned the role */ function setProxyRoleAddress(address newsig) public hasAdmin returns(bool) { marketBytes[PROXY_ROLE] = newsig; return true; } function setDaoAdd(address newdaoAdd) hasDevAdmin public returns(bool){ daoAdd = newdaoAdd; marketBytes[DAO]= newdaoAdd; return true; } function setMarketAdd(address newmrktAdd) hasAdmin public returns(bool){ marketplaceAdd = newmrktAdd; marketBytes[MARKET]= newmrktAdd; return true; } function setNftAdd(address newnftAdd) hasAdmin public returns(bool){ nftAdd = newnftAdd; marketBytes[NFT]= newnftAdd; return true; } function setMarketMintAdd(address newmintAdd) hasAdmin public returns(bool){ marketMintAdd = newmintAdd; marketBytes[MINT] = newmintAdd; return true; } function setOffersAdd(address newoffAdd) hasAdmin public returns(bool){ offersAdd = newoffAdd; marketBytes[OFFERS] = newoffAdd; return true; } function setTradesAdd(address newtradAdd) hasAdmin public returns(bool){ tradesAdd = newtradAdd; marketBytes[TRADES] = newtradAdd; return true; } function setBidsAdd(address newbidsAdd) hasAdmin public returns(bool){ bidsAdd = newbidsAdd; marketBytes[BIDS] = newbidsAdd; return true; } function setRwdsAdd(address newrwdsAdd) hasAdmin public returns(bool){ rewardsAdd = newrwdsAdd; marketBytes[REWARDS] = newrwdsAdd; return true; } function setRoleAdd(address newrole) public hasAdmin returns(bool){ roleAdd = newrole; marketBytes[ROLE] = newrole; return true; } function setOwnerProxyAdd(address newproxyAdd) public hasAdmin returns(bool){ ownerProxyAdd = newproxyAdd; marketBytes[PROXY]=newproxyAdd; return true; } function setPhunkyAdd(address newphunky) public hasDevAdmin returns(bool){ PHUNKYAdd = newphunky; marketBytes[PHUNKY] = newphunky; return true; } function setDevSigAddress(address newsig) public hasDevAdmin returns(bool){ devSig = newsig; marketBytes[DEV] = newsig; return true; } function fetchAddress(bytes32 thevar) public view returns(address){ return marketBytes[thevar]; } function hasTheRole(bytes32 role, address theaddress) public view returns(bool){ return hasRole(role, theaddress); } function hasContractRole(address theaddress) public view returns(bool){ if(theaddress == marketBytes[MARKET] || theaddress == marketBytes[BIDS] || theaddress == marketBytes[OFFERS] || theaddress == marketBytes[TRADES] || theaddress == marketBytes[MINT] ){ return true; } return false; } /// @notice /*~~~> Internal function for sending ether <~~~*/ /// @return Bool function sendEther(address recipient, uint ethvalue) internal returns (bool){ (bool success, bytes memory data) = address(recipient).call{value: ethvalue}(""); return(success); } /// @notice /*~~~> DEV only function for withdrawing stuck funds sent to one of the proxy contracts. <~~~*/ /// @return Bool function withdrawEth(address recipient, uint ethvalue) external hasDevAdmin nonReentrant returns(bool){ require(sendEther(recipient, ethvalue)); return(true); } /*~~~> Fallback functions <~~~*/ event Received(address,uint); receive() external payable { emit Received(msg.sender, msg.value); } }
@notice~~~> @return Bool
Internal function for sending ether <~~~*/ function sendEther(address recipient, uint ethvalue) internal returns (bool){ return(success); }
1,324,459
[ 1, 7650, 98, 34, 327, 9166, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3186, 445, 364, 5431, 225, 2437, 203, 225, 411, 7650, 98, 5549, 203, 225, 445, 1366, 41, 1136, 12, 2867, 8027, 16, 2254, 13750, 1132, 13, 2713, 1135, 261, 6430, 15329, 203, 565, 327, 12, 4768, 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 ]
./full_match/100/0x2eBB30d1dcD64aEe62D2F8719457D909fE241B23/sources/SwaprERC20.sol
transfer TOKEN_Y tokens
uint256 tokenYAmount = (tokenXAmount * SWAP_RATIO) / 1e10;
14,268,947
[ 1, 13866, 14275, 67, 61, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 1147, 61, 6275, 273, 261, 2316, 60, 6275, 380, 16392, 2203, 67, 54, 789, 4294, 13, 342, 404, 73, 2163, 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 ]
./full_match/3/0xA7D4862d12371797dA656E97C0F3A090f1D11A15/sources/tam/vxx.sol
if True is this is a propsal that concerns a director, must use VoteDirectorOn_Off to specify (as below)
bool directorProposal;
14,244,844
[ 1, 430, 1053, 353, 333, 353, 279, 3458, 287, 716, 356, 2750, 2387, 279, 2657, 280, 16, 1297, 999, 27540, 28280, 1398, 67, 7210, 358, 4800, 261, 345, 5712, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1426, 2657, 280, 14592, 31, 21821, 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 ]
pragma solidity ^0.5.6; import '../common/UsingExternalStorage.sol'; import './GroupI.sol'; contract GroupLogic is UsingExternalStorage, GroupI { // Constants for hashing storage keys string constant GROUP_KEY = "COMMUNITY"; string constant MEMBER_KEY = "MEMBER"; string constant INVITATION_KEY = "INVITATION"; // Role constants; admin is default 1 uint8 constant admin = 1; uint8[] public roles; // TODO: in future, devise way for user to change expiration period uint expirationPeriod = 3 days; // Nonce mapping and sequence (groupId) mapping(address => bytes32) public temporaryInvitation; struct Commit { uint256 id; bytes32 commit; bytes sig; uint64 block; bool revealed; } // Ephemeral mapping for commit/reveal scheme for accepting invite mapping(address => Commit) public commits; // Enum for Invitation State enum InvitationState { Pending, Revoked, Accepted } InvitationState InvState; InvitationState constant defaultState = InvitationState.Pending; /** * addRoles * @dev Sets roles additional to admin (role 1) * @dev Roles are to be defined via documentation * @param _additionalRoles uint8 array of additional roles */ function addRoles( uint8[] memory _additionalRoles ) public onlyAdmin(4001) { roles = _additionalRoles; roles.push(admin); // add admin role by default for (uint i = 0; i < roles.length; i++) { storageContract.putBooleanValue( keccak256( abi.encodePacked( "ADDITIONAL_ROLES", roles[i] ) ), true ); } } /** * createGroup * @dev creates a group with sender as group creator and with highest permissions * @dev Reverts if neither params are provided * @dev Reverts if more than 10 invitations are attached * @param _sender msg.sender OR ecrecovered address from meta-tx * @param _metadataLocator IPFS hash for locating metadata * @param _secretHashes array of secretHashes to be added as members * @param _assignedRoles array of roles to be added as members * @return bool upon successful tx */ function createGroup( address _sender, bytes32 _metadataLocator, bytes32[] memory _secretHashes, uint8[] memory _assignedRoles ) internal returns (bool) { // require length of invites to be <= index 9 (10 total invs) require(_secretHashes.length <= 10, "there are more than 10 secret hashes"); require(_assignedRoles.length <= 10, "there are more than 10 roles"); require(_assignedRoles.length == _secretHashes.length, "roles and length not equal"); // groupId stored in external storage uint256 groupId = storageContract.getUintValue(keccak256( abi.encodePacked("groupId")) ); // set group to ENABLED storageContract.putBooleanValue(keccak256( abi.encodePacked(GROUP_KEY, groupId, "ENABLED")), true ); // set groupId as sequence (uint256) storageContract.putUintValue(keccak256( abi.encodePacked(GROUP_KEY, groupId, "groupStruct", "groupId")), groupId ); // set metadataLocator to group "struct" storageContract.putBytes32Value(keccak256( abi.encodePacked(GROUP_KEY, groupId, "groupStruct", "metadataLocator")), _metadataLocator ); // emit GroupCreated event emit GroupCreated(groupId, _sender, _metadataLocator); // set groupCreator as sender storageContract.putAddressValue(keccak256( abi.encodePacked(GROUP_KEY, groupId, "groupStruct", "groupCreator")), _sender ); // call addMember function to add sender as admin to newly created group addMember(_sender, groupId, admin); if(_secretHashes.length > 0) { storeBatchInvitation(_sender, groupId, _secretHashes, _assignedRoles); } // increment groupId storageContract.incrementUintValue(keccak256( abi.encodePacked("groupId")), 1 ); return true; } /** * addMember * @dev Creates a new member * @param _sender address of sender who originated group creation * @param _groupId from the sequence public uint256 (group id) * @param _role role (permissions level) address to be set to * @return bool when member is successfully added */ function addMember( address _sender, uint256 _groupId, uint8 _role ) internal returns (bool) { storageContract.putUintValue(keccak256( abi.encodePacked(MEMBER_KEY, _groupId, _sender)), _role ); // if _role is admin, increment adminCount if(_role == admin) { storageContract.incrementUintValue(keccak256( abi.encodePacked(GROUP_KEY, _groupId, "adminCount")), 1 ); } // emit Member Added event emit MemberAdded(_sender, _groupId, _role); } /** * removeMember * @dev logic function to remove member from group * @param _sender tx sender * @param _groupId group id to remove member from * @param _accountToRemove account to be removed * @return bool upon successful removal of member */ function removeMember( address _sender, uint256 _groupId, address _accountToRemove ) internal returns (bool) { // retrieving previous role to populate MemberRemoved event uint256 prevRole = storageContract.getUintValue(keccak256( abi.encodePacked(MEMBER_KEY, _groupId, _accountToRemove)) ); require(prevRole > 0, "account to remove is not a member of group"); // ensure sender is an admin of the group require(_accountToRemove == _sender || isAdmin(_groupId, _sender) == true, "account to remove not sender or sender not admin"); // check if accountToRemove is admin if(isAdmin(_groupId, _accountToRemove) == true) { // check that at least 2 admins remaining to prevent orphaning require(getAdminCount(_groupId) > 1, "user not an admin"); storageContract.decrementUintValue(keccak256( abi.encodePacked(GROUP_KEY, _groupId, "adminCount")), 1 ); } // now set member's role to 0 storageContract.putUintValue(keccak256( abi.encodePacked(MEMBER_KEY, _groupId, _accountToRemove)), 0 ); // emit Member Removed event emit MemberRemoved(_groupId, _accountToRemove, uint8(prevRole)); return true; } /** * changeMemberRole * @dev transaction function to change member role of a group * @param _sender tx sender * @param _groupId group id member belongs to * @param _accountToChange account being changed * @param _newRole new role for the member * @return bool upon successful transaction */ function changeMemberRole( address _sender, uint256 _groupId, address _accountToChange, uint8 _newRole ) internal returns (bool) { uint256 signerRole = storageContract.getUintValue( keccak256( abi.encodePacked( MEMBER_KEY, _groupId, _sender ) ) ); // ensure sender is an admin of the group require(uint8(signerRole) == admin); // only two roles at this point, admin and moderator // if admin is the account to change, then decrement // if moderator is the count to change, then increment if(isAdmin(_groupId, _accountToChange) == true) { require(getAdminCount(_groupId) > 1); storageContract.decrementUintValue(keccak256( abi.encodePacked(GROUP_KEY, _groupId, "adminCount")), 1 ); } else { storageContract.incrementUintValue(keccak256( abi.encodePacked(GROUP_KEY, _groupId, "adminCount")), 1 ); } // check if accountToChange belongs to the community isMember(_groupId, _accountToChange); // retrieving previous role to populate MemberRemoved event uint256 prevRole = storageContract.getUintValue(keccak256( abi.encodePacked(MEMBER_KEY, _groupId, _accountToChange)) ); // set member to new role storageContract.putUintValue(keccak256( abi.encodePacked(MEMBER_KEY, _groupId, _accountToChange)), _newRole ); // emit Member Role Changed event emit MemberRoleChanged( _groupId, _accountToChange, _newRole, uint8(prevRole)); return true; } /** * storeInvitation * @dev logic function to store invitation * @param _sender tx sender * @param _groupId group id user will be invited to * @param _role assigned role for the member * @param _secretHash hash generated by backend * @return bool upon successful transaction */ function storeInvitation( address _sender, uint256 _groupId, uint8 _role, bytes32 _secretHash ) internal returns (bool) { // require address storing invite is an admin require(isAdmin(_groupId, _sender) == true, "_sender is not an admin"); // require role to exist require(storageContract.getBooleanValue( keccak256( abi.encodePacked( "ADDITIONAL_ROLES", _role ) ) ) == true, "role does not exist"); // retrieve enable value from external storage bool enabled = storageContract.getBooleanValue(keccak256( abi.encodePacked(GROUP_KEY, _groupId, "ENABLED")) ); // require groupId to be enabled require(enabled == true, "group is not enabled"); // set recovered signer as _sender address storageContract.putAddressValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "SIGNER")), // msgHash from call to prepareInvitation() _sender ); // store secretHash so it can be checked later storageContract.putBytes32Value(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "SECRET_HASH")), _secretHash ); // set role storageContract.putUintValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "ROLE")), _role ); // set expiration date of 3 days storageContract.putUintValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "EXPIRATION_DATE")), now + expirationPeriod ); // put invitation into default state of pending storageContract.putUintValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "STATE")), uint(defaultState) ); // emit event emit InvitationPending(_groupId, _role, _secretHash); return true; } /** * storeBatchInvitation * @dev stores batches of invitations (up to 10) * @param _sender msg.sender OR ecrecovered address from meta-tx * @param _groupId identifier of the group id * @param _secretHashes array of secretHashes to be added as members * @param _assignedRoles array of roles to be added as members * @return bool upon successful tx */ function storeBatchInvitation( address _sender, uint256 _groupId, bytes32[] memory _secretHashes, uint8[] memory _assignedRoles ) internal returns (bool) { require(_secretHashes.length <= 10, "there are more than 10 secret hashes"); require(_assignedRoles.length <= 10, "there are more than 10 roles"); require(_assignedRoles.length == _secretHashes.length, "roles and length not equal"); // iterate through the additional invitations for (uint i = 0; i < _secretHashes.length; i++) { // call 'storeInvitation' with each individual invitation storeInvitation(_sender, _groupId, _assignedRoles[i], _secretHashes[i]); } } /** * revokeInvitation * @dev logic function to revoke pending invitation * @param _sender tx sender * @param _groupId group id to invite user to * @param _secretHash hash generated by backend * @return bool upon successful transaction */ function revokeInvitation( address _sender, uint256 _groupId, bytes32 _secretHash ) internal returns (bool) { uint256 signerRole = storageContract.getUintValue( keccak256( abi.encodePacked( MEMBER_KEY, _groupId, _sender ) ) ); // ensure sender is an admin of the group require(uint8(signerRole) == admin); // set invitation state to 'Revoked' storageContract.putUintValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "STATE")), uint(InvitationState.Revoked) ); // emit Invitation Revoked event emit InvitationRevoked(_groupId, uint8(signerRole), _secretHash); return true; } /** * acceptInvitationCommit * @dev logic function to perform commit for accepting invitation * @param _sender tx sender * @param _groupId group id to invite user to * @param _addressSecretHash hash of (secret + address) * @return bool upon successful transaction */ function acceptInvitationCommit( address _sender, uint256 _groupId, bytes32 _addressSecretHash ) internal returns (bool) { commits[_sender].id = _groupId; commits[_sender].commit = _addressSecretHash; commits[_sender].block = uint64(block.number); commits[_sender].revealed = false; emit AcceptCommitted(_groupId, _addressSecretHash); return true; } /** * acceptInvitationLogic * @dev logic function to accept invitation * @param _sender tx sender * @param _groupId group id of corresponding invite * @param _secret hash * @return bool upon successful transaction */ function acceptInvitationLogic( address _sender, uint256 _groupId, bytes32 _secret ) internal returns (bool) { // assign reference to ephemeral Commit struct Commit storage tempCommit = commits[_sender]; // retrieve secretHash bytes32 secretHash = storageContract.getBytes32Value(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, keccak256(abi.encodePacked(_secret)), "SECRET_HASH")) ); // retrieve expiration date from ext. storage uint expirationDate = storageContract.getUintValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, keccak256(abi.encodePacked(_secret)), "EXPIRATION_DATE")) ); // retrieve preset role for invited user from ext. storage uint role = storageContract.getUintValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, keccak256(abi.encodePacked(_secret)), "ROLE") )); //verify that hashed '_secret' == 'secretHash' require( keccak256(abi.encodePacked(_secret)) == secretHash, "hashed provided 'secret' does not match stored 'secretHash'" ); //verify that commit hash is for correct address' require( keccak256(abi.encodePacked(_secret, _sender)) == tempCommit.commit, "provided sender does not match sender address in commit signature" ); // require current block to be greater than block the commit was recorded require(block.number > tempCommit.block); // require current time to be before the expiration date require(block.timestamp < expirationDate); // require that temporary commit is not already revealed require(!tempCommit.revealed); // then set to revealed tempCommit.revealed = true; // implicit conversion from uint256 -> uint8 for 'role' addMember(_sender, _groupId, uint8(role)); return true; } /////////////////////////////////////////////////////////////////////// // UTILS /////////////////////////////////////////////////////////////////////// /** * getRole * @dev helper function to retrieve user role * @param _groupId groupId to retrieve role from * @param _addr address of user within group * @return uint256 role of user */ function getRole( uint256 _groupId, address _addr ) public view returns (uint256) { return storageContract.getUintValue(keccak256( abi.encodePacked(MEMBER_KEY, _groupId, _addr)) ); } /** * isAdmin * @dev helper function to check if user is admin * @param _groupId groupId to perform admin check on * @param _addr address of proposed admin check * @return bool if address is an admin of provided group */ function isAdmin( uint256 _groupId, address _addr ) public view returns (bool) { if(storageContract.getUintValue(keccak256( abi.encodePacked(MEMBER_KEY, _groupId, _addr))) == 1) { return true; } else { return false; } } /** * isMember * @dev helper function to check if user is member of provided group * @param _groupId groupId to perform member check on * @param _addr address of proposed member check * @return bool if address is a member of provided group */ function isMember( uint256 _groupId, address _addr ) public view returns (bool) { require(storageContract.getUintValue(keccak256( abi.encodePacked(MEMBER_KEY, _groupId, _addr)) ) > 0); return true; } /** * getInvitationState * @dev helper function to check what state invitation is in * @dev 0 = Pending, 1 = Revoked, 2 = Accepted * @param _groupId groupId to perform member check on * @param _secretHash hash of invitation * @return uint state of invitation */ function getInvitationState( uint256 _groupId, bytes32 _secretHash ) public view returns (uint) { return storageContract.getUintValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "STATE")) ); } /** * getAdminCount * @dev helper function to check number of admins of individual group * @param _groupId groupId to perform admin count check on * @return uint256 number of admins of specified group */ function getAdminCount( uint256 _groupId ) public view returns (uint256) { return storageContract.getUintValue(keccak256( abi.encodePacked(GROUP_KEY, _groupId, "adminCount")) ); } }
require address storing invite is an admin require role to exist retrieve enable value from external storage require groupId to be enabled set recovered signer as _sender address msgHash from call to prepareInvitation() store secretHash so it can be checked later set role set expiration date of 3 days put invitation into default state of pending emit event
function storeInvitation( address _sender, uint256 _groupId, uint8 _role, bytes32 _secretHash ) internal returns (bool) { require(isAdmin(_groupId, _sender) == true, "_sender is not an admin"); require(storageContract.getBooleanValue( keccak256( abi.encodePacked( "ADDITIONAL_ROLES", _role ) ) ) == true, "role does not exist"); bool enabled = storageContract.getBooleanValue(keccak256( abi.encodePacked(GROUP_KEY, _groupId, "ENABLED")) ); require(enabled == true, "group is not enabled"); storageContract.putAddressValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "SIGNER")), _sender ); storageContract.putBytes32Value(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "SECRET_HASH")), _secretHash ); storageContract.putUintValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "ROLE")), _role ); storageContract.putUintValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "EXPIRATION_DATE")), now + expirationPeriod ); storageContract.putUintValue(keccak256( abi.encodePacked(INVITATION_KEY, _groupId, _secretHash, "STATE")), uint(defaultState) ); emit InvitationPending(_groupId, _role, _secretHash); return true; }
13,100,605
[ 1, 6528, 1758, 15729, 19035, 353, 392, 3981, 2583, 2478, 358, 1005, 4614, 4237, 460, 628, 3903, 2502, 2583, 6612, 358, 506, 3696, 444, 24616, 10363, 487, 389, 15330, 1758, 1234, 2310, 628, 745, 358, 2911, 19896, 1435, 1707, 4001, 2310, 1427, 518, 848, 506, 5950, 5137, 444, 2478, 444, 7686, 1509, 434, 890, 4681, 1378, 26441, 1368, 805, 919, 434, 4634, 3626, 871, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1707, 19896, 12, 203, 3639, 1758, 389, 15330, 16, 203, 3639, 2254, 5034, 389, 27547, 16, 203, 3639, 2254, 28, 282, 389, 4615, 16, 203, 3639, 1731, 1578, 389, 5875, 2310, 203, 565, 262, 203, 3639, 2713, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 291, 4446, 24899, 27547, 16, 389, 15330, 13, 422, 638, 16, 4192, 15330, 353, 486, 392, 3981, 8863, 203, 203, 3639, 2583, 12, 5697, 8924, 18, 588, 5507, 620, 12, 203, 7734, 417, 24410, 581, 5034, 12, 203, 10792, 24126, 18, 3015, 4420, 329, 12, 203, 13491, 315, 8355, 30525, 67, 30797, 3113, 203, 13491, 389, 4615, 203, 10792, 262, 203, 7734, 262, 203, 5411, 262, 422, 638, 16, 315, 4615, 1552, 486, 1005, 8863, 203, 203, 3639, 1426, 3696, 273, 2502, 8924, 18, 588, 5507, 620, 12, 79, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 8468, 67, 3297, 16, 389, 27547, 16, 315, 13560, 6, 3719, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 5745, 422, 638, 16, 315, 1655, 353, 486, 3696, 8863, 203, 203, 3639, 2502, 8924, 18, 458, 1887, 620, 12, 79, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 706, 58, 1285, 2689, 67, 3297, 16, 389, 27547, 16, 389, 5875, 2310, 16, 315, 11260, 654, 7923, 3631, 203, 5411, 389, 15330, 203, 3639, 11272, 203, 203, 3639, 2502, 8924, 18, 458, 2160, 1578, 620, 12, 79, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 2 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC20Metadata.sol"; import "@yield-protocol/utils-v2/contracts/token/ERC20Permit.sol"; import "@yield-protocol/utils-v2/contracts/token/SafeERC20Namer.sol"; import "@yield-protocol/utils-v2/contracts/token/MinimalTransferHelper.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U112.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256I256.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU128U112.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU128I128.sol"; import "@yield-protocol/yieldspace-interfaces/IPool.sol"; import "@yield-protocol/yieldspace-interfaces/IPoolFactory.sol"; import "@yield-protocol/vault-interfaces/IFYToken.sol"; import "./YieldMath.sol"; /// @dev The Pool contract exchanges base for fyToken at a price defined by a specific formula. contract Pool is IPool, ERC20Permit { using CastU256U128 for uint256; using CastU256U112 for uint256; using CastU256I256 for uint256; using CastU128U112 for uint128; using CastU128I128 for uint128; using MinimalTransferHelper for IERC20; event Trade(uint32 maturity, address indexed from, address indexed to, int256 bases, int256 fyTokens); event Liquidity(uint32 maturity, address indexed from, address indexed to, address indexed fyTokenTo, int256 bases, int256 fyTokens, int256 poolTokens); event Sync(uint112 baseCached, uint112 fyTokenCached, uint256 cumulativeBalancesRatio); int128 public immutable override ts; // 1 / Seconds in 10 years, in 64.64 int128 public immutable override g1; // To be used when selling base to the pool int128 public immutable override g2; // To be used when selling fyToken to the pool uint32 public immutable override maturity; uint96 public immutable override scaleFactor; // Scale up to 18 low decimal tokens to get the right precision in YieldMath IERC20 public immutable override base; IFYToken public immutable override fyToken; uint112 private baseCached; // uses single storage slot, accessible via getCache uint112 private fyTokenCached; // uses single storage slot, accessible via getCache uint32 private blockTimestampLast; // uses single storage slot, accessible via getCache uint256 public cumulativeBalancesRatio; // Fixed point factor with 27 decimals (ray) constructor() ERC20Permit( string(abi.encodePacked("Yield ", SafeERC20Namer.tokenName(IPoolFactory(msg.sender).nextFYToken()), " LP Token")), string(abi.encodePacked(SafeERC20Namer.tokenSymbol(IPoolFactory(msg.sender).nextFYToken()), "LP")), SafeERC20Namer.tokenDecimals(IPoolFactory(msg.sender).nextBase()) ) { IPoolFactory _factory = IPoolFactory(msg.sender); IFYToken _fyToken = IFYToken(_factory.nextFYToken()); IERC20 _base = IERC20(_factory.nextBase()); fyToken = _fyToken; base = _base; uint256 _maturity = _fyToken.maturity(); require (_maturity <= type(uint32).max, "Pool: Maturity too far in the future"); maturity = uint32(_maturity); ts = _factory.ts(); g1 = _factory.g1(); g2 = _factory.g2(); scaleFactor = uint96(10 ** (18 - SafeERC20Namer.tokenDecimals(address(_base)))); } /// @dev Trading can only be done before maturity modifier beforeMaturity() { require( block.timestamp < maturity, "Pool: Too late" ); _; } // ---- Balances management ---- /// @dev Updates the cache to match the actual balances. function sync() external { _update(_getBaseBalance(), _getFYTokenBalance(), baseCached, fyTokenCached); } /// @dev Returns the cached balances & last updated timestamp. /// @return Cached base token balance. /// @return Cached virtual FY token balance. /// @return Timestamp that balances were last cached. function getCache() external view override returns (uint112, uint112, uint32) { return (baseCached, fyTokenCached, blockTimestampLast); } /// @dev Returns the "virtual" fyToken balance, which is the real balance plus the pool token supply. function getFYTokenBalance() public view override returns(uint112) { return _getFYTokenBalance(); } /// @dev Returns the base balance function getBaseBalance() public view override returns(uint112) { return _getBaseBalance(); } /// @dev Returns the "virtual" fyToken balance, which is the real balance plus the pool token supply. function _getFYTokenBalance() internal view returns(uint112) { return (fyToken.balanceOf(address(this)) + _totalSupply).u112(); } /// @dev Returns the base balance function _getBaseBalance() internal view returns(uint112) { return base.balanceOf(address(this)).u112(); } /// @dev Retrieve any base tokens not accounted for in the cache function retrieveBase(address to) external override returns(uint128 retrieved) { retrieved = _getBaseBalance() - baseCached; // Cache can never be above balances base.safeTransfer(to, retrieved); // Now the current balances match the cache, so no need to update the TWAR } /// @dev Retrieve any fyTokens not accounted for in the cache function retrieveFYToken(address to) external override returns(uint128 retrieved) { retrieved = _getFYTokenBalance() - fyTokenCached; // Cache can never be above balances IERC20(address(fyToken)).safeTransfer(to, retrieved); // Now the balances match the cache, so no need to update the TWAR } /// @dev Update cache and, on the first call per block, ratio accumulators function _update(uint128 baseBalance, uint128 fyBalance, uint112 _baseCached, uint112 _fyTokenCached) private { uint32 blockTimestamp = uint32(block.timestamp); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _baseCached != 0 && _fyTokenCached != 0) { // We multiply by 1e27 here so that r = t * y/x is a fixed point factor with 27 decimals uint256 scaledFYTokenCached = uint256(_fyTokenCached) * 1e27; cumulativeBalancesRatio += scaledFYTokenCached * timeElapsed / _baseCached; } baseCached = baseBalance.u112(); fyTokenCached = fyBalance.u112(); blockTimestampLast = blockTimestamp; emit Sync(baseCached, fyTokenCached, cumulativeBalancesRatio); } // ---- Liquidity ---- /// @dev Mint liquidity tokens in exchange for adding base and fyToken /// The amount of liquidity tokens to mint is calculated from the amount of unaccounted for fyToken in this contract. /// A proportional amount of base tokens need to be present in this contract, also unaccounted for. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any surplus base. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Maximum ratio of base to fyToken in the pool. /// @return The amount of liquidity tokens minted. function mint(address to, address remainder, uint256 minRatio, uint256 maxRatio) external override returns (uint256, uint256, uint256) { return _mintInternal(to, remainder, 0, minRatio, maxRatio); } /// @dev Mint liquidity tokens in exchange for adding only base /// The amount of liquidity tokens is calculated from the amount of fyToken to buy from the pool, /// plus the amount of unaccounted for fyToken in this contract. /// The base tokens need to be present in this contract, unaccounted for. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any surplus base. /// @param fyTokenToBuy Amount of `fyToken` being bought in the Pool, from this we calculate how much base it will be taken in. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Maximum ratio of base to fyToken in the pool. /// @return The amount of liquidity tokens minted. function mintWithBase(address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio) external override returns (uint256, uint256, uint256) { return _mintInternal(to, remainder, fyTokenToBuy, minRatio, maxRatio); } /// @dev Mint liquidity tokens, with an optional internal trade to buy fyToken beforehand. /// The amount of liquidity tokens is calculated from the amount of fyToken to buy from the pool, /// plus the amount of unaccounted for fyToken in this contract. /// The base tokens need to be present in this contract, unaccounted for. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any surplus base. /// @param fyTokenToBuy Amount of `fyToken` being bought in the Pool, from this we calculate how much base it will be taken in. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Minimum ratio of base to fyToken in the pool. function _mintInternal(address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio) internal returns (uint256 baseIn, uint256 fyTokenIn, uint256 tokensMinted) { // Gather data uint256 supply = _totalSupply; (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint256 _realFYTokenCached = _fyTokenCached - supply; // The fyToken cache includes the virtual fyToken, equal to the supply uint256 baseBalance = base.balanceOf(address(this)); uint256 fyTokenBalance = fyToken.balanceOf(address(this)); uint256 baseAvailable = baseBalance - _baseCached; // Check the burn wasn't sandwiched require ( _realFYTokenCached == 0 || ( uint256(_baseCached) * 1e18 / _realFYTokenCached >= minRatio && uint256(_baseCached) * 1e18 / _realFYTokenCached <= maxRatio ), "Pool: Reserves ratio changed" ); // Calculate token amounts if (supply == 0) { // Initialize at 1 pool token minted per base token supplied baseIn = baseAvailable; tokensMinted = baseIn; } else if (_realFYTokenCached == 0) { // Edge case, no fyToken in the Pool after initialization baseIn = baseAvailable; tokensMinted = supply * baseIn / _baseCached; } else { // There is an optional virtual trade before the mint uint256 baseToSell; if (fyTokenToBuy > 0) { baseToSell = _buyFYTokenPreview( fyTokenToBuy.u128(), _baseCached, _fyTokenCached ); } // We use all the available fyTokens, plus a virtual trade if it happened, surplus is in base tokens fyTokenIn = fyTokenBalance - _realFYTokenCached; tokensMinted = (supply * (fyTokenToBuy + fyTokenIn)) / (_realFYTokenCached - fyTokenToBuy); baseIn = baseToSell + ((_baseCached + baseToSell) * tokensMinted) / supply; require(baseAvailable >= baseIn, "Pool: Not enough base token in"); } // Update TWAR _update( (_baseCached + baseIn).u128(), (_fyTokenCached + fyTokenIn + tokensMinted).u128(), // Account for the "virtual" fyToken from the new minted LP tokens _baseCached, _fyTokenCached ); // Execute mint _mint(to, tokensMinted); // Return any unused base if (baseAvailable - baseIn > 0) base.safeTransfer(remainder, baseAvailable - baseIn); emit Liquidity(maturity, msg.sender, to, address(0), -(baseIn.i256()), -(fyTokenIn.i256()), tokensMinted.i256()); } /// @dev Burn liquidity tokens in exchange for base and fyToken. /// The liquidity tokens need to be in this contract. /// @param baseTo Wallet receiving the base. /// @param fyTokenTo Wallet receiving the fyToken. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Maximum ratio of base to fyToken in the pool. /// @return The amount of tokens burned and returned (tokensBurned, bases, fyTokens). function burn(address baseTo, address fyTokenTo, uint256 minRatio, uint256 maxRatio) external override returns (uint256, uint256, uint256) { return _burnInternal(baseTo, fyTokenTo, false, minRatio, maxRatio); } /// @dev Burn liquidity tokens in exchange for base. /// The liquidity provider needs to have called `pool.approve`. /// @param to Wallet receiving the base and fyToken. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Minimum ratio of base to fyToken in the pool. /// @return tokensBurned The amount of lp tokens burned. /// @return baseOut The amount of base tokens returned. function burnForBase(address to, uint256 minRatio, uint256 maxRatio) external override returns (uint256 tokensBurned, uint256 baseOut) { (tokensBurned, baseOut, ) = _burnInternal(to, address(0), true, minRatio, maxRatio); } /// @dev Burn liquidity tokens in exchange for base. /// The liquidity provider needs to have called `pool.approve`. /// @param baseTo Wallet receiving the base. /// @param fyTokenTo Wallet receiving the fyToken. /// @param tradeToBase Whether the resulting fyToken should be traded for base tokens. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Minimum ratio of base to fyToken in the pool. /// @return tokensBurned The amount of pool tokens burned. /// @return tokenOut The amount of base tokens returned. /// @return fyTokenOut The amount of fyTokens returned. function _burnInternal(address baseTo, address fyTokenTo, bool tradeToBase, uint256 minRatio, uint256 maxRatio) internal returns (uint256 tokensBurned, uint256 tokenOut, uint256 fyTokenOut) { // Gather data tokensBurned = _balanceOf[address(this)]; uint256 supply = _totalSupply; (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint256 _realFYTokenCached = _fyTokenCached - supply; // The fyToken cache includes the virtual fyToken, equal to the supply // Check the burn wasn't sandwiched require ( _realFYTokenCached == 0 || ( uint256(_baseCached) * 1e18 / _realFYTokenCached >= minRatio && uint256(_baseCached) * 1e18 / _realFYTokenCached <= maxRatio ), "Pool: Reserves ratio changed" ); // Calculate trade tokenOut = (tokensBurned * _baseCached) / supply; fyTokenOut = (tokensBurned * _realFYTokenCached) / supply; if (tradeToBase) { tokenOut += YieldMath.baseOutForFYTokenIn( // This is a virtual sell (_baseCached - tokenOut.u128()) * scaleFactor, // Cache, minus virtual burn (_fyTokenCached - fyTokenOut.u128()) * scaleFactor, // Cache, minus virtual burn fyTokenOut.u128() * scaleFactor, // Sell the virtual fyToken obtained maturity - uint32(block.timestamp), // This can't be called after maturity ts, g2 ) / scaleFactor; fyTokenOut = 0; } // Update TWAR _update( (_baseCached - tokenOut).u128(), (_fyTokenCached - fyTokenOut - tokensBurned).u128(), _baseCached, _fyTokenCached ); // Transfer assets _burn(address(this), tokensBurned); base.safeTransfer(baseTo, tokenOut); if (fyTokenOut > 0) IERC20(address(fyToken)).safeTransfer(fyTokenTo, fyTokenOut); emit Liquidity(maturity, msg.sender, baseTo, fyTokenTo, tokenOut.i256(), fyTokenOut.i256(), -(tokensBurned.i256())); } // ---- Trading ---- /// @dev Sell base for fyToken. /// The trader needs to have transferred the amount of base to sell to the pool before in the same transaction. /// @param to Wallet receiving the fyToken being bought /// @param min Minimm accepted amount of fyToken /// @return Amount of fyToken that will be deposited on `to` wallet function sellBase(address to, uint128 min) external override returns(uint128) { // Calculate trade (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint112 _baseBalance = _getBaseBalance(); uint112 _fyTokenBalance = _getFYTokenBalance(); uint128 baseIn = _baseBalance - _baseCached; uint128 fyTokenOut = _sellBasePreview( baseIn, _baseCached, _fyTokenBalance ); // Slippage check require( fyTokenOut >= min, "Pool: Not enough fyToken obtained" ); // Update TWAR _update( _baseBalance, _fyTokenBalance - fyTokenOut, _baseCached, _fyTokenCached ); // Transfer assets IERC20(address(fyToken)).safeTransfer(to, fyTokenOut); emit Trade(maturity, msg.sender, to, -(baseIn.i128()), fyTokenOut.i128()); return fyTokenOut; } /// @dev Returns how much fyToken would be obtained by selling `baseIn` base /// @param baseIn Amount of base hypothetically sold. /// @return Amount of fyToken hypothetically bought. function sellBasePreview(uint128 baseIn) external view override returns(uint128) { (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); return _sellBasePreview(baseIn, _baseCached, _fyTokenCached); } /// @dev Returns how much fyToken would be obtained by selling `baseIn` base function _sellBasePreview( uint128 baseIn, uint112 baseBalance, uint112 fyTokenBalance ) private view beforeMaturity returns(uint128) { uint128 fyTokenOut = YieldMath.fyTokenOutForBaseIn( baseBalance * scaleFactor, fyTokenBalance * scaleFactor, baseIn * scaleFactor, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g1 ) / scaleFactor; require( fyTokenBalance - fyTokenOut >= baseBalance + baseIn, "Pool: fyToken balance too low" ); return fyTokenOut; } /// @dev Buy base for fyToken /// The trader needs to have called `fyToken.approve` /// @param to Wallet receiving the base being bought /// @param tokenOut Amount of base being bought that will be deposited in `to` wallet /// @param max Maximum amount of fyToken that will be paid for the trade /// @return Amount of fyToken that will be taken from caller function buyBase(address to, uint128 tokenOut, uint128 max) external override returns(uint128) { // Calculate trade uint128 fyTokenBalance = _getFYTokenBalance(); (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint128 fyTokenIn = _buyBasePreview( tokenOut, _baseCached, _fyTokenCached ); require( fyTokenBalance - _fyTokenCached >= fyTokenIn, "Pool: Not enough fyToken in" ); // Slippage check require( fyTokenIn <= max, "Pool: Too much fyToken in" ); // Update TWAR _update( _baseCached - tokenOut, _fyTokenCached + fyTokenIn, _baseCached, _fyTokenCached ); // Transfer assets base.safeTransfer(to, tokenOut); emit Trade(maturity, msg.sender, to, tokenOut.i128(), -(fyTokenIn.i128())); return fyTokenIn; } /// @dev Returns how much fyToken would be required to buy `tokenOut` base. /// @param tokenOut Amount of base hypothetically desired. /// @return Amount of fyToken hypothetically required. function buyBasePreview(uint128 tokenOut) external view override returns(uint128) { (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); return _buyBasePreview(tokenOut, _baseCached, _fyTokenCached); } /// @dev Returns how much fyToken would be required to buy `tokenOut` base. function _buyBasePreview( uint128 tokenOut, uint112 baseBalance, uint112 fyTokenBalance ) private view beforeMaturity returns(uint128) { return YieldMath.fyTokenInForBaseOut( baseBalance * scaleFactor, fyTokenBalance * scaleFactor, tokenOut * scaleFactor, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g2 ) / scaleFactor; } /// @dev Sell fyToken for base /// The trader needs to have transferred the amount of fyToken to sell to the pool before in the same transaction. /// @param to Wallet receiving the base being bought /// @param min Minimm accepted amount of base /// @return Amount of base that will be deposited on `to` wallet function sellFYToken(address to, uint128 min) external override returns(uint128) { // Calculate trade (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint112 _fyTokenBalance = _getFYTokenBalance(); uint112 _baseBalance = _getBaseBalance(); uint128 fyTokenIn = _fyTokenBalance - _fyTokenCached; uint128 baseOut = _sellFYTokenPreview( fyTokenIn, _baseCached, _fyTokenCached ); // Slippage check require( baseOut >= min, "Pool: Not enough base obtained" ); // Update TWAR _update( _baseBalance - baseOut, _fyTokenBalance, _baseCached, _fyTokenCached ); // Transfer assets base.safeTransfer(to, baseOut); emit Trade(maturity, msg.sender, to, baseOut.i128(), -(fyTokenIn.i128())); return baseOut; } /// @dev Returns how much base would be obtained by selling `fyTokenIn` fyToken. /// @param fyTokenIn Amount of fyToken hypothetically sold. /// @return Amount of base hypothetically bought. function sellFYTokenPreview(uint128 fyTokenIn) external view override returns(uint128) { (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); return _sellFYTokenPreview(fyTokenIn, _baseCached, _fyTokenCached); } /// @dev Returns how much base would be obtained by selling `fyTokenIn` fyToken. function _sellFYTokenPreview( uint128 fyTokenIn, uint112 baseBalance, uint112 fyTokenBalance ) private view beforeMaturity returns(uint128) { return YieldMath.baseOutForFYTokenIn( baseBalance * scaleFactor, fyTokenBalance * scaleFactor, fyTokenIn * scaleFactor, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g2 ) / scaleFactor; } /// @dev Buy fyToken for base /// The trader needs to have called `base.approve` /// @param to Wallet receiving the fyToken being bought /// @param fyTokenOut Amount of fyToken being bought that will be deposited in `to` wallet /// @param max Maximum amount of base token that will be paid for the trade /// @return Amount of base that will be taken from caller's wallet function buyFYToken(address to, uint128 fyTokenOut, uint128 max) external override returns(uint128) { // Calculate trade uint128 baseBalance = _getBaseBalance(); (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint128 baseIn = _buyFYTokenPreview( fyTokenOut, _baseCached, _fyTokenCached ); require( baseBalance - _baseCached >= baseIn, "Pool: Not enough base token in" ); // Slippage check require( baseIn <= max, "Pool: Too much base token in" ); // Update TWAR _update( _baseCached + baseIn, _fyTokenCached - fyTokenOut, _baseCached, _fyTokenCached ); // Transfer assets IERC20(address(fyToken)).safeTransfer(to, fyTokenOut); emit Trade(maturity, msg.sender, to, -(baseIn.i128()), fyTokenOut.i128()); return baseIn; } /// @dev Returns how much base would be required to buy `fyTokenOut` fyToken. /// @param fyTokenOut Amount of fyToken hypothetically desired. /// @return Amount of base hypothetically required. function buyFYTokenPreview(uint128 fyTokenOut) external view override returns(uint128) { (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); return _buyFYTokenPreview(fyTokenOut, _baseCached, _fyTokenCached); } /// @dev Returns how much base would be required to buy `fyTokenOut` fyToken. function _buyFYTokenPreview( uint128 fyTokenOut, uint128 baseBalance, uint128 fyTokenBalance ) private view beforeMaturity returns(uint128) { uint128 baseIn = YieldMath.baseInForFYTokenOut( baseBalance * scaleFactor, fyTokenBalance * scaleFactor, fyTokenOut * scaleFactor, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g1 ) / scaleFactor; require( fyTokenBalance - fyTokenOut >= baseBalance + baseIn, "Pool: fyToken balance too low" ); return baseIn; } } // 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 // Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; import "./IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ 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 // Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/53516bc555a454862470e7860a9b5254db4d00f5/contracts/token/ERC20/ERC20Permit.sol pragma solidity ^0.8.0; import "./ERC20.sol"; import "./IERC2612.sol"; /** * @dev Extension of {ERC20} that allows token holders to use their tokens * without sending any transactions by setting {IERC20-allowance} with a * signature using the {permit} method, and then spend them via * {IERC20-transferFrom}. * * The {permit} signature mechanism conforms to the {IERC2612} interface. */ abstract contract ERC20Permit is ERC20, IERC2612 { mapping (address => uint256) public override nonces; bytes32 public immutable PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private immutable _DOMAIN_SEPARATOR; uint256 public immutable deploymentChainId; constructor(string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_, decimals_) { deploymentChainId = block.chainid; _DOMAIN_SEPARATOR = _calculateDomainSeparator(block.chainid); } /// @dev Calculate the DOMAIN_SEPARATOR. function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version())), chainId, address(this) ) ); } /// @dev Return the DOMAIN_SEPARATOR. function DOMAIN_SEPARATOR() external view returns (bytes32) { return block.chainid == deploymentChainId ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(block.chainid); } /// @dev Setting the version as a function so that it can be overriden function version() public pure virtual returns(string memory) { return "1"; } /** * @dev See {IERC2612-permit}. * * In cases where the free option is not a concern, deadline can simply be * set to uint(-1), so it should be seen as an optional parameter */ function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external virtual override { require(deadline >= block.timestamp, "ERC20Permit: expired deadline"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline ) ); bytes32 hash = keccak256( abi.encodePacked( "\x19\x01", block.chainid == deploymentChainId ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(block.chainid), hashStruct ) ); address signer = ecrecover(hash, v, r, s); require( signer != address(0) && signer == owner, "ERC20Permit: invalid signature" ); _setAllowance(owner, spender, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "../token/IERC20Metadata.sol"; import "../utils/AddressStringUtil.sol"; // produces token descriptors from inconsistent or absent ERC20 symbol implementations that can return string or bytes32 // this library will always produce a string symbol to represent the token library SafeERC20Namer { function bytes32ToString(bytes32 x) private pure returns (string memory) { bytes memory bytesString = new bytes(32); uint256 charCount = 0; for (uint256 j = 0; j < 32; j++) { bytes1 char = x[j]; if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint256 j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } // assumes the data is in position 2 function parseStringData(bytes memory b) private pure returns (string memory) { uint256 charCount = 0; // first parse the charCount out of the data for (uint256 i = 32; i < 64; i++) { charCount <<= 8; charCount += uint8(b[i]); } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint256 i = 0; i < charCount; i++) { bytesStringTrimmed[i] = b[i + 64]; } return string(bytesStringTrimmed); } // uses a heuristic to produce a token name from the address // the heuristic returns the full hex of the address string in upper case function addressToName(address token) private pure returns (string memory) { return AddressStringUtil.toAsciiString(token, 40); } // uses a heuristic to produce a token symbol from the address // the heuristic returns the first 6 hex of the address string in upper case function addressToSymbol(address token) private pure returns (string memory) { return AddressStringUtil.toAsciiString(token, 6); } // calls an external view token contract method that returns a symbol or name, and parses the output into a string function callAndParseStringReturn(address token, bytes4 selector) private view returns (string memory) { (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(selector)); // if not implemented, or returns empty data, return empty string if (!success || data.length == 0) { return ""; } // bytes32 data always has length 32 if (data.length == 32) { bytes32 decoded = abi.decode(data, (bytes32)); return bytes32ToString(decoded); } else if (data.length > 64) { return abi.decode(data, (string)); } return ""; } // attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address function tokenSymbol(address token) public view returns (string memory) { string memory symbol = callAndParseStringReturn(token, IERC20Metadata.symbol.selector); if (bytes(symbol).length == 0) { // fallback to 6 uppercase hex of address return addressToSymbol(token); } return symbol; } // attempts to extract the token name. if it does not implement name, returns a name derived from the address function tokenName(address token) public view returns (string memory) { string memory name = callAndParseStringReturn(token, IERC20Metadata.name.selector); if (bytes(name).length == 0) { // fallback to full hex of address return addressToName(token); } return name; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function tokenDecimals(address token) public view returns (uint8) { (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(IERC20Metadata.decimals.selector)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } } // SPDX-License-Identifier: MIT // Taken from https://github.com/Uniswap/uniswap-lib/blob/master/contracts/libraries/TransferHelper.sol pragma solidity >=0.6.0; import "./IERC20.sol"; import "../utils/RevertMsgExtractor.sol"; // helper methods for transferring ERC20 tokens that do not consistently return true/false library MinimalTransferHelper { /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with the underlying revert message if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( IERC20 token, address to, uint256 value ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); if (!(success && (data.length == 0 || abi.decode(data, (bool))))) revert(RevertMsgExtractor.getRevertMsg(data)); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU256U128 { /// @dev Safely cast an uint256 to an uint128 function u128(uint256 x) internal pure returns (uint128 y) { require (x <= type(uint128).max, "Cast overflow"); y = uint128(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU256U112 { /// @dev Safely cast an uint256 to an uint112 function u112(uint256 x) internal pure returns (uint112 y) { require (x <= type(uint112).max, "Cast overflow"); y = uint112(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU256I256 { /// @dev Safely cast an uint256 to an int256 function i256(uint256 x) internal pure returns (int256 y) { require (x <= uint256(type(int256).max), "Cast overflow"); y = int256(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU128U112 { /// @dev Safely cast an uint128 to an uint112 function u112(uint128 x) internal pure returns (uint112 y) { require (x <= uint128(type(uint112).max), "Cast overflow"); y = uint112(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU128I128 { /// @dev Safely cast an uint128 to an int128 function i128(uint128 x) internal pure returns (int128 y) { require (x <= uint128(type(int128).max), "Cast overflow"); y = int128(x); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.8.0; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC2612.sol"; import "@yield-protocol/vault-interfaces/IFYToken.sol"; interface IPool is IERC20, IERC2612 { function ts() external view returns(int128); function g1() external view returns(int128); function g2() external view returns(int128); function maturity() external view returns(uint32); function scaleFactor() external view returns(uint96); function getCache() external view returns (uint112, uint112, uint32); function base() external view returns(IERC20); function fyToken() external view returns(IFYToken); function getBaseBalance() external view returns(uint112); function getFYTokenBalance() external view returns(uint112); function retrieveBase(address to) external returns(uint128 retrieved); function retrieveFYToken(address to) external returns(uint128 retrieved); function sellBase(address to, uint128 min) external returns(uint128); function buyBase(address to, uint128 baseOut, uint128 max) external returns(uint128); function sellFYToken(address to, uint128 min) external returns(uint128); function buyFYToken(address to, uint128 fyTokenOut, uint128 max) external returns(uint128); function sellBasePreview(uint128 baseIn) external view returns(uint128); function buyBasePreview(uint128 baseOut) external view returns(uint128); function sellFYTokenPreview(uint128 fyTokenIn) external view returns(uint128); function buyFYTokenPreview(uint128 fyTokenOut) external view returns(uint128); function mint(address to, address remainder, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256); function mintWithBase(address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256); function burn(address baseTo, address fyTokenTo, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256); function burnForBase(address to, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IPoolFactory { event PoolCreated(address indexed base, address indexed fyToken, address pool); function POOL_BYTECODE_HASH() external pure returns (bytes32); function calculatePoolAddress(address base, address fyToken) external view returns (address); function getPool(address base, address fyToken) external view returns (address); function createPool(address base, address fyToken) external returns (address); function nextBase() external view returns (address); function nextFYToken() external view returns (address); function ts() external view returns (int128); function g1() external view returns (int128); function g2() external view returns (int128); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; interface IFYToken is IERC20 { /// @dev Asset that is returned on redemption. function underlying() external view returns (address); /// @dev Unix time at which redemption of fyToken for underlying are possible function maturity() external view returns (uint256); /// @dev Record price data at maturity function mature() external; /// @dev Mint fyToken providing an equal amount of underlying to the protocol function mintWithUnderlying(address to, uint256 amount) external; /// @dev Burn fyToken after maturity for an amount of underlying. function redeem(address to, uint256 amount) external returns (uint256); /// @dev Mint fyToken. /// This function can only be called by other Yield contracts, not users directly. /// @param to Wallet to mint the fyToken in. /// @param fyTokenAmount Amount of fyToken to mint. function mint(address to, uint256 fyTokenAmount) external; /// @dev Burn fyToken. /// This function can only be called by other Yield contracts, not users directly. /// @param from Wallet to burn the fyToken from. /// @param fyTokenAmount Amount of fyToken to burn. function burn(address from, uint256 fyTokenAmount) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "./Math64x64.sol"; library Exp64x64 { /** * Raise given number x into power specified as a simple fraction y/z and then * multiply the result by the normalization factor 2^(128 * (1 - y/z)). * Revert if z is zero, or if both x and y are zeros. * * @param x number to raise into given power y/z * @param y numerator of the power to raise x into * @param z denominator of the power to raise x into * @return x raised into power y/z and then multiplied by 2^(128 * (1 - y/z)) */ function pow(uint128 x, uint128 y, uint128 z) internal pure returns(uint128) { unchecked { require(z != 0); if(x == 0) { require(y != 0); return 0; } else { uint256 l = uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - log_2(x)) * y / z; if(l > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) return 0; else return pow_2(uint128(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - l)); } } } /** * Calculate base 2 logarithm of an unsigned 128-bit integer number. Revert * in case x is zero. * * @param x number to calculate base 2 logarithm of * @return base 2 logarithm of x, multiplied by 2^121 */ function log_2(uint128 x) internal pure returns(uint128) { unchecked { require(x != 0); uint b = x; uint l = 0xFE000000000000000000000000000000; if(b < 0x10000000000000000) {l -= 0x80000000000000000000000000000000; b <<= 64;} if(b < 0x1000000000000000000000000) {l -= 0x40000000000000000000000000000000; b <<= 32;} if(b < 0x10000000000000000000000000000) {l -= 0x20000000000000000000000000000000; b <<= 16;} if(b < 0x1000000000000000000000000000000) {l -= 0x10000000000000000000000000000000; b <<= 8;} if(b < 0x10000000000000000000000000000000) {l -= 0x8000000000000000000000000000000; b <<= 4;} if(b < 0x40000000000000000000000000000000) {l -= 0x4000000000000000000000000000000; b <<= 2;} if(b < 0x80000000000000000000000000000000) {l -= 0x2000000000000000000000000000000; b <<= 1;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000;} /* b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) l |= 0x1; */ return uint128(l); } } /** * Calculate 2 raised into given power. * * @param x power to raise 2 into, multiplied by 2^121 * @return 2 raised into given power */ function pow_2(uint128 x) internal pure returns(uint128) { unchecked { uint r = 0x80000000000000000000000000000000; if(x & 0x1000000000000000000000000000000 > 0) r = r * 0xb504f333f9de6484597d89b3754abe9f >> 127; if(x & 0x800000000000000000000000000000 > 0) r = r * 0x9837f0518db8a96f46ad23182e42f6f6 >> 127; if(x & 0x400000000000000000000000000000 > 0) r = r * 0x8b95c1e3ea8bd6e6fbe4628758a53c90 >> 127; if(x & 0x200000000000000000000000000000 > 0) r = r * 0x85aac367cc487b14c5c95b8c2154c1b2 >> 127; if(x & 0x100000000000000000000000000000 > 0) r = r * 0x82cd8698ac2ba1d73e2a475b46520bff >> 127; if(x & 0x80000000000000000000000000000 > 0) r = r * 0x8164d1f3bc0307737be56527bd14def4 >> 127; if(x & 0x40000000000000000000000000000 > 0) r = r * 0x80b1ed4fd999ab6c25335719b6e6fd20 >> 127; if(x & 0x20000000000000000000000000000 > 0) r = r * 0x8058d7d2d5e5f6b094d589f608ee4aa2 >> 127; if(x & 0x10000000000000000000000000000 > 0) r = r * 0x802c6436d0e04f50ff8ce94a6797b3ce >> 127; if(x & 0x8000000000000000000000000000 > 0) r = r * 0x8016302f174676283690dfe44d11d008 >> 127; if(x & 0x4000000000000000000000000000 > 0) r = r * 0x800b179c82028fd0945e54e2ae18f2f0 >> 127; if(x & 0x2000000000000000000000000000 > 0) r = r * 0x80058baf7fee3b5d1c718b38e549cb93 >> 127; if(x & 0x1000000000000000000000000000 > 0) r = r * 0x8002c5d00fdcfcb6b6566a58c048be1f >> 127; if(x & 0x800000000000000000000000000 > 0) r = r * 0x800162e61bed4a48e84c2e1a463473d9 >> 127; if(x & 0x400000000000000000000000000 > 0) r = r * 0x8000b17292f702a3aa22beacca949013 >> 127; if(x & 0x200000000000000000000000000 > 0) r = r * 0x800058b92abbae02030c5fa5256f41fe >> 127; if(x & 0x100000000000000000000000000 > 0) r = r * 0x80002c5c8dade4d71776c0f4dbea67d6 >> 127; if(x & 0x80000000000000000000000000 > 0) r = r * 0x8000162e44eaf636526be456600bdbe4 >> 127; if(x & 0x40000000000000000000000000 > 0) r = r * 0x80000b1721fa7c188307016c1cd4e8b6 >> 127; if(x & 0x20000000000000000000000000 > 0) r = r * 0x8000058b90de7e4cecfc487503488bb1 >> 127; if(x & 0x10000000000000000000000000 > 0) r = r * 0x800002c5c8678f36cbfce50a6de60b14 >> 127; if(x & 0x8000000000000000000000000 > 0) r = r * 0x80000162e431db9f80b2347b5d62e516 >> 127; if(x & 0x4000000000000000000000000 > 0) r = r * 0x800000b1721872d0c7b08cf1e0114152 >> 127; if(x & 0x2000000000000000000000000 > 0) r = r * 0x80000058b90c1aa8a5c3736cb77e8dff >> 127; if(x & 0x1000000000000000000000000 > 0) r = r * 0x8000002c5c8605a4635f2efc2362d978 >> 127; if(x & 0x800000000000000000000000 > 0) r = r * 0x800000162e4300e635cf4a109e3939bd >> 127; if(x & 0x400000000000000000000000 > 0) r = r * 0x8000000b17217ff81bef9c551590cf83 >> 127; if(x & 0x200000000000000000000000 > 0) r = r * 0x800000058b90bfdd4e39cd52c0cfa27c >> 127; if(x & 0x100000000000000000000000 > 0) r = r * 0x80000002c5c85fe6f72d669e0e76e411 >> 127; if(x & 0x80000000000000000000000 > 0) r = r * 0x8000000162e42ff18f9ad35186d0df28 >> 127; if(x & 0x40000000000000000000000 > 0) r = r * 0x80000000b17217f84cce71aa0dcfffe7 >> 127; if(x & 0x20000000000000000000000 > 0) r = r * 0x8000000058b90bfc07a77ad56ed22aaa >> 127; if(x & 0x10000000000000000000000 > 0) r = r * 0x800000002c5c85fdfc23cdead40da8d6 >> 127; if(x & 0x8000000000000000000000 > 0) r = r * 0x80000000162e42fefc25eb1571853a66 >> 127; if(x & 0x4000000000000000000000 > 0) r = r * 0x800000000b17217f7d97f692baacded5 >> 127; if(x & 0x2000000000000000000000 > 0) r = r * 0x80000000058b90bfbead3b8b5dd254d7 >> 127; if(x & 0x1000000000000000000000 > 0) r = r * 0x8000000002c5c85fdf4eedd62f084e67 >> 127; if(x & 0x800000000000000000000 > 0) r = r * 0x800000000162e42fefa58aef378bf586 >> 127; if(x & 0x400000000000000000000 > 0) r = r * 0x8000000000b17217f7d24a78a3c7ef02 >> 127; if(x & 0x200000000000000000000 > 0) r = r * 0x800000000058b90bfbe9067c93e474a6 >> 127; if(x & 0x100000000000000000000 > 0) r = r * 0x80000000002c5c85fdf47b8e5a72599f >> 127; if(x & 0x80000000000000000000 > 0) r = r * 0x8000000000162e42fefa3bdb315934a2 >> 127; if(x & 0x40000000000000000000 > 0) r = r * 0x80000000000b17217f7d1d7299b49c46 >> 127; if(x & 0x20000000000000000000 > 0) r = r * 0x8000000000058b90bfbe8e9a8d1c4ea0 >> 127; if(x & 0x10000000000000000000 > 0) r = r * 0x800000000002c5c85fdf4745969ea76f >> 127; if(x & 0x8000000000000000000 > 0) r = r * 0x80000000000162e42fefa3a0df5373bf >> 127; if(x & 0x4000000000000000000 > 0) r = r * 0x800000000000b17217f7d1cff4aac1e1 >> 127; if(x & 0x2000000000000000000 > 0) r = r * 0x80000000000058b90bfbe8e7db95a2f1 >> 127; if(x & 0x1000000000000000000 > 0) r = r * 0x8000000000002c5c85fdf473e61ae1f8 >> 127; if(x & 0x800000000000000000 > 0) r = r * 0x800000000000162e42fefa39f121751c >> 127; if(x & 0x400000000000000000 > 0) r = r * 0x8000000000000b17217f7d1cf815bb96 >> 127; if(x & 0x200000000000000000 > 0) r = r * 0x800000000000058b90bfbe8e7bec1e0d >> 127; if(x & 0x100000000000000000 > 0) r = r * 0x80000000000002c5c85fdf473dee5f17 >> 127; if(x & 0x80000000000000000 > 0) r = r * 0x8000000000000162e42fefa39ef5438f >> 127; if(x & 0x40000000000000000 > 0) r = r * 0x80000000000000b17217f7d1cf7a26c8 >> 127; if(x & 0x20000000000000000 > 0) r = r * 0x8000000000000058b90bfbe8e7bcf4a4 >> 127; if(x & 0x10000000000000000 > 0) r = r * 0x800000000000002c5c85fdf473de72a2 >> 127; /* if(x & 0x8000000000000000 > 0) r = r * 0x80000000000000162e42fefa39ef3765 >> 127; if(x & 0x4000000000000000 > 0) r = r * 0x800000000000000b17217f7d1cf79b37 >> 127; if(x & 0x2000000000000000 > 0) r = r * 0x80000000000000058b90bfbe8e7bcd7d >> 127; if(x & 0x1000000000000000 > 0) r = r * 0x8000000000000002c5c85fdf473de6b6 >> 127; if(x & 0x800000000000000 > 0) r = r * 0x800000000000000162e42fefa39ef359 >> 127; if(x & 0x400000000000000 > 0) r = r * 0x8000000000000000b17217f7d1cf79ac >> 127; if(x & 0x200000000000000 > 0) r = r * 0x800000000000000058b90bfbe8e7bcd6 >> 127; if(x & 0x100000000000000 > 0) r = r * 0x80000000000000002c5c85fdf473de6a >> 127; if(x & 0x80000000000000 > 0) r = r * 0x8000000000000000162e42fefa39ef35 >> 127; if(x & 0x40000000000000 > 0) r = r * 0x80000000000000000b17217f7d1cf79a >> 127; if(x & 0x20000000000000 > 0) r = r * 0x8000000000000000058b90bfbe8e7bcd >> 127; if(x & 0x10000000000000 > 0) r = r * 0x800000000000000002c5c85fdf473de6 >> 127; if(x & 0x8000000000000 > 0) r = r * 0x80000000000000000162e42fefa39ef3 >> 127; if(x & 0x4000000000000 > 0) r = r * 0x800000000000000000b17217f7d1cf79 >> 127; if(x & 0x2000000000000 > 0) r = r * 0x80000000000000000058b90bfbe8e7bc >> 127; if(x & 0x1000000000000 > 0) r = r * 0x8000000000000000002c5c85fdf473de >> 127; if(x & 0x800000000000 > 0) r = r * 0x800000000000000000162e42fefa39ef >> 127; if(x & 0x400000000000 > 0) r = r * 0x8000000000000000000b17217f7d1cf7 >> 127; if(x & 0x200000000000 > 0) r = r * 0x800000000000000000058b90bfbe8e7b >> 127; if(x & 0x100000000000 > 0) r = r * 0x80000000000000000002c5c85fdf473d >> 127; if(x & 0x80000000000 > 0) r = r * 0x8000000000000000000162e42fefa39e >> 127; if(x & 0x40000000000 > 0) r = r * 0x80000000000000000000b17217f7d1cf >> 127; if(x & 0x20000000000 > 0) r = r * 0x8000000000000000000058b90bfbe8e7 >> 127; if(x & 0x10000000000 > 0) r = r * 0x800000000000000000002c5c85fdf473 >> 127; if(x & 0x8000000000 > 0) r = r * 0x80000000000000000000162e42fefa39 >> 127; if(x & 0x4000000000 > 0) r = r * 0x800000000000000000000b17217f7d1c >> 127; if(x & 0x2000000000 > 0) r = r * 0x80000000000000000000058b90bfbe8e >> 127; if(x & 0x1000000000 > 0) r = r * 0x8000000000000000000002c5c85fdf47 >> 127; if(x & 0x800000000 > 0) r = r * 0x800000000000000000000162e42fefa3 >> 127; if(x & 0x400000000 > 0) r = r * 0x8000000000000000000000b17217f7d1 >> 127; if(x & 0x200000000 > 0) r = r * 0x800000000000000000000058b90bfbe8 >> 127; if(x & 0x100000000 > 0) r = r * 0x80000000000000000000002c5c85fdf4 >> 127; if(x & 0x80000000 > 0) r = r * 0x8000000000000000000000162e42fefa >> 127; if(x & 0x40000000 > 0) r = r * 0x80000000000000000000000b17217f7d >> 127; if(x & 0x20000000 > 0) r = r * 0x8000000000000000000000058b90bfbe >> 127; if(x & 0x10000000 > 0) r = r * 0x800000000000000000000002c5c85fdf >> 127; if(x & 0x8000000 > 0) r = r * 0x80000000000000000000000162e42fef >> 127; if(x & 0x4000000 > 0) r = r * 0x800000000000000000000000b17217f7 >> 127; if(x & 0x2000000 > 0) r = r * 0x80000000000000000000000058b90bfb >> 127; if(x & 0x1000000 > 0) r = r * 0x8000000000000000000000002c5c85fd >> 127; if(x & 0x800000 > 0) r = r * 0x800000000000000000000000162e42fe >> 127; if(x & 0x400000 > 0) r = r * 0x8000000000000000000000000b17217f >> 127; if(x & 0x200000 > 0) r = r * 0x800000000000000000000000058b90bf >> 127; if(x & 0x100000 > 0) r = r * 0x80000000000000000000000002c5c85f >> 127; if(x & 0x80000 > 0) r = r * 0x8000000000000000000000000162e42f >> 127; if(x & 0x40000 > 0) r = r * 0x80000000000000000000000000b17217 >> 127; if(x & 0x20000 > 0) r = r * 0x8000000000000000000000000058b90b >> 127; if(x & 0x10000 > 0) r = r * 0x800000000000000000000000002c5c85 >> 127; if(x & 0x8000 > 0) r = r * 0x80000000000000000000000000162e42 >> 127; if(x & 0x4000 > 0) r = r * 0x800000000000000000000000000b1721 >> 127; if(x & 0x2000 > 0) r = r * 0x80000000000000000000000000058b90 >> 127; if(x & 0x1000 > 0) r = r * 0x8000000000000000000000000002c5c8 >> 127; if(x & 0x800 > 0) r = r * 0x800000000000000000000000000162e4 >> 127; if(x & 0x400 > 0) r = r * 0x8000000000000000000000000000b172 >> 127; if(x & 0x200 > 0) r = r * 0x800000000000000000000000000058b9 >> 127; if(x & 0x100 > 0) r = r * 0x80000000000000000000000000002c5c >> 127; if(x & 0x80 > 0) r = r * 0x8000000000000000000000000000162e >> 127; if(x & 0x40 > 0) r = r * 0x80000000000000000000000000000b17 >> 127; if(x & 0x20 > 0) r = r * 0x8000000000000000000000000000058b >> 127; if(x & 0x10 > 0) r = r * 0x800000000000000000000000000002c5 >> 127; if(x & 0x8 > 0) r = r * 0x80000000000000000000000000000162 >> 127; if(x & 0x4 > 0) r = r * 0x800000000000000000000000000000b1 >> 127; if(x & 0x2 > 0) r = r * 0x80000000000000000000000000000058 >> 127; if(x & 0x1 > 0) r = r * 0x8000000000000000000000000000002c >> 127; */ r >>= 127 -(x >> 121); return uint128(r); } } } /** * Ethereum smart contract library implementing Yield Math model. */ library YieldMath { using Math64x64 for int128; using Math64x64 for uint128; using Math64x64 for int256; using Math64x64 for uint256; using Exp64x64 for uint128; uint128 public constant ONE = 0x10000000000000000; // In 64.64 uint128 public constant TWO = 0x20000000000000000; // In 64.64 uint256 public constant MAX = type(uint128).max; // Used for overflow checks uint256 public constant VAR = 1e12; // The logarithm math used is not precise to the wei, but can deviate up to 1e12 from the real value. /** * Calculate a YieldSpace pool invariant according to the whitepaper */ function invariant(uint128 baseReserves, uint128 fyTokenReserves, uint256 totalSupply, uint128 timeTillMaturity, int128 ts) public pure returns(uint128) { if (totalSupply == 0) return 0; unchecked { // a = (1 - ts * timeTillMaturity) int128 a = int128(ONE).sub(ts.mul(timeTillMaturity.fromUInt())); require (a > 0, "YieldMath: Too far from maturity"); uint256 sum = uint256(baseReserves.pow(uint128 (a), ONE)) + uint256(fyTokenReserves.pow(uint128 (a), ONE)) >> 1; require(sum < MAX, "YieldMath: Sum overflow"); uint256 result = uint256(uint128(sum).pow(ONE, uint128(a))) / totalSupply; require (result < MAX, "YieldMath: Result overflow"); return uint128(result); } } /** * Calculate the amount of fyToken a user would get for given amount of Base. * https://www.desmos.com/calculator/5nf2xuy6yb * @param baseReserves base reserves amount * @param fyTokenReserves fyToken reserves amount * @param baseAmount base amount to be traded * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of fyToken a user would get for given amount of Base */ function fyTokenOutForBaseIn( uint128 baseReserves, uint128 fyTokenReserves, uint128 baseAmount, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { unchecked { uint128 a = _computeA(timeTillMaturity, ts, g); // za = baseReserves ** a uint256 za = baseReserves.pow(a, ONE); // ya = fyTokenReserves ** a uint256 ya = fyTokenReserves.pow(a, ONE); // zx = baseReserves + baseAmount uint256 zx = uint256(baseReserves) + uint256(baseAmount); require(zx <= MAX, "YieldMath: Too much base in"); // zxa = zx ** a uint256 zxa = uint128(zx).pow(a, ONE); // sum = za + ya - zxa uint256 sum = za + ya - zxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow. require(sum <= MAX, "YieldMath: Insufficient fyToken reserves"); // result = fyTokenReserves - (sum ** (1/a)) uint256 result = uint256(fyTokenReserves) - uint256(uint128(sum).pow(ONE, a)); require(result <= MAX, "YieldMath: Rounding induced error"); result = result > VAR ? result - VAR : 0; // Subtract error guard, flooring the result at zero return uint128(result); } } /** * Calculate the amount of base a user would get for certain amount of fyToken. * https://www.desmos.com/calculator/6jlrre7ybt * @param baseReserves base reserves amount * @param fyTokenReserves fyToken reserves amount * @param fyTokenAmount fyToken amount to be traded * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of Base a user would get for given amount of fyToken */ function baseOutForFYTokenIn( uint128 baseReserves, uint128 fyTokenReserves, uint128 fyTokenAmount, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { unchecked { uint128 a = _computeA(timeTillMaturity, ts, g); // za = baseReserves ** a uint256 za = baseReserves.pow(a, ONE); // ya = fyTokenReserves ** a uint256 ya = fyTokenReserves.pow(a, ONE); // yx = fyDayReserves + fyTokenAmount uint256 yx = uint256(fyTokenReserves) + uint256(fyTokenAmount); require(yx <= MAX, "YieldMath: Too much fyToken in"); // yxa = yx ** a uint256 yxa = uint128(yx).pow(a, ONE); // sum = za + ya - yxa uint256 sum = za + ya - yxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow. require(sum <= MAX, "YieldMath: Insufficient base reserves"); // result = baseReserves - (sum ** (1/a)) uint256 result = uint256(baseReserves) - uint256(uint128(sum).pow(ONE, a)); require(result <= MAX, "YieldMath: Rounding induced error"); result = result > VAR ? result - VAR : 0; // Subtract error guard, flooring the result at zero return uint128(result); } } /** * Calculate the amount of fyToken a user could sell for given amount of Base. * https://www.desmos.com/calculator/0rgnmtckvy * @param baseReserves base reserves amount * @param fyTokenReserves fyToken reserves amount * @param baseAmount Base amount to be traded * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of fyToken a user could sell for given amount of Base */ function fyTokenInForBaseOut( uint128 baseReserves, uint128 fyTokenReserves, uint128 baseAmount, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { unchecked { uint128 a = _computeA(timeTillMaturity, ts, g); // za = baseReserves ** a uint256 za = baseReserves.pow(a, ONE); // ya = fyTokenReserves ** a uint256 ya = fyTokenReserves.pow(a, ONE); // zx = baseReserves - baseAmount uint256 zx = uint256(baseReserves) - uint256(baseAmount); require(zx <= MAX, "YieldMath: Too much base out"); // zxa = zx ** a uint256 zxa = uint128(zx).pow(a, ONE); // sum = za + ya - zxa uint256 sum = za + ya - zxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow. require(sum <= MAX, "YieldMath: Resulting fyToken reserves too high"); // result = (sum ** (1/a)) - fyTokenReserves uint256 result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves); require(result <= MAX, "YieldMath: Rounding induced error"); result = result < MAX - VAR ? result + VAR : MAX; // Add error guard, ceiling the result at max return uint128(result); } } /** * Calculate the amount of base a user would have to pay for certain amount of fyToken. * https://www.desmos.com/calculator/ws5oqj8x5i * @param baseReserves Base reserves amount * @param fyTokenReserves fyToken reserves amount * @param fyTokenAmount fyToken amount to be traded * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of base a user would have to pay for given amount of * fyToken */ function baseInForFYTokenOut( uint128 baseReserves, uint128 fyTokenReserves, uint128 fyTokenAmount, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { unchecked { uint128 a = _computeA(timeTillMaturity, ts, g); // za = baseReserves ** a uint256 za = baseReserves.pow(a, ONE); // ya = fyTokenReserves ** a uint256 ya = fyTokenReserves.pow(a, ONE); // yx = baseReserves - baseAmount uint256 yx = uint256(fyTokenReserves) - uint256(fyTokenAmount); require(yx <= MAX, "YieldMath: Too much fyToken out"); // yxa = yx ** a uint256 yxa = uint128(yx).pow(a, ONE); // sum = za + ya - yxa uint256 sum = za + ya - yxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow. require(sum <= MAX, "YieldMath: Resulting base reserves too high"); // result = (sum ** (1/a)) - baseReserves uint256 result = uint256(uint128(sum).pow(ONE, a)) - uint256(baseReserves); require(result <= MAX, "YieldMath: Rounding induced error"); result = result < MAX - VAR ? result + VAR : MAX; // Add error guard, ceiling the result at max return uint128(result); } } /** * Calculate the max amount of fyTokens that can be bought from the pool without making the interest rate negative. * See section 6.3 of the YieldSpace White paper * @param baseReserves Base reserves amount * @param fyTokenReserves fyToken reserves amount * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return max amount of fyTokens that can be bought from the pool */ function maxFYTokenOut( uint128 baseReserves, uint128 fyTokenReserves, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { if (baseReserves == fyTokenReserves) return 0; unchecked { uint128 a = _computeA(timeTillMaturity, ts, g); // xa = baseReserves ** a uint128 xa = baseReserves.pow(a, ONE); // ya = fyTokenReserves ** a uint128 ya = fyTokenReserves.pow(a, ONE); int128 xy2 = (xa + ya).divu(TWO); uint inaccessible = uint256(uint128(xy2).pow(ONE, a)); require(inaccessible <= MAX, "YieldMath: Rounding induced error"); inaccessible = inaccessible < MAX - VAR ? inaccessible + VAR : MAX; // Add error guard, ceiling the result at max return uint128(inaccessible) > fyTokenReserves ? 0 : fyTokenReserves - uint128(inaccessible); } } /** * Calculate the max amount of fyTokens that can be sold to into the pool. * @param baseReserves Base reserves amount * @param fyTokenReserves fyToken reserves amount * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return max amount of fyTokens that can be sold to into the pool */ function maxFYTokenIn( uint128 baseReserves, uint128 fyTokenReserves, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { unchecked { uint128 b = _computeB(timeTillMaturity, ts, g); // xa = baseReserves ** a uint128 xa = baseReserves.pow(b, ONE); // ya = fyTokenReserves ** a uint128 ya = fyTokenReserves.pow(b, ONE); uint result = (xa + ya).pow(ONE, b) - fyTokenReserves; require(result <= MAX, "YieldMath: Rounding induced error"); result = result > VAR ? result - VAR : 0; // Subtract error guard, flooring the result at zero return uint128(result); } } /** * Calculate the max amount of base that can be sold to into the pool without making the interest rate negative. * @param baseReserves Base reserves amount * @param fyTokenReserves fyToken reserves amount * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return max amount of base that can be sold to into the pool */ function maxBaseIn( uint128 baseReserves, uint128 fyTokenReserves, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns (uint128) { uint128 _maxFYTokenOut = maxFYTokenOut(baseReserves, fyTokenReserves, timeTillMaturity, ts, g); if (_maxFYTokenOut > 0) return baseInForFYTokenOut(baseReserves, fyTokenReserves, _maxFYTokenOut, timeTillMaturity, ts, g); return 0; } /** * Calculate the max amount of base that can be bought from the pool. * @param baseReserves Base reserves amount * @param fyTokenReserves fyToken reserves amount * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return max amount of base that can be bought from the pool */ function maxBaseOut( uint128 baseReserves, uint128 fyTokenReserves, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns (uint128) { uint128 _maxFYTokenIn = maxFYTokenIn(baseReserves, fyTokenReserves, timeTillMaturity, ts, g); return baseOutForFYTokenIn(baseReserves, fyTokenReserves, _maxFYTokenIn, timeTillMaturity, ts, g); } function _computeA(uint128 timeTillMaturity, int128 ts, int128 g) private pure returns (uint128) { unchecked { // t = ts * timeTillMaturity int128 t = ts.mul(timeTillMaturity.fromUInt()); require(t >= 0, "YieldMath: t must be positive"); // Meaning neither T or ts can be negative // a = (1 - gt) int128 a = int128(ONE).sub(g.mul(t)); require(a > 0, "YieldMath: Too far from maturity"); require(a <= int128(ONE), "YieldMath: g must be positive"); return uint128(a); } } function _computeB(uint128 timeTillMaturity, int128 ts, int128 g) private pure returns (uint128) { unchecked { // t = ts * timeTillMaturity int128 t = ts.mul(timeTillMaturity.fromUInt()); require(t >= 0, "YieldMath: t must be positive"); // Meaning neither T or ts can be negative // b = (1 - t/g) int128 b = int128(ONE).sub(t.div(g)); require(b > 0, "YieldMath: Too far from maturity"); require(b <= int128(ONE), "YieldMath: g must be positive"); return uint128(b); } } } // SPDX-License-Identifier: MIT // Inspired on token.sol from DappHub. Natspec adpated from OpenZeppelin. pragma solidity ^0.8.0; import "./IERC20Metadata.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}. * * 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. * * Calls to {transferFrom} do not check for allowance if the caller is the owner * of the funds. This allows to reduce the number of approvals that are necessary. * * Finally, {transferFrom} does not decrease the allowance if it is set to * type(uint256).max. This reduces the gas costs without any likely impact. */ contract ERC20 is IERC20Metadata { uint256 internal _totalSupply; mapping (address => uint256) internal _balanceOf; mapping (address => mapping (address => uint256)) internal _allowance; string public override name = "???"; string public override symbol = "???"; uint8 public override decimals = 18; /** * @dev Sets the values for {name}, {symbol} and {decimals}. */ constructor(string memory name_, string memory symbol_, uint8 decimals_) { name = name_; symbol = symbol_; decimals = decimals_; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() external view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address guy) external view virtual override returns (uint256) { return _balanceOf[guy]; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) external view virtual override returns (uint256) { return _allowance[owner][spender]; } /** * @dev See {IERC20-approve}. */ function approve(address spender, uint wad) external virtual override returns (bool) { return _setAllowance(msg.sender, spender, wad); } /** * @dev See {IERC20-transfer}. * * Requirements: * * - the caller must have a balance of at least `wad`. */ function transfer(address dst, uint wad) external virtual override returns (bool) { return _transfer(msg.sender, dst, wad); } /** * @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: * * - `src` must have a balance of at least `wad`. * - the caller is not `src`, it must have allowance for ``src``'s tokens of at least * `wad`. */ /// if_succeeds {:msg "TransferFrom - decrease allowance"} msg.sender != src ==> old(_allowance[src][msg.sender]) >= wad; function transferFrom(address src, address dst, uint wad) external virtual override returns (bool) { _decreaseAllowance(src, wad); return _transfer(src, dst, wad); } /** * @dev Moves tokens `wad` from `src` to `dst`. * * Emits a {Transfer} event. * * Requirements: * * - `src` must have a balance of at least `amount`. */ /// if_succeeds {:msg "Transfer - src decrease"} old(_balanceOf[src]) >= _balanceOf[src]; /// if_succeeds {:msg "Transfer - dst increase"} _balanceOf[dst] >= old(_balanceOf[dst]); /// if_succeeds {:msg "Transfer - supply"} old(_balanceOf[src]) + old(_balanceOf[dst]) == _balanceOf[src] + _balanceOf[dst]; function _transfer(address src, address dst, uint wad) internal virtual returns (bool) { require(_balanceOf[src] >= wad, "ERC20: Insufficient balance"); unchecked { _balanceOf[src] = _balanceOf[src] - wad; } _balanceOf[dst] = _balanceOf[dst] + wad; emit Transfer(src, dst, wad); return true; } /** * @dev Sets the allowance granted to `spender` by `owner`. * * Emits an {Approval} event indicating the updated allowance. */ function _setAllowance(address owner, address spender, uint wad) internal virtual returns (bool) { _allowance[owner][spender] = wad; emit Approval(owner, spender, wad); return true; } /** * @dev Decreases the allowance granted to the caller by `src`, unless src == msg.sender or _allowance[src][msg.sender] == MAX * * Emits an {Approval} event indicating the updated allowance, if the allowance is updated. * * Requirements: * * - `spender` must have allowance for the caller of at least * `wad`, unless src == msg.sender */ /// if_succeeds {:msg "Decrease allowance - underflow"} old(_allowance[src][msg.sender]) <= _allowance[src][msg.sender]; function _decreaseAllowance(address src, uint wad) internal virtual returns (bool) { if (src != msg.sender) { uint256 allowed = _allowance[src][msg.sender]; if (allowed != type(uint).max) { require(allowed >= wad, "ERC20: Insufficient approval"); unchecked { _setAllowance(src, msg.sender, allowed - wad); } } } return true; } /** @dev Creates `wad` tokens and assigns them to `dst`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. */ /// if_succeeds {:msg "Mint - balance overflow"} old(_balanceOf[dst]) >= _balanceOf[dst]; /// if_succeeds {:msg "Mint - supply overflow"} old(_totalSupply) >= _totalSupply; function _mint(address dst, uint wad) internal virtual returns (bool) { _balanceOf[dst] = _balanceOf[dst] + wad; _totalSupply = _totalSupply + wad; emit Transfer(address(0), dst, wad); return true; } /** * @dev Destroys `wad` tokens from `src`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `src` must have at least `wad` tokens. */ /// if_succeeds {:msg "Burn - balance underflow"} old(_balanceOf[src]) <= _balanceOf[src]; /// if_succeeds {:msg "Burn - supply underflow"} old(_totalSupply) <= _totalSupply; function _burn(address src, uint wad) internal virtual returns (bool) { unchecked { require(_balanceOf[src] >= wad, "ERC20: Insufficient balance"); _balanceOf[src] = _balanceOf[src] - wad; _totalSupply = _totalSupply - wad; emit Transfer(src, address(0), wad); } return true; } } // SPDX-License-Identifier: MIT // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ pragma solidity ^0.8.0; /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612 { /** * @dev Sets `amount` 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: * * - `owner` cannot be the zero address. * - `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 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current ERC2612 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; library AddressStringUtil { // converts an address to the uppercase hex string, extracting only len bytes (up to 20, multiple of 2) function toAsciiString(address addr, uint256 len) internal pure returns (string memory) { require(len % 2 == 0 && len > 0 && len <= 40, "AddressStringUtil: INVALID_LEN"); bytes memory s = new bytes(len); uint256 addrNum = uint256(uint160(addr)); for (uint256 ii = 0; ii < len ; ii +=2) { uint8 b = uint8(addrNum >> (4 * (38 - ii))); s[ii] = char(b >> 4); s[ii + 1] = char(b & 0x0f); } return string(s); } // hi and lo are only 4 bits and between 0 and 16 // this method converts those values to the unicode/ascii code point for the hex representation // uses upper case for the characters function char(uint8 b) private pure returns (bytes1 c) { if (b < 10) { return bytes1(b + 0x30); } else { return bytes1(b + 0x37); } } } // SPDX-License-Identifier: MIT // Taken from https://github.com/sushiswap/BoringSolidity/blob/441e51c0544cf2451e6116fe00515e71d7c42e2c/contracts/BoringBatchable.sol pragma solidity >=0.6.0; library RevertMsgExtractor { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. 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 } } // SPDX-License-Identifier: BUSL-1.1 /* * Math 64.64 Smart Contract Library. Copyright © 2019 by Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity 0.8.6; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library Math64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } }
@dev Returns the base balance
function getBaseBalance() public view override returns(uint112) { return _getBaseBalance(); }
223,865
[ 1, 1356, 326, 1026, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8297, 13937, 1435, 203, 3639, 1071, 1476, 3849, 203, 3639, 1135, 12, 11890, 17666, 13, 203, 565, 288, 203, 3639, 327, 389, 588, 2171, 13937, 5621, 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 ]
pragma solidity >=0.4.21 <0.7.0; contract Record { //structure for the user or patient model struct user{ uint patid; string accountname; //user name string password; //user password address useraddress; //user ethereum address bool set; string lat; string lang; } struct permission{ address doc; bool set; } mapping(address => permission) permissionlist; function askPermission(address _useraddress,address _doctoraddress) public{ permissionlist[_useraddress]=permission(_doctoraddress,false); } function showPermission(address _useraddress) public view returns(address){ return permissionlist[_useraddress].doc; } function addPermission(address _useraddress,address _doctoraddress) public{ permissionlist[_useraddress]=permission(_doctoraddress,true); } function removePermission(address _useraddress,address _doctoraddress) public{ permissionlist[_useraddress]=permission(_doctoraddress,false); } function getPermisson(address _useraddress) public view returns(address){ return permissionlist[_useraddress].doc; } function gotPermission(address _useraddress,address _doctoraddress)public view returns(bool) { if(permissionlist[_useraddress].doc==_doctoraddress && permissionlist[_useraddress].set==true) return true; else return false; } //structure for heart disease struct heart{ string diseases; } mapping(address=>heart) public heartlist; //add heart disease output function addheart(address _useraddress,string memory _recordhash) public { heartlist[_useraddress]=heart(_recordhash); } function getheart(address _useraddress) public view returns(string memory){ return heartlist[_useraddress].diseases; } //structure for malaria disease struct malaria{ string diseases; } mapping(address=>malaria) public malarialist; //add malaria disease output function addMalaria(address _useraddress,string memory _recordhash) public { malarialist[_useraddress]=malaria(_recordhash); } function getMalaria(address _useraddress) public view returns(string memory){ return malarialist[_useraddress].diseases; } //structure for kidney disease struct kidney{ string diseases; } mapping(address=>kidney) public kidneylist; //add kidney disease output function addKidney(address _useraddress,string memory _recordhash) public { kidneylist[_useraddress]=kidney(_recordhash); } function getKidney(address _useraddress) public view returns(string memory){ return kidneylist[_useraddress].diseases; } //structure for liver disease struct liver{ string diseases; } mapping(address=>liver) public liverlist; //add liver disease output function addLiver(address _useraddress,string memory _recordhash) public { liverlist[_useraddress]=liver(_recordhash); } function getLiver(address _useraddress) public view returns(string memory){ return liverlist[_useraddress].diseases; } uint public userCount=0; //number of user or patient registered mapping(address => user) public userlist; //return the user name by mapping the address function find_user_name(address _address) public view returns(string memory){ return userlist[_address].accountname; } //return the user name by mapping the address function find_user_password(address _address) public view returns(string memory){ return userlist[_address].password; } //add user's name, ethereum address and password function addUser(string memory _accountname,string memory _password, address _useraddress,bool _userset,string memory _lat,string memory _lang) public{ user storage User = userlist[_useraddress]; require(!User.set); uint ui=incrementcount(); //keep count of no. of registered user ui=ui-1; userlist[_useraddress]=user(ui,_accountname,_password,_useraddress,_userset,_lat,_lang); count.push(0); } function getUserDetails(address _useraddress) public view returns(string memory _lat,string memory _lang){ _lat=userlist[_useraddress].lat; _lang=userlist[_useraddress].lang; } //increments every time to keep track of registered user function incrementcount() public returns(uint ){ return userCount+=1; } //structure for the doctor struct doctor{ string doctorname; //doctor name string password; //doctor password address doctoraddress; //doctor ethereum address bool set; //to check whether doctor exist } uint[] count; //structure ro store record struct record{ address patientaddress; string recordHash; } event HospitalAddition(address hospital); mapping (address => bool) public isHospital; mapping(address => doctor) public doctorlist; mapping(address => mapping(uint => record)) recordList; function addHospital(address _hospital) public { isHospital[_hospital] = true; emit HospitalAddition(_hospital); } function addDoctor(string memory _doctorname,string memory _password, address _doctoraddress,bool _doctorset) public{ doctor storage Doctor = doctorlist[_doctoraddress]; // Check that the doctor did not already exist: require(!Doctor.set); doctorlist[_doctoraddress]=doctor(_doctorname,_password,_doctoraddress,_doctorset); } function addRecord(address _patientaddress,address _doctoraddress,string memory _recordhash) public{ if(permissionlist[_patientaddress].doc==_doctoraddress && permissionlist[_patientaddress].set == true) { uint got=getId(_patientaddress); count[got] = count[got]+1; uint go=count[got]; recordList[_patientaddress][go]=record(_patientaddress,_recordhash); } else { revert("No Permission Given"); } } function getRecord(address _patientaddress,uint num) public view returns( string memory ){ return recordList[_patientaddress][num].recordHash; } function getDoctorName(address _docaddress) public view returns(string memory){ return doctorlist[_docaddress].doctorname; } function getDoctorPassword(address _docaddress) public view returns(string memory){ return doctorlist[_docaddress].password; } function getId(address _patientaddress) public view returns (uint){ return userlist[_patientaddress].patid; } function getRecordCountPatient(uint _num) public view returns(uint){ return count[_num]; } function getNum(address _patientaddress) public view returns(uint){ uint n=userlist[_patientaddress].patid; return count[n]; } }
user ethereum address
address useraddress;
1,775,868
[ 1, 1355, 13750, 822, 379, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1758, 729, 2867, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; /** * @title TokenBEP20 */ import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; contract Token is ERC20, ERC20Burnable { constructor() ERC20("Token", "Token") { _mint(msg.sender, 100000000e18); //100,000,000 tokens totalsupply } }
100,000,000 tokens totalsupply
_mint(msg.sender, 100000000e18);
5,423,324
[ 1, 6625, 16, 3784, 16, 3784, 2430, 19489, 416, 1283, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 67, 81, 474, 12, 3576, 18, 15330, 16, 2130, 9449, 73, 2643, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^ 0.4.21; pragma solidity ^0.4.10; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } pragma solidity ^0.4.10; interface ERC20 { function balanceOf(address who) view returns (uint256); function transfer(address to, uint256 value) returns (bool); function allowance(address owner, address spender) view returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.4.10; interface ERC223 { function transfer(address to, uint value, bytes data) returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } pragma solidity ^0.4.10; contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } pragma solidity ^0.4.21; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable()public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner)public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping(address => uint256)public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ function RefundVault(address _wallet)public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor)onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close()onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds()onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor)public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } /** * @title BonusScheme * @dev This contract is used for storing and granting tokens calculated * according to bonus scheme while a crowdsale is in progress. * When crowdsale ends the rest of tokens is transferred to developers. */ contract BonusScheme is Ownable { using SafeMath for uint256; /** * Defining timestamps for bonuscheme from White Paper. * The start of bonuses is 15 May 2018 and the end is 23 June 2018. * There are 2 seconds in between changing the phases. */ uint256 startOfFirstBonus = 1525892100; uint256 endOfFirstBonus = (startOfFirstBonus - 1) + 5 minutes; uint256 startOfSecondBonus = (startOfFirstBonus + 1) + 5 minutes; uint256 endOfSecondBonus = (startOfSecondBonus - 1) + 5 minutes; uint256 startOfThirdBonus = (startOfSecondBonus + 1) + 5 minutes; uint256 endOfThirdBonus = (startOfThirdBonus - 1) + 5 minutes; uint256 startOfFourthBonus = (startOfThirdBonus + 1) + 5 minutes; uint256 endOfFourthBonus = (startOfFourthBonus - 1) + 5 minutes; uint256 startOfFifthBonus = (startOfFourthBonus + 1) + 5 minutes; uint256 endOfFifthBonus = (startOfFifthBonus - 1) + 5 minutes; /** * Defining bonuses according to White Paper. * First week there is bonus 35%. * Second week there is bonus 30%. * Third week there is bonus 20%. * Fourth week there is bonus 10%. * Fifth week there is bonus 5%. */ uint256 firstBonus = 35; uint256 secondBonus = 30; uint256 thirdBonus = 20; uint256 fourthBonus = 10; uint256 fifthBonus = 5; event BonusCalculated(uint256 tokenAmount); function BonusScheme() public { } /** * @dev Calculates from Bonus Scheme how many tokens can be added to purchased _tokenAmount. * @param _tokenAmount The amount of calculated tokens to sent Ether. * @return Number of bonus tokens that can be granted with the specified _tokenAmount. */ function getBonusTokens(uint256 _tokenAmount)onlyOwner public returns(uint256) { if (block.timestamp >= startOfFirstBonus && block.timestamp <= endOfFirstBonus) { _tokenAmount = _tokenAmount.mul(firstBonus).div(100); } else if (block.timestamp >= startOfSecondBonus && block.timestamp <= endOfSecondBonus) { _tokenAmount = _tokenAmount.mul(secondBonus).div(100); } else if (block.timestamp >= startOfThirdBonus && block.timestamp <= endOfThirdBonus) { _tokenAmount = _tokenAmount.mul(thirdBonus).div(100); } else if (block.timestamp >= startOfFourthBonus && block.timestamp <= endOfFourthBonus) { _tokenAmount = _tokenAmount.mul(fourthBonus).div(100); } else if (block.timestamp >= startOfFifthBonus && block.timestamp <= endOfFifthBonus) { _tokenAmount = _tokenAmount.mul(fifthBonus).div(100); } else _tokenAmount=0; emit BonusCalculated(_tokenAmount); return _tokenAmount; } } contract StandardToken is ERC20, ERC223, Ownable { using SafeMath for uint; string internal _name; string internal _symbol; uint8 internal _decimals; uint256 internal _totalSupply; uint256 internal _bonusSupply; uint256 public ethRate; // How many token units a buyer gets per eth uint256 public min_contribution; // Minimal contribution in ICO uint256 public totalWeiRaised; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. uint public tokensSold; // the number of tokens already sold uint public softCap; //softcap in tokens uint public start; // the start date of the crowdsale uint public end; // the end date of the crowdsale bool public crowdsaleClosed; // indicates if the crowdsale has been closed already RefundVault public vault; // refund vault used to hold funds while crowdsale is running BonusScheme public bonusScheme; // contract used to hold and give tokens according to bonus scheme from white paper address public fundsWallet; // Where should the raised ETH go? mapping(address => bool)public frozenAccount; mapping(address => uint256)internal balances; mapping(address => mapping(address => uint256))internal allowed; /* This generates a public event on the blockchain that will notify clients */ event Burn(address indexed burner, uint256 value); event FrozenFunds(address target, bool frozen); event Finalized(); event BonusSent(address indexed from, address indexed to, uint256 boughtTokens, uint256 bonusTokens); /** * 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 of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //TODO: correction of smart contract balance of tokens //done //TODO: change symbol and name of token //TODO: change start and end timestamps function StandardToken()public { _symbol = "AmTC1"; _name = "AmTokenTestCase1"; _decimals = 5; _totalSupply = 1100000 * (10 ** uint256(_decimals)); //_creatorSupply = _totalSupply * 25 / 100; // The creator has 25% of tokens //_icoSupply = _totalSupply * 58 / 100; // Smart contract balance is 58% of tokens (638 000 tokens) _bonusSupply = _totalSupply * 17 / 100; // The Bonus scheme supply is 17% (187 000 tokens) fundsWallet = msg.sender; // The owner of the contract gets ETH vault = new RefundVault(fundsWallet); bonusScheme = new BonusScheme(); //balances[this] = _icoSupply; // Token balance to smart contract will be added manually from owners wallet balances[msg.sender] = _totalSupply.sub(_bonusSupply); balances[bonusScheme] = _bonusSupply; ethRate = 40000000; // Set the rate of token to ether exchange for the ICO min_contribution = 1 ether / (10**11); // 0.1 ETH is minimum deposit totalWeiRaised = 0; tokensSold = 0; softCap = 20000 * 10 ** uint(_decimals); start = 1525891800; end = 1525893600; crowdsaleClosed = false; } modifier beforeICO() { require(block.timestamp <= start); _; } modifier afterDeadline() { require(block.timestamp > end); _; } function name() public view returns(string) { return _name; } function symbol() public view returns(string) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } function totalSupply() public view returns(uint256) { return _totalSupply; } // ----------------------------------------- // 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 */ //bad calculations, change //should be ok //TODO: pre-ico phase to be defined and checked with other tokens, ICO-when closed check softcap, softcap-add pre-ico tokens, if isnt achieved revert all transactions, hardcap, timestamps&bonus scheme(will be discussed next week), minimum amount is 0,1ETH ... function buyTokens(address _beneficiary)public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); // calculate token amount to be sold require(balances[this] > tokens); //check if the contract has enough tokens totalWeiRaised = totalWeiRaised.add(weiAmount); //update state tokensSold = tokensSold.add(tokens); //update state _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _processBonus(_beneficiary, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); /* balances[this] = balances[this].sub(weiAmount); balances[_beneficiary] = balances[_beneficiary].add(weiAmount); emit Transfer(this, _beneficiary, weiAmount); // Broadcast a message to the blockchain */ } // ----------------------------------------- // Crowdsale 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 view { require(_beneficiary != address(0)); require(_weiAmount >= min_contribution); require(!crowdsaleClosed && block.timestamp >= start && block.timestamp <= end); } /** * @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 pure { // 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 { this.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 Executed when a purchase has been validated and bonus tokens need to be calculated. Not necessarily emits/sends bonus tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens from which is calculated bonus amount */ function _processBonus(address _beneficiary, uint256 _tokenAmount)internal { uint256 bonusTokens = bonusScheme.getBonusTokens(_tokenAmount); // Calculate bonus token amount if (balances[bonusScheme] < bonusTokens) { // If the bonus scheme does not have enough tokens, send all remaining bonusTokens = balances[bonusScheme]; balances[bonusScheme] = 0; } if (bonusTokens > 0) { // If there are no tokens left in bonus scheme, we do not need transaction. balances[bonusScheme] = balances[bonusScheme].sub(bonusTokens); balances[_beneficiary] = balances[_beneficiary].add(bonusTokens); emit Transfer(address(bonusScheme), _beneficiary, bonusTokens); emit BonusSent(address(bonusScheme), _beneficiary, _tokenAmount, bonusTokens); tokensSold = tokensSold.add(bonusTokens); // update state } } /** * @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) { _weiAmount = _weiAmount.mul(ethRate); return _weiAmount.div(10 ** uint(18 - _decimals)); //as we have other decimals number than standard 18, we need to calculate } /** * @dev Determines how ETH is stored/forwarded on purchases, sending funds to vault. */ function _forwardFunds()internal { vault.deposit.value(msg.value)(msg.sender); //Transfer ether to vault } ///!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! bad function, refactor //should be solved now //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons function transfer(address _to, uint256 _value)public returns(bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(!frozenAccount[msg.sender]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen //require(!isContract(_to)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner)public view returns(uint256 balance) { return balances[_owner]; } //standard function transferFrom similar to ERC20 transferFrom with no _data //added due to backwards compatibility reasons function transferFrom(address _from, address _to, uint256 _value)public returns(bool) { require(_to != address(0)); require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value)public returns(bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender)public view returns(uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue)public returns(bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue)public returns(bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // Function that is called when a user or another contract wants to transfer funds . ///add trasnfertocontractwithcustomfallback //done function transfer(address _to, uint _value, bytes _data, string _custom_fallback)public returns(bool success) { require(!frozenAccount[msg.sender]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen if (isContract(_to)) { return transferToContractWithCustomFallback(_to, _value, _data, _custom_fallback); } else { return transferToAddress(_to, _value, _data); } } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data)public returns(bool) { require(!frozenAccount[msg.sender]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } /* require(_to != address(0)); require(_value > 0 && _value <= balances[msg.sender]); if(isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); return true; } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value, _data); */ } function isContract(address _addr)private view returns(bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data)private returns(bool success) { require(balanceOf(msg.sender) > _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data)private returns(bool success) { require(balanceOf(msg.sender) > _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract with custom fallback function transferToContractWithCustomFallback(address _to, uint _value, bytes _data, string _custom_fallback)private returns(bool success) { require(balanceOf(msg.sender) > _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); emit Transfer(msg.sender, _to, _value, _data); return true; } function setPreICOSoldAmount(uint256 _soldTokens, uint256 _raisedWei)onlyOwner beforeICO public { tokensSold = tokensSold.add(_soldTokens); totalWeiRaised = totalWeiRaised.add(_raisedWei); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze)onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value)onlyOwner public returns(bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender _totalSupply = _totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; } /* NOT NEEDED as ethers are in vault //check the functionality // @notice Failsafe drain function withdrawEther()onlyOwner public returns(bool) { owner.transfer(address(this).balance); return true; } */ // @notice Failsafe transfer tokens for the team to given account function withdrawTokens()onlyOwner public returns(bool) { require(this.transfer(owner, balances[this])); uint256 bonusTokens = balances[address(bonusScheme)]; balances[address(bonusScheme)] = 0; if (bonusTokens > 0) { // If there are no tokens left in bonus scheme, we do not need transaction. balances[owner] = balances[owner].add(bonusTokens); emit Transfer(address(bonusScheme), owner, bonusTokens); } return true; } /** * @dev Allow the owner to transfer out any accidentally sent ERC20 tokens. * @param _tokenAddress The address of the ERC20 contract. * @param _amount The amount of tokens to be transferred. */ function transferAnyERC20Token(address _tokenAddress, uint256 _amount)onlyOwner public returns(bool success) { return ERC20(_tokenAddress).transfer(owner, _amount); } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund()public { require(crowdsaleClosed); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached()public view returns(bool) { return tokensSold >= softCap; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization()internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()onlyOwner afterDeadline public { require(!crowdsaleClosed); finalization(); emit Finalized(); withdrawTokens(); crowdsaleClosed = true; } }
@notice `freeze? Prevent | Allow` `target` from sending & receiving tokens @param target Address to be frozen @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze)onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); }
931,840
[ 1, 68, 29631, 35, 19412, 571, 7852, 68, 1375, 3299, 68, 628, 5431, 473, 15847, 2430, 225, 1018, 5267, 358, 506, 12810, 225, 16684, 3344, 358, 16684, 518, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 16684, 3032, 12, 2867, 1018, 16, 1426, 16684, 13, 3700, 5541, 1071, 288, 203, 202, 202, 28138, 3032, 63, 3299, 65, 273, 16684, 31, 203, 202, 202, 18356, 478, 9808, 42, 19156, 12, 3299, 16, 16684, 1769, 203, 202, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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
this low-level function should be called from a contract which performs important safety checks
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,959
[ 1, 2211, 4587, 17, 2815, 445, 1410, 506, 2566, 628, 279, 6835, 1492, 11199, 10802, 24179, 4271, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 12, 11890, 3844, 20, 1182, 16, 2254, 3844, 21, 1182, 16, 1758, 358, 16, 1731, 745, 892, 501, 13, 3903, 225, 2176, 288, 203, 3639, 2583, 12, 8949, 20, 1182, 405, 374, 747, 3844, 21, 1182, 405, 374, 16, 296, 1682, 15506, 14245, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 15527, 67, 2192, 51, 5321, 8284, 203, 3639, 2583, 12, 8949, 20, 1182, 411, 389, 455, 6527, 20, 597, 3844, 21, 1182, 411, 389, 455, 6527, 21, 16, 296, 1682, 15506, 14245, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 8284, 203, 203, 3639, 2254, 11013, 20, 31, 203, 3639, 2254, 11013, 21, 31, 203, 3639, 1758, 389, 2316, 20, 273, 1147, 20, 31, 203, 3639, 1758, 389, 2316, 21, 273, 1147, 21, 31, 203, 3639, 2583, 12, 869, 480, 389, 2316, 20, 597, 358, 480, 389, 2316, 21, 16, 296, 1682, 15506, 14245, 30, 10071, 67, 4296, 8284, 203, 3639, 309, 261, 892, 18, 2469, 405, 374, 13, 467, 1682, 15506, 14245, 3005, 11182, 12, 869, 2934, 298, 15506, 14245, 1477, 12, 3576, 18, 15330, 16, 3844, 20, 1182, 16, 3844, 21, 1182, 16, 501, 1769, 203, 3639, 11013, 20, 273, 467, 654, 39, 3462, 24899, 2316, 20, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 11013, 21, 273, 467, 654, 39, 3462, 24899, 2316, 21, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 289, 203, 3639, 2254, 3844, 20, 382, 273, 11013, 20, 405, 389, 455, 6527, 20, 300, 3844, 2 ]
./full_match/295/0x0000000000000000000000000000000000233233/sources/HederaTokenService.sol
Operation to grant kyc to token account @param token The token address @param account The account address to grant kyc @return responseCode The response code for the status of the request. SUCCESS is 22.
function grantTokenKyc(address token, address account) internal returns (int64 responseCode){ (bool success, bytes memory result) = precompileAddress.call( abi.encodeWithSelector(IHederaTokenService.grantTokenKyc.selector, token, account)); (responseCode) = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN; }
4,664,481
[ 1, 2988, 358, 7936, 417, 93, 71, 358, 1147, 2236, 225, 1147, 1021, 1147, 1758, 225, 2236, 1021, 2236, 1758, 358, 7936, 417, 93, 71, 327, 20407, 1021, 766, 981, 364, 326, 1267, 434, 326, 590, 18, 16561, 353, 11201, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7936, 1345, 47, 93, 71, 12, 2867, 1147, 16, 1758, 2236, 13, 2713, 1135, 261, 474, 1105, 20407, 15329, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 563, 13, 273, 675, 11100, 1887, 18, 1991, 12, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 45, 44, 329, 6070, 1345, 1179, 18, 16243, 1345, 47, 93, 71, 18, 9663, 16, 1147, 16, 2236, 10019, 203, 3639, 261, 2740, 1085, 13, 273, 2216, 692, 24126, 18, 3922, 12, 2088, 16, 261, 474, 1578, 3719, 294, 670, 329, 6070, 1064, 6295, 18, 14737, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-16 */ // Sources flattened with hardhat v2.9.1 https://hardhat.org // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] // 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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/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 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); /** * @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-upgradeable/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @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 onlyInitializing { } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } // 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(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[46] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable { function __ERC721URIStorage_init() internal onlyInitializing { } function __ERC721URIStorage_init_unchained() internal onlyInitializing { } 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]; } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/security/[email protected] // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal onlyInitializing { } function __ERC721Burnable_init_unchained() internal onlyInitializing { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/interfaces/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // File @openzeppelin/contracts-upgradeable/proxy/beacon/[email protected] // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // File @openzeppelin/contracts-upgradeable/proxy/ERC1967/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File @openzeppelin/contracts-upgradeable/utils/cryptography/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProofUpgradeable { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File contracts/TuttleTribe.sol pragma solidity ^0.8.4; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract TuttleTribeV2 is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, PausableUpgradeable, OwnableUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; address proxyRegistryAddress; uint256 basePrice; uint256 _totalSupply; uint256 _wlSupply; bytes32 merkleRoot; bool _wlMint; bool _publicMint; mapping (address => bool) public teamMinters; mapping (address => bool) public dayOfMinters; CountersUpgradeable.Counter private _tokenIdCounter; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() initializer public { __ERC721_init("Tuttle Tribe", "TUTT"); __ERC721Enumerable_init(); __ERC721URIStorage_init(); __Pausable_init(); __Ownable_init(); __ERC721Burnable_init(); __UUPSUpgradeable_init(); address _proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; proxyRegistryAddress = _proxyRegistryAddress; basePrice = 50000000000000000; _totalSupply = 3050; _wlSupply = 2500; _tokenIdCounter.increment(); _wlMint = false; _publicMint = false; // initial 80 to team wallet for(uint256 i=0; i< 80; i++){ uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(0x6fBe1EaF0fc2b2D8ffe10Fbe951aF2dA7dA3f1bF, tokenId); } } function wlMint(uint256 count, bytes32[] calldata proof) public payable { require(_wlMint == true, 'MINTING NOT YET STARTED'); require(count <= 5, 'MAX 5 PER TRANSACTION'); if(teamMinters[msg.sender] == true) { uint256 tokenId = _tokenIdCounter.current(); require(tokenId <= _wlSupply); _tokenIdCounter.increment(); _safeMint(msg.sender, tokenId); teamMinters[msg.sender] = false; uint256 _count = msg.value / basePrice; for(uint256 i=0; i< _count; i++) { uint256 tkenId = _tokenIdCounter.current(); require(tkenId <= _wlSupply); _tokenIdCounter.increment(); _safeMint(msg.sender, tkenId); } return; } else require(msg.value >= basePrice * count, 'INCREASE PAYMENT TO MINT'); require(count >= 1, 'DONT DRINK UNNEEDED GAS'); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProofUpgradeable.verify(proof, merkleRoot, leaf),'NOT ON ALLOWLIST'); for(uint256 i=0; i< count; i++){ uint256 tokenId = _tokenIdCounter.current(); require(tokenId <= _wlSupply); _tokenIdCounter.increment(); _safeMint(msg.sender, tokenId); } } function batchMint(uint256 count) public payable { require(_publicMint == true, 'PUBLIC MINTING NOT YET STARTED'); if(teamMinters[msg.sender] == true) { uint256 tokenId = _tokenIdCounter.current(); require(tokenId <= _wlSupply); _tokenIdCounter.increment(); _safeMint(msg.sender, tokenId); teamMinters[msg.sender] = false; uint256 _count = msg.value / basePrice; for(uint256 i=0; i< _count; i++) { uint256 tkenId = _tokenIdCounter.current(); require(tkenId <= _wlSupply); _tokenIdCounter.increment(); _safeMint(msg.sender, tkenId); } return; } else require(count <= 5, 'MAX 5 PER TRANSACTION'); require(msg.value >= basePrice * count, 'INCREASE PAYMENT TO MINT'); for(uint256 i=0; i< count; i++){ uint256 tokenId = _tokenIdCounter.current(); require(tokenId <= _totalSupply); _tokenIdCounter.increment(); _safeMint(msg.sender, tokenId); } } function addTeamMinters(address[] calldata users) public onlyOwner { for (uint i = 0; i < users.length; i++) { teamMinters[users[i]] = true; } } function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } function commenceWlMint() public onlyOwner { _wlMint = true; } function commencePublicMint() public onlyOwner { _publicMint = true; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } function currentToken() public view returns (uint256) { uint256 currentNFT = _tokenIdCounter.current(); return currentNFT; } function _baseURI() internal pure override returns (string memory) { return "https://api.goatkeepers.sh/v1/tuttle/metadata/"; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function _authorizeUpgrade(address newImplementation) internal onlyOwner override {} // The following functions are overrides required by Solidity. function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function withdrawAll() public { uint256 amount = address(this).balance; require(payable(owner()).send(amount)); } }
initial 80 to team wallet
function initialize() initializer public { __ERC721_init("Tuttle Tribe", "TUTT"); __ERC721Enumerable_init(); __ERC721URIStorage_init(); __Pausable_init(); __Ownable_init(); __ERC721Burnable_init(); __UUPSUpgradeable_init(); address _proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; proxyRegistryAddress = _proxyRegistryAddress; basePrice = 50000000000000000; _totalSupply = 3050; _wlSupply = 2500; _tokenIdCounter.increment(); _wlMint = false; _publicMint = false; for(uint256 i=0; i< 80; i++){ uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(0x6fBe1EaF0fc2b2D8ffe10Fbe951aF2dA7dA3f1bF, tokenId); } }
1,963,747
[ 1, 6769, 8958, 358, 5927, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4046, 1435, 12562, 1071, 288, 203, 3639, 1001, 654, 39, 27, 5340, 67, 2738, 2932, 56, 322, 5929, 840, 495, 73, 3113, 315, 56, 57, 1470, 8863, 203, 3639, 1001, 654, 39, 27, 5340, 3572, 25121, 67, 2738, 5621, 203, 3639, 1001, 654, 39, 27, 5340, 3098, 3245, 67, 2738, 5621, 203, 3639, 1001, 16507, 16665, 67, 2738, 5621, 203, 3639, 1001, 5460, 429, 67, 2738, 5621, 203, 3639, 1001, 654, 39, 27, 5340, 38, 321, 429, 67, 2738, 5621, 203, 3639, 1001, 57, 3079, 55, 10784, 429, 67, 2738, 5621, 203, 3639, 1758, 389, 5656, 4243, 1887, 273, 374, 6995, 6564, 5908, 557, 29, 8204, 39, 10261, 39, 23, 74, 5082, 29, 5292, 28, 70, 378, 2226, 37, 27, 71, 5292, 5528, 38, 20, 4700, 71, 21, 31, 203, 3639, 2889, 4243, 1887, 273, 389, 5656, 4243, 1887, 31, 203, 3639, 1026, 5147, 273, 1381, 12648, 12648, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 5196, 3361, 31, 203, 3639, 389, 21504, 3088, 1283, 273, 6969, 713, 31, 203, 3639, 389, 2316, 548, 4789, 18, 15016, 5621, 203, 3639, 389, 21504, 49, 474, 273, 629, 31, 203, 3639, 389, 482, 49, 474, 273, 629, 31, 203, 3639, 364, 12, 11890, 5034, 277, 33, 20, 31, 277, 32, 8958, 31, 277, 27245, 95, 203, 5411, 2254, 5034, 1147, 548, 273, 389, 2316, 548, 4789, 18, 2972, 5621, 203, 5411, 389, 2316, 548, 4789, 18, 15016, 5621, 203, 5411, 389, 4626, 49, 474, 12, 20, 92, 26, 74, 1919, 21, 41, 69, 42, 2 ]
pragma solidity ^0.5.0; import "../helpers/openzeppelin-solidity/math/SafeMath.sol"; import "../helpers/openzeppelin-solidity/token/ERC20/IERC20.sol"; import "../modules/Countdown.sol"; import "../modules/Griefing.sol"; import "../modules/Metadata.sol"; import "../modules/Operated.sol"; import "../modules/Template.sol"; /* Agreement between two stakers * - each staker has the ability to grief each other * * NOTE: * - This top level contract should only perform access control and state transitions * */ contract TwoWayGriefing is Countdown, Griefing, Metadata, Operated, Template { using SafeMath for uint256; Data private _data; struct Data { address stakerA; address stakerB; } function initialize( address token, address operator, bytes memory stakeDataA, bytes memory stakeDataB, uint256 countdownLength, bytes memory staticMetadata ) public initializeTemplate() { // decode staker data (address stakerA, uint256 ratioA, Griefing.RatioType ratioTypeA) = abi.decode(stakeDataA, (address, uint256, Griefing.RatioType)); (address stakerB, uint256 ratioB, Griefing.RatioType ratioTypeB) = abi.decode(stakeDataB, (address, uint256, Griefing.RatioType)); // set storage values _data.stakerA = stakerA; _data.stakerB = stakerB; // set griefing ratio Griefing._setRatio(stakerA, ratioA, ratioTypeA); Griefing._setRatio(stakerB, ratioB, ratioTypeB); // set operator if (operator != address(0)) { Operated._setOperator(operator); Operated._activateOperator(); } // set token used for staking Staking._setToken(token); // set countdown length Countdown._setLength(countdownLength); // set static metadata Metadata._setStaticMetadata(staticMetadata); } // state functions function setVariableMetadata(bytes memory variableMetadata) public { // restrict access require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator"); // update metadata Metadata._setVariableMetadata(variableMetadata); } function increaseStake(address staker, uint256 currentStake, uint256 amountToAdd) public { // check if valid staker input require(isStaker(staker), "only registered staker"); // restrict access require(staker == msg.sender || Operated.isActiveOperator(msg.sender), "only staker or active operator"); // require agreement is not ended require(!Countdown.isOver(), "agreement ended"); // add stake from msg.sender Staking._addStake(staker, msg.sender, currentStake, amountToAdd); } function punish(address target, uint256 currentStake, uint256 punishment, bytes memory message) public returns (uint256 cost) { // check if valid target input require(isStaker(target), "only registered staker"); // only counterparty or operator can grief target address counterparty = getCounterparty(target); // restrict access - NOTE: currently allows to grief self require(msg.sender == counterparty || Operated.isActiveOperator(msg.sender), "only staker or active operator"); // require agreement is not ended require(!Countdown.isOver(), "agreement ended"); // execute griefing from msg.sender cost = Griefing._grief(msg.sender, target, currentStake, punishment, message); } function startCountdown() public returns (uint256 deadline) { // restrict access require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator"); // require countdown is not started require(Deadline.getDeadline() == 0, "deadline already set"); // start countdown deadline = Countdown._start(); } function retrieveStake(address staker, address recipient) public returns (uint256 amount) { // check if valid staker input require(isStaker(staker), "only registered staker"); // restrict access require(staker == msg.sender || Operated.isActiveOperator(msg.sender), "only staker or active operator"); // require deadline is passed require(Deadline.isAfterDeadline(),"deadline not passed"); // retrieve stake amount = Staking._takeFullStake(staker, recipient); } // view functions function isStaker(address caller) public view returns (bool ok) { // returns true if caller is one of the registered stakers ok = (caller == _data.stakerA || caller == _data.stakerB); } function getStakers() public view returns (address stakerA, address stakerB) { stakerA = _data.stakerA; stakerB = _data.stakerB; } function getCounterparty(address caller) public view returns (address counterparty) { // if stakerA, return stakerB // if stakerB, return stakerA if (_data.stakerA == caller) { return _data.stakerB; } else if (_data.stakerB == caller) { return _data.stakerA; } // don't revert when `caller` is not a staker // just return empty address and allow higher level functions // to do error-handling with isStaker return address(0); } }
if stakerA, return stakerB if stakerB, return stakerA
function getCounterparty(address caller) public view returns (address counterparty) { if (_data.stakerA == caller) { return _data.stakerB; return _data.stakerA; } }
12,589,634
[ 1, 430, 384, 6388, 37, 16, 327, 384, 6388, 38, 309, 384, 6388, 38, 16, 327, 384, 6388, 37, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 31107, 21214, 12, 2867, 4894, 13, 1071, 1476, 1135, 261, 2867, 3895, 21214, 13, 288, 203, 3639, 309, 261, 67, 892, 18, 334, 6388, 37, 422, 4894, 13, 288, 203, 5411, 327, 389, 892, 18, 334, 6388, 38, 31, 203, 5411, 327, 389, 892, 18, 334, 6388, 37, 31, 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 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 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; } } // ---------------------------------------------------------------------------- // contract WhiteListAccess // ---------------------------------------------------------------------------- contract WhiteListAccess { function WhiteListAccess() public { owner = msg.sender; whitelist[owner] = true; whitelist[address(this)] = true; } address public owner; mapping (address => bool) whitelist; modifier onlyOwner {require(msg.sender == owner); _;} modifier onlyWhitelisted {require(whitelist[msg.sender]); _;} function addToWhiteList(address trusted) public onlyOwner() { whitelist[trusted] = true; } function removeFromWhiteList(address untrusted) public onlyOwner() { whitelist[untrusted] = false; } } // ---------------------------------------------------------------------------- // 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); } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract _Token is WhiteListAccess, _ERC20Interface { using _SafeMath for uint; uint8 public decimals; uint public totSupply; string public symbol; string public name; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function _Token(string _name, string _sym) public { symbol = _sym; name = _name; decimals = 0; totSupply = 0; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totSupply; } // ------------------------------------------------------------------------ // 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) { require(!freezed); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function desapprove(address spender) public returns (bool success) { allowed[msg.sender][spender] = 0; 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(!freezed); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // FLC API // ------------------------------------------------------------------------ bool freezed; function create(uint units) public onlyWhitelisted() { totSupply = totSupply + units; balances[msg.sender] = balances[msg.sender] + units; } function freeze() public onlyWhitelisted() { freezed = true; } function unfreeze() public onlyWhitelisted() { freezed = false; } } contract FourLeafClover is _Token("Four Leaf Clover", "FLC") { function FourLeafClover() public {} }
------------------------------------------------------------------------ Get the _token balance for account `_tokenOwner` ------------------------------------------------------------------------
function balanceOf(address _tokenOwner) public constant returns (uint balance) { return balances[_tokenOwner]; }
1,422,489
[ 1, 29461, 968, 326, 389, 2316, 11013, 364, 2236, 1375, 67, 2316, 5541, 68, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 12, 2867, 389, 2316, 5541, 13, 1071, 5381, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 67, 2316, 5541, 15533, 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 ]
pragma solidity ^0.4.17; // source : https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md contract ERC20Interface { function transfer(address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); } contract WeaponTokenize { /* State variables */ address public owner; uint[] weaponList; address[] authorizedOwners; /* mappings */ mapping (uint => string) gameDataOf; mapping (uint => string) publicDataOf; mapping (uint => string) ownerDataOf; mapping (uint => address) ownerOf; mapping (address => bool) isAuthorizedOwner; /* Events */ event WeaponAdded(uint indexed weaponId, string gameData, string publicData, string ownerData); event WeaponUpdated(uint indexed weaponId, string gameData, string publicData, string ownerData); event OwnershipTransferred(address indexed _oldOwner, address indexed _newOwner); event WeaponOwnerUpdated (uint indexed _weaponId, address indexed _oldOwner, address indexed _newOwner); event AuthorizedOwnerAdded(address indexed _addeduthorizedOwner); event AuthorizedOwnerRemoved(address indexed _removedAuthorizedOwner); /* Modifiers */ modifier onlyOwnerOfContract() { require(msg.sender == owner); _; } modifier onlyAuthorizedOwner() { require(isAuthorizedOwner[msg.sender]); _; } /* constructor */ function WeaponTokenize () public { owner = msg.sender; isAuthorizedOwner[msg.sender] = true; authorizedOwners.push(msg.sender); } ////////////////////////////////////////// // OWNER SPECIFIC FUNCTIONS ////////////////////////////////////////// /* Add authrized owners */ function addAuthorizedOwners (address _newAuthorizedUser) public onlyOwnerOfContract returns(bool res) { require(!isAuthorizedOwner[_newAuthorizedUser]); isAuthorizedOwner[_newAuthorizedUser] = true; authorizedOwners.push(_newAuthorizedUser); emit AuthorizedOwnerAdded(_newAuthorizedUser); return true; } /* Remove authorized users */ function removeAuthorizeduser(address _authorizedUser) public onlyOwnerOfContract returns(bool res){ require(isAuthorizedOwner[_authorizedUser]); delete(isAuthorizedOwner[_authorizedUser]); for(uint i=0; i< authorizedOwners.length;i++){ if(authorizedOwners[i] == _authorizedUser){ delete authorizedOwners[i]; break; } } emit AuthorizedOwnerRemoved(_authorizedUser); return true; } /* Change ownership */ function transferOwnership (address _newOwner) public onlyOwnerOfContract returns(bool res) { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address _tokenAddress, uint _value) public onlyOwnerOfContract returns (bool success) { return ERC20Interface(_tokenAddress).transfer(owner, _value); } ////////////////////////////////////////// // AUTHORIZEED USERS FUNCTIONALITY ////////////////////////////////////////// /* Add weapon */ function addWeapon (uint _id, string _gameData, string _publicData, string _ownerData, address _ownerAddrress) public onlyAuthorizedOwner returns(bool res) { gameDataOf[_id] = _gameData; publicDataOf[_id] = _publicData; ownerDataOf[_id] = _ownerData; ownerOf[_id] = _ownerAddrress; weaponList.push(_id); emit WeaponAdded(_id, _gameData, _publicData, _ownerData); return true; } /* update all weapon details */ function updateWeapon (uint _id, string _gameData, string _publicData, string _ownerData) public onlyAuthorizedOwner returns(bool res) { gameDataOf[_id] = _gameData; publicDataOf[_id] = _publicData; ownerDataOf[_id] = _ownerData; //emit WeaponAdded(_id, _gameData, _publicData, _ownerData); return true; } /* update game proprietary data */ function updateGameProprietaryData (uint _id, string _gameData) public onlyAuthorizedOwner returns(bool res) { gameDataOf[_id] = _gameData; emit WeaponUpdated(_id, _gameData, "", ""); return true; } /* update public data */ function updatePublicData (uint _id, string _publicData) public onlyAuthorizedOwner returns(bool res) { publicDataOf[_id] = _publicData; emit WeaponUpdated(_id, "", _publicData, ""); return true; } /* update owner proprietary data */ function updateOwnerProprietaryData (uint _id, string _ownerData) public onlyAuthorizedOwner returns(bool res) { ownerDataOf[_id] = _ownerData; emit WeaponUpdated(_id, "", "", _ownerData); return true; } /* change owner of weapon */ function updateOwnerOfWeapon (uint _id, address _newOwner) public onlyAuthorizedOwner returns(bool res) { address oldOwner = ownerOf[_id]; ownerOf[_id] = _newOwner; emit WeaponOwnerUpdated(_id, oldOwner, _newOwner); return true; } ////////////////////////////////////////// // PUBLICLY ACCESSIBLE METHODS (CONSTANT) ////////////////////////////////////////// /* Get Weapon Data */ function getGameProprietaryData (uint _id) public view returns(string _gameData) { return gameDataOf[_id]; } function getPublicData (uint _id) public view returns(string _pubicData) { return publicDataOf[_id]; } function getOwnerProprietaryData (uint _id) public view returns(string _ownerData) { return ownerDataOf[_id] ; } function getAllWeaponData (uint _id) public view returns(string _gameData,string _pubicData,string _ownerData ) { return (gameDataOf[_id], publicDataOf[_id], ownerDataOf[_id]); } function getOwnerOf (uint _weaponId) public view returns(address _owner) { return ownerOf[_weaponId]; } function getWeaponList () public view returns(uint[] tokenizedWeapons) { return weaponList; } function getAuthorizedOwners () public view returns(address[] authorizedUsers) { return authorizedOwners; } // ------------------------------------------------------------------------ // Prevents contract from accepting ETH // ------------------------------------------------------------------------ function () public payable { revert(); } }
update public data */
function updatePublicData (uint _id, string _publicData) public onlyAuthorizedOwner returns(bool res) { publicDataOf[_id] = _publicData; emit WeaponUpdated(_id, "", _publicData, ""); return true; }
2,538,410
[ 1, 2725, 1071, 501, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 4782, 751, 261, 11890, 389, 350, 16, 225, 533, 389, 482, 751, 13, 1071, 1338, 15341, 5541, 1135, 12, 6430, 400, 13, 288, 203, 1377, 1071, 751, 951, 63, 67, 350, 65, 273, 389, 482, 751, 31, 203, 1377, 3626, 1660, 28629, 7381, 24899, 350, 16, 23453, 389, 482, 751, 16, 1408, 1769, 203, 1377, 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 ]
./full_match/56/0x10445390D5Bd1Fff365f2fB5Cd2E02f71A513f89/sources/project_/contracts/ourToken.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./
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
3,225,918
[ 1, 8924, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 2525, 805, 16, 326, 3410, 2236, 903, 506, 326, 1245, 716, 5993, 383, 1900, 326, 6835, 18, 1220, 848, 5137, 506, 3550, 598, 288, 13866, 5460, 12565, 5496, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 353, 1772, 288, 203, 225, 1758, 3238, 389, 8443, 31, 203, 203, 225, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 225, 3885, 1832, 2713, 288, 203, 565, 1758, 1234, 12021, 273, 389, 3576, 12021, 5621, 203, 565, 389, 8443, 273, 1234, 12021, 31, 203, 225, 289, 203, 203, 225, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 565, 327, 389, 8443, 31, 203, 225, 289, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 24899, 8443, 422, 389, 3576, 12021, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 1654, 8386, 5460, 12565, 1435, 1071, 1338, 5541, 288, 203, 565, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 565, 389, 8443, 273, 1758, 12, 20, 1769, 203, 225, 289, 203, 203, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 565, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 5460, 429, 30, 394, 3410, 353, 326, 3634, 1758, 8863, 203, 565, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 394, 5541, 1769, 203, 565, 389, 8443, 273, 394, 5541, 31, 203, 225, 289, 203, 97, 203, 2, -100, -100 ]
./partial_match/4/0xE5b4Cda4dCC0bE5BEA97dDbEE9B584CB7f1ab1ae/sources/coffer_Factory.sol
Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { if (deprecated) { return UpgradedStandardToken_CT(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); return super.approve(_spender, _value); } }
8,523,040
[ 1, 8514, 4232, 39, 3462, 2590, 358, 31049, 6835, 309, 333, 1245, 353, 6849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 389, 1132, 13, 1071, 1338, 6110, 1225, 12, 22, 380, 3847, 13, 288, 203, 3639, 309, 261, 14089, 13, 288, 203, 5411, 327, 1948, 19305, 8336, 1345, 67, 1268, 12, 416, 19305, 1887, 2934, 12908, 537, 858, 12235, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 1132, 1769, 203, 5411, 327, 2240, 18, 12908, 537, 24899, 87, 1302, 264, 16, 389, 1132, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IKeep3rV1Oracle { function sample(address tokenIn, uint amountIn, address tokenOut, uint points, uint window) external view returns (uint[] memory); function current(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut); } interface IERC20 { function decimals() external view returns (uint); } contract Keep3rV1Volatility { uint private constant FIXED_1 = 0x080000000000000000000000000000000; uint private constant FIXED_2 = 0x100000000000000000000000000000000; uint private constant SQRT_1 = 13043817825332782212; uint private constant LNX = 3988425491; uint private constant LOG_10_2 = 3010299957; uint private constant LOG_E_2 = 6931471806; uint private constant BASE = 1e10; IKeep3rV1Oracle public constant KV1O = IKeep3rV1Oracle(0x73353801921417F465377c8d898c6f4C0270282C); address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (uint(1) << s)) { _n >>= s; res |= s; } } } return res; } function ln(uint256 x) internal pure returns (uint) { uint res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = 127; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += uint(1) << (i - 1); } } } return res * LOG_E_2 / BASE; } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = (z * y) / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = (res * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = (res * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = (res * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = (res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = (res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = (res * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = (res * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } function quote(address tokenIn, address tokenOut, uint t) public view returns (uint call, uint put) { uint price = KV1O.current(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut); return quotePrice(tokenIn, tokenOut, t, price, price); } function price(address tokenIn, address tokenOut) public view returns (uint) { if (tokenIn == WETH) { return KV1O.current(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut); } else { uint _weth = KV1O.current(tokenIn, 1e18, WETH); return KV1O.current(WETH, _weth, tokenOut); } } function quotePrice(address tokenIn, address tokenOut, uint t, uint sp, uint st) public view returns (uint call, uint put) { uint v = rVol(tokenIn, tokenOut, 4, 24); return quoteAll(t, v, sp, st); } function quoteAll(uint t, uint v, uint sp, uint st) public pure returns (uint call, uint put) { uint _c; uint _p; if (sp > st) { _c = C(t, v, sp, st); _p = st-sp+_c; } else { _p = C(t, v, st, sp); _c = st-sp+_p; } return (_c, _p); } function C(uint t, uint v, uint sp, uint st) public pure returns (uint) { if (sp == st) { return LNX * sp / 1e10 * v / 1e18 * sqrt(1e18 * t / 365) / 1e9; } uint sigma = ((v**2)/2); uint sigmaB = 1e36; uint sig = 1e18 * sigma / sigmaB * t / 365; uint sSQRT = v * sqrt(1e18 * t / 365) / 1e9; uint d1 = 1e18 * ln(FIXED_1 * sp / st) / FIXED_1; d1 = (d1 + sig) * 1e18 / sSQRT; uint d2 = d1 - sSQRT; uint cdfD1 = ncdf(FIXED_1 * d1 / 1e18); uint cdfD2 = cdf(int(FIXED_1) * int(d2) / 1e18); return sp * cdfD1 / 1e14 - st * cdfD2 / 1e14; } function ncdf(uint x) internal pure returns (uint) { int t1 = int(1e7 + (2315419 * x / FIXED_1)); uint exp = x / 2 * x / FIXED_1; int d = int(3989423 * FIXED_1 / optimalExp(uint(exp))); uint prob = uint(d * (3193815 + ( -3565638 + (17814780 + (-18212560 + 13302740 * 1e7 / t1) * 1e7 / t1) * 1e7 / t1) * 1e7 / t1) * 1e7 / t1); if( x > 0 ) prob = 1e14 - prob; return prob; } /** * @notice Takes the absolute value of a given number * @dev Helper function * @param _number The specified number * @return The absolute value of the number */ function abs(int256 _number) private pure returns (uint256) { return _number < 0 ? uint256(_number * (-1)) : uint256(_number); } function cdf(int x) internal pure returns (uint) { int t1 = int(1e7 + int(2315419 * abs(x) / FIXED_1)); uint exp = uint(x / 2 * x) / FIXED_1; int d = int(3989423 * FIXED_1 / optimalExp(uint(exp))); uint prob = uint(d * (3193815 + ( -3565638 + (17814780 + (-18212560 + 13302740 * 1e7 / t1) * 1e7 / t1) * 1e7 / t1) * 1e7 / t1) * 1e7 / t1); if( x > 0 ) prob = 1e14 - prob; return prob; } function generalLog(uint256 x) internal pure returns (uint) { uint res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = 127; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += uint(1) << (i - 1); } } } return res * LOG_10_2 / BASE; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function vol(uint[] memory p) public pure returns (uint x) { for (uint8 i = 1; i <= (p.length-1); i++) { x += ((generalLog(p[i] * FIXED_1) - generalLog(p[i-1] * FIXED_1)))**2; //denom += FIXED_1**2; } //return (sum, denom); x = sqrt(uint(252) * sqrt(x / (p.length-1))); return uint(1e18) * x / SQRT_1; } function rVol(address tokenIn, address tokenOut, uint points, uint window) public view returns (uint) { return vol(KV1O.sample(tokenIn, uint(10)**IERC20(tokenIn).decimals(), tokenOut, points, window)); } function rVolHourly(address tokenIn, address tokenOut, uint points) external view returns (uint) { return rVol(tokenIn, tokenOut, points, 2); } function rVolDaily(address tokenIn, address tokenOut, uint points) external view returns (uint) { return rVol(tokenIn, tokenOut, points, 48); } function rVolWeekly(address tokenIn, address tokenOut, uint points) external view returns (uint) { return rVol(tokenIn, tokenOut, points, 336); } function rVolHourlyRecent(address tokenIn, address tokenOut) external view returns (uint) { return rVol(tokenIn, tokenOut, 2, 2); } function rVolDailyRecent(address tokenIn, address tokenOut) external view returns (uint) { return rVol(tokenIn, tokenOut, 2, 48); } function rVolWeeklyRecent(address tokenIn, address tokenOut) external view returns (uint) { return rVol(tokenIn, tokenOut, 2, 336); } }
denom += FIXED_1**2;
function vol(uint[] memory p) public pure returns (uint x) { for (uint8 i = 1; i <= (p.length-1); i++) { x += ((generalLog(p[i] * FIXED_1) - generalLog(p[i-1] * FIXED_1)))**2; } return uint(1e18) * x / SQRT_1; }
41,278
[ 1, 13002, 362, 1011, 26585, 67, 2138, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6626, 12, 11890, 8526, 3778, 293, 13, 1071, 16618, 1135, 261, 11890, 619, 13, 288, 203, 3639, 364, 261, 11890, 28, 277, 273, 404, 31, 277, 1648, 261, 84, 18, 2469, 17, 21, 1769, 277, 27245, 288, 203, 5411, 619, 1011, 14015, 12259, 1343, 12, 84, 63, 77, 65, 380, 26585, 67, 21, 13, 300, 7470, 1343, 12, 84, 63, 77, 17, 21, 65, 380, 26585, 67, 21, 20349, 636, 22, 31, 203, 3639, 289, 203, 3639, 327, 2254, 12, 21, 73, 2643, 13, 380, 619, 342, 348, 53, 12185, 67, 21, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IStdReference.sol"; contract Lottery is Ownable { address payable[] public players; address payable public recentWinner; uint256 public randomness; uint256 public usdEntryFee; IStdReference bandRef; event PlayerEntered(address player, uint256 bet); event LotteryEnded(address winner, uint256 prize); enum LOTTERY_STATE { OPEN, CLOSED, CALCULATING_WINNER } LOTTERY_STATE public lottery_state; constructor(IStdReference _bandRef) { usdEntryFee = 50 * 1e18; lottery_state = LOTTERY_STATE.CLOSED; bandRef = _bandRef; } // _usdEntryFee is USD with 8 decimals function setUsdEntryFee(uint256 _usdEntryFee) public onlyOwner { require( lottery_state == LOTTERY_STATE.CLOSED, "Lottery is not closed." ); usdEntryFee = _usdEntryFee * 1e10; } function getPrice() private view returns (uint256) { // Get price feed from BAND Protocol IStdReference.ReferenceData memory data = bandRef.getReferenceData( "ETH", "USD" ); // BRAND protocol returns 9 decimals // multiplier: 1000000000 = 1e9 return data.rate; } function enter() public payable { require(lottery_state == LOTTERY_STATE.OPEN, "Lottery is not open."); require(msg.value >= getEntranceFee(), "Not enough ETH."); players.push(payable(msg.sender)); emit PlayerEntered(msg.sender, msg.value); } function getEntranceFee() public view returns (uint256) { uint256 price = getPrice(); uint256 ajustedPrice = uint256(price); // BAND returns 9 decimals but we need 18 uint256 costToEnter = (usdEntryFee * 1e18) / ajustedPrice; return costToEnter; } function startLottery() public onlyOwner { require( lottery_state == LOTTERY_STATE.CLOSED, "Lottery is not closed." ); lottery_state = LOTTERY_STATE.OPEN; } function endLottery() public onlyOwner { require(lottery_state == LOTTERY_STATE.OPEN, "Lottery is not open."); lottery_state = LOTTERY_STATE.CALCULATING_WINNER; // [MOCK] Generate randomness // uint256 _randomness = _unsafePseudoRandom(); uint256 _randomness = 1; // Pick winner require(_randomness > 0, "random not found"); uint256 indexOfWinner = _randomness % players.length; randomness = _randomness; recentWinner = players[indexOfWinner]; // Transfer emit LotteryEnded(recentWinner, address(this).balance); recentWinner.transfer(address(this).balance); // Reset the lottery players = new address payable[](0); lottery_state = LOTTERY_STATE.CLOSED; } // [WARN] This is not the recommended way to generate // random numbers. DO NOT USE IN PRODUCTION ENVIRONMENTS. // I'm using it here because BAND does not offer // randomness yet function _unsafePseudoRandom() private view returns (uint256) { // sha3 and now have been deprecated return uint256( keccak256( abi.encodePacked(block.difficulty, block.timestamp, players) ) ); // convert hash to integer // players is an array of entrants } }
[MOCK] Generate randomness uint256 _randomness = _unsafePseudoRandom(); Pick winner Transfer Reset the lottery
function endLottery() public onlyOwner { require(lottery_state == LOTTERY_STATE.OPEN, "Lottery is not open."); lottery_state = LOTTERY_STATE.CALCULATING_WINNER; uint256 _randomness = 1; require(_randomness > 0, "random not found"); uint256 indexOfWinner = _randomness % players.length; randomness = _randomness; recentWinner = players[indexOfWinner]; emit LotteryEnded(recentWinner, address(this).balance); recentWinner.transfer(address(this).balance); players = new address payable[](0); lottery_state = LOTTERY_STATE.CLOSED; }
2,528,337
[ 1, 63, 5980, 3507, 65, 6654, 2744, 4496, 2254, 5034, 389, 9188, 4496, 273, 389, 318, 4626, 26716, 8529, 5621, 23038, 5657, 1224, 12279, 7151, 326, 17417, 387, 93, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 679, 48, 352, 387, 93, 1435, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 23372, 387, 93, 67, 2019, 422, 1806, 1470, 8404, 67, 7998, 18, 11437, 16, 315, 48, 352, 387, 93, 353, 486, 1696, 1199, 1769, 203, 3639, 17417, 387, 93, 67, 2019, 273, 1806, 1470, 8404, 67, 7998, 18, 7913, 39, 1506, 28054, 67, 24572, 12196, 31, 203, 203, 3639, 2254, 5034, 389, 9188, 4496, 273, 404, 31, 203, 203, 3639, 2583, 24899, 9188, 4496, 405, 374, 16, 315, 9188, 486, 1392, 8863, 203, 3639, 2254, 5034, 3133, 59, 7872, 273, 389, 9188, 4496, 738, 18115, 18, 2469, 31, 203, 3639, 2744, 4496, 273, 389, 9188, 4496, 31, 203, 3639, 8399, 59, 7872, 273, 18115, 63, 31806, 59, 7872, 15533, 203, 203, 3639, 3626, 511, 352, 387, 93, 28362, 12, 20872, 59, 7872, 16, 1758, 12, 2211, 2934, 12296, 1769, 203, 3639, 8399, 59, 7872, 18, 13866, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 203, 3639, 18115, 273, 394, 1758, 8843, 429, 8526, 12, 20, 1769, 203, 3639, 17417, 387, 93, 67, 2019, 273, 1806, 1470, 8404, 67, 7998, 18, 28475, 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 ]
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * 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.24; /** * @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/AddressUtils.sol pragma solidity ^0.4.24; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/upgradeability/EternalStorage.sol pragma solidity 0.4.24; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/interfaces/IBridgeValidators.sol pragma solidity 0.4.24; interface IBridgeValidators { function isValidator(address _validator) external view returns (bool); function requiredSignatures() external view returns (uint256); function owner() external view returns (address); } // File: contracts/upgradeable_contracts/ValidatorStorage.sol pragma solidity 0.4.24; contract ValidatorStorage { bytes32 internal constant VALIDATOR_CONTRACT = 0x5a74bb7e202fb8e4bf311841c7d64ec19df195fee77d7e7ae749b27921b6ddfe; // keccak256(abi.encodePacked("validatorContract")) } // File: contracts/upgradeable_contracts/Validatable.sol pragma solidity 0.4.24; contract Validatable is EternalStorage, ValidatorStorage { function validatorContract() public view returns (IBridgeValidators) { return IBridgeValidators(addressStorage[VALIDATOR_CONTRACT]); } modifier onlyValidator() { require(validatorContract().isValidator(msg.sender)); /* solcov ignore next */ _; } function requiredSignatures() public view returns (uint256) { return validatorContract().requiredSignatures(); } } // File: contracts/libraries/Message.sol pragma solidity 0.4.24; library Message { function addressArrayContains(address[] array, address value) internal pure returns (bool) { for (uint256 i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; } // layout of message :: bytes: // offset 0: 32 bytes :: uint256 - message length // offset 32: 20 bytes :: address - recipient address // offset 52: 32 bytes :: uint256 - value // offset 84: 32 bytes :: bytes32 - transaction hash // offset 116: 20 bytes :: address - contract address to prevent double spending // mload always reads 32 bytes. // so we can and have to start reading recipient at offset 20 instead of 32. // if we were to read at 32 the address would contain part of value and be corrupted. // when reading from offset 20 mload will read 12 bytes (most of them zeros) followed // by the 20 recipient address bytes and correctly convert it into an address. // this saves some storage/gas over the alternative solution // which is padding address to 32 bytes and reading recipient at offset 32. // for more details see discussion in: // https://github.com/paritytech/parity-bridge/issues/61 function parseMessage(bytes message) internal pure returns (address recipient, uint256 amount, bytes32 txHash, address contractAddress) { require(isMessageValid(message)); assembly { recipient := mload(add(message, 20)) amount := mload(add(message, 52)) txHash := mload(add(message, 84)) contractAddress := mload(add(message, 104)) } } function isMessageValid(bytes _msg) internal pure returns (bool) { return _msg.length == requiredMessageLength(); } function requiredMessageLength() internal pure returns (uint256) { return 104; } function recoverAddressFromSignedMessage(bytes signature, bytes message, bool isAMBMessage) internal pure returns (address) { require(signature.length == 65); bytes32 r; bytes32 s; bytes1 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := mload(add(signature, 0x60)) } require(uint8(v) == 27 || uint8(v) == 28); require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0); return ecrecover(hashMessage(message, isAMBMessage), uint8(v), r, s); } function hashMessage(bytes message, bool isAMBMessage) internal pure returns (bytes32) { bytes memory prefix = "\x19Ethereum Signed Message:\n"; if (isAMBMessage) { return keccak256(abi.encodePacked(prefix, uintToString(message.length), message)); } else { string memory msgLength = "104"; return keccak256(abi.encodePacked(prefix, msgLength, message)); } } /** * @dev Validates provided signatures, only first requiredSignatures() number * of signatures are going to be validated, these signatures should be from different validators. * @param _message bytes message used to generate signatures * @param _signatures bytes blob with signatures to be validated. * First byte X is a number of signatures in a blob, * next X bytes are v components of signatures, * next 32 * X bytes are r components of signatures, * next 32 * X bytes are s components of signatures. * @param _validatorContract contract, which conforms to the IBridgeValidators interface, * where info about current validators and required signatures is stored. * @param isAMBMessage true if _message is an AMB message with arbitrary length. */ function hasEnoughValidSignatures( bytes _message, bytes _signatures, IBridgeValidators _validatorContract, bool isAMBMessage ) internal view { require(isAMBMessage || isMessageValid(_message)); uint256 requiredSignatures = _validatorContract.requiredSignatures(); uint256 amount; assembly { amount := and(mload(add(_signatures, 1)), 0xff) } require(amount >= requiredSignatures); bytes32 hash = hashMessage(_message, isAMBMessage); address[] memory encounteredAddresses = new address[](requiredSignatures); for (uint256 i = 0; i < requiredSignatures; i++) { uint8 v; bytes32 r; bytes32 s; uint256 posr = 33 + amount + 32 * i; uint256 poss = posr + 32 * amount; assembly { v := mload(add(_signatures, add(2, i))) r := mload(add(_signatures, posr)) s := mload(add(_signatures, poss)) } address recoveredAddress = ecrecover(hash, v, r, s); require(_validatorContract.isValidator(recoveredAddress)); require(!addressArrayContains(encounteredAddresses, recoveredAddress)); encounteredAddresses[i] = recoveredAddress; } } function uintToString(uint256 i) internal pure returns (string) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = bytes1(48 + (i % 10)); i /= 10; } return string(bstr); } } // File: contracts/upgradeable_contracts/MessageRelay.sol pragma solidity 0.4.24; contract MessageRelay is EternalStorage { function relayedMessages(bytes32 _txHash) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))]; } function setRelayedMessages(bytes32 _txHash, bool _status) internal { boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))] = _status; } } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.4.24; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.4.24; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner()); /* solcov ignore next */ _; } } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.4.24; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: contracts/upgradeable_contracts/InitializableBridge.sol pragma solidity 0.4.24; contract InitializableBridge is Initializable { bytes32 internal constant DEPLOYED_AT_BLOCK = 0xb120ceec05576ad0c710bc6e85f1768535e27554458f05dcbb5c65b8c7a749b0; // keccak256(abi.encodePacked("deployedAtBlock")) function deployedAtBlock() external view returns (uint256) { return uintStorage[DEPLOYED_AT_BLOCK]; } } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.4.24; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @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 OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner()); /* solcov ignore next */ _; } /** * @dev Throws if called by any account other than contract itself or owner. */ modifier onlyRelevantSender() { // proxy owner if used through proxy, address(0) otherwise require( !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); /* solcov ignore next */ _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[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) external onlyOwner { _setOwner(newOwner); } /** * @dev Sets a new owner address */ function _setOwner(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/upgradeable_contracts/Sacrifice.sol pragma solidity 0.4.24; contract Sacrifice { constructor(address _recipient) public payable { selfdestruct(_recipient); } } // File: contracts/libraries/Address.sol pragma solidity 0.4.24; /** * @title Address * @dev Helper methods for Address type. */ library Address { /** * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract * @param _receiver address that will receive the native tokens * @param _value the amount of native tokens to send */ function safeSendValue(address _receiver, uint256 _value) internal { if (!_receiver.send(_value)) { (new Sacrifice).value(_value)(_receiver); } } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @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/interfaces/ERC677.sol pragma solidity 0.4.24; contract ERC677 is ERC20 { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferAndCall(address, uint256, bytes) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) public returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool); } contract LegacyERC20 { function transfer(address _spender, uint256 _value) public; // returns (bool); function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool); } // File: contracts/libraries/SafeERC20.sol pragma solidity 0.4.24; /** * @title SafeERC20 * @dev Helper methods for safe token transfers. * Functions perform additional checks to be sure that token transfer really happened. */ library SafeERC20 { using SafeMath for uint256; /** * @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _to address of the receiver * @param _value amount of tokens to send */ function safeTransfer(address _token, address _to, uint256 _value) internal { LegacyERC20(_token).transfer(_to, _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } /** * @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _from address of the sender * @param _value amount of tokens to send */ function safeTransferFrom(address _token, address _from, uint256 _value) internal { LegacyERC20(_token).transferFrom(_from, address(this), _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } } // File: contracts/upgradeable_contracts/Claimable.sol pragma solidity 0.4.24; /** * @title Claimable * @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations. */ contract Claimable { using SafeERC20 for address; /** * Throws if a given address is equal to address(0) */ modifier validAddress(address _to) { require(_to != address(0)); /* solcov ignore next */ _; } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimValues(address _token, address _to) internal validAddress(_to) { if (_token == address(0)) { claimNativeCoins(_to); } else { claimErc20Tokens(_token, _to); } } /** * @dev Internal function for withdrawing all native coins from the contract. * @param _to address of the coins receiver. */ function claimNativeCoins(address _to) internal { uint256 value = address(this).balance; Address.safeSendValue(_to, value); } /** * @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract. * @param _token address of the claimed ERC20 token. * @param _to address of the tokens receiver. */ function claimErc20Tokens(address _token, address _to) internal { ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); _token.safeTransfer(_to, balance); } } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.4.24; contract VersionableBridge { function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (6, 1, 0); } /* solcov ignore next */ function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/DecimalShiftBridge.sol pragma solidity 0.4.24; contract DecimalShiftBridge is EternalStorage { using SafeMath for uint256; bytes32 internal constant DECIMAL_SHIFT = 0x1e8ecaafaddea96ed9ac6d2642dcdfe1bebe58a930b1085842d8fc122b371ee5; // keccak256(abi.encodePacked("decimalShift")) /** * @dev Internal function for setting the decimal shift for bridge operations. * Decimal shift can be positive, negative, or equal to zero. * It has the following meaning: N tokens in the foreign chain are equivalent to N * pow(10, shift) tokens on the home side. * @param _shift new value of decimal shift. */ function _setDecimalShift(int256 _shift) internal { // since 1 wei * 10**77 > 2**255, it does not make any sense to use higher values require(_shift > -77 && _shift < 77); uintStorage[DECIMAL_SHIFT] = uint256(_shift); } /** * @dev Returns the value of foreign-to-home decimal shift. * @return decimal shift. */ function decimalShift() public view returns (int256) { return int256(uintStorage[DECIMAL_SHIFT]); } /** * @dev Converts the amount of home tokens into the equivalent amount of foreign tokens. * @param _value amount of home tokens. * @return equivalent amount of foreign tokens. */ function _unshiftValue(uint256 _value) internal view returns (uint256) { return _shiftUint(_value, -decimalShift()); } /** * @dev Converts the amount of foreign tokens into the equivalent amount of home tokens. * @param _value amount of foreign tokens. * @return equivalent amount of home tokens. */ function _shiftValue(uint256 _value) internal view returns (uint256) { return _shiftUint(_value, decimalShift()); } /** * @dev Calculates _value * pow(10, _shift). * @param _value amount of tokens. * @param _shift decimal shift to apply. * @return shifted value. */ function _shiftUint(uint256 _value, int256 _shift) private pure returns (uint256) { if (_shift == 0) { return _value; } if (_shift > 0) { return _value.mul(10**uint256(_shift)); } return _value.div(10**uint256(-_shift)); } } // File: contracts/upgradeable_contracts/BasicBridge.sol pragma solidity 0.4.24; contract BasicBridge is InitializableBridge, Validatable, Ownable, Upgradeable, Claimable, VersionableBridge, DecimalShiftBridge { event GasPriceChanged(uint256 gasPrice); event RequiredBlockConfirmationChanged(uint256 requiredBlockConfirmations); bytes32 internal constant GAS_PRICE = 0x55b3774520b5993024893d303890baa4e84b1244a43c60034d1ced2d3cf2b04b; // keccak256(abi.encodePacked("gasPrice")) bytes32 internal constant REQUIRED_BLOCK_CONFIRMATIONS = 0x916daedf6915000ff68ced2f0b6773fe6f2582237f92c3c95bb4d79407230071; // keccak256(abi.encodePacked("requiredBlockConfirmations")) /** * @dev Public setter for fallback gas price value. Only bridge owner can call this method. * @param _gasPrice new value for the gas price. */ function setGasPrice(uint256 _gasPrice) external onlyOwner { _setGasPrice(_gasPrice); } function gasPrice() external view returns (uint256) { return uintStorage[GAS_PRICE]; } function setRequiredBlockConfirmations(uint256 _blockConfirmations) external onlyOwner { _setRequiredBlockConfirmations(_blockConfirmations); } function _setRequiredBlockConfirmations(uint256 _blockConfirmations) internal { require(_blockConfirmations > 0); uintStorage[REQUIRED_BLOCK_CONFIRMATIONS] = _blockConfirmations; emit RequiredBlockConfirmationChanged(_blockConfirmations); } function requiredBlockConfirmations() external view returns (uint256) { return uintStorage[REQUIRED_BLOCK_CONFIRMATIONS]; } /** * @dev Internal function for updating fallback gas price value. * @param _gasPrice new value for the gas price, zero gas price is allowed. */ function _setGasPrice(uint256 _gasPrice) internal { uintStorage[GAS_PRICE] = _gasPrice; emit GasPriceChanged(_gasPrice); } } // File: contracts/upgradeable_contracts/BasicTokenBridge.sol pragma solidity 0.4.24; contract BasicTokenBridge is EternalStorage, Ownable, DecimalShiftBridge { using SafeMath for uint256; event DailyLimitChanged(uint256 newLimit); event ExecutionDailyLimitChanged(uint256 newLimit); bytes32 internal constant MIN_PER_TX = 0xbbb088c505d18e049d114c7c91f11724e69c55ad6c5397e2b929e68b41fa05d1; // keccak256(abi.encodePacked("minPerTx")) bytes32 internal constant MAX_PER_TX = 0x0f8803acad17c63ee38bf2de71e1888bc7a079a6f73658e274b08018bea4e29c; // keccak256(abi.encodePacked("maxPerTx")) bytes32 internal constant DAILY_LIMIT = 0x4a6a899679f26b73530d8cf1001e83b6f7702e04b6fdb98f3c62dc7e47e041a5; // keccak256(abi.encodePacked("dailyLimit")) bytes32 internal constant EXECUTION_MAX_PER_TX = 0xc0ed44c192c86d1cc1ba51340b032c2766b4a2b0041031de13c46dd7104888d5; // keccak256(abi.encodePacked("executionMaxPerTx")) bytes32 internal constant EXECUTION_DAILY_LIMIT = 0x21dbcab260e413c20dc13c28b7db95e2b423d1135f42bb8b7d5214a92270d237; // keccak256(abi.encodePacked("executionDailyLimit")) function totalSpentPerDay(uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))]; } function totalExecutedPerDay(uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))]; } function dailyLimit() public view returns (uint256) { return uintStorage[DAILY_LIMIT]; } function executionDailyLimit() public view returns (uint256) { return uintStorage[EXECUTION_DAILY_LIMIT]; } function maxPerTx() public view returns (uint256) { return uintStorage[MAX_PER_TX]; } function executionMaxPerTx() public view returns (uint256) { return uintStorage[EXECUTION_MAX_PER_TX]; } function minPerTx() public view returns (uint256) { return uintStorage[MIN_PER_TX]; } function withinLimit(uint256 _amount) public view returns (bool) { uint256 nextLimit = totalSpentPerDay(getCurrentDay()).add(_amount); return dailyLimit() >= nextLimit && _amount <= maxPerTx() && _amount >= minPerTx(); } function withinExecutionLimit(uint256 _amount) public view returns (bool) { uint256 nextLimit = totalExecutedPerDay(getCurrentDay()).add(_amount); return executionDailyLimit() >= nextLimit && _amount <= executionMaxPerTx(); } function getCurrentDay() public view returns (uint256) { return now / 1 days; } function addTotalSpentPerDay(uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))] = totalSpentPerDay(_day).add(_value); } function addTotalExecutedPerDay(uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))] = totalExecutedPerDay(_day).add(_value); } function setDailyLimit(uint256 _dailyLimit) external onlyOwner { require(_dailyLimit > maxPerTx() || _dailyLimit == 0); uintStorage[DAILY_LIMIT] = _dailyLimit; emit DailyLimitChanged(_dailyLimit); } function setExecutionDailyLimit(uint256 _dailyLimit) external onlyOwner { require(_dailyLimit > executionMaxPerTx() || _dailyLimit == 0); uintStorage[EXECUTION_DAILY_LIMIT] = _dailyLimit; emit ExecutionDailyLimitChanged(_dailyLimit); } function setExecutionMaxPerTx(uint256 _maxPerTx) external onlyOwner { require(_maxPerTx < executionDailyLimit()); uintStorage[EXECUTION_MAX_PER_TX] = _maxPerTx; } function setMaxPerTx(uint256 _maxPerTx) external onlyOwner { require(_maxPerTx == 0 || (_maxPerTx > minPerTx() && _maxPerTx < dailyLimit())); uintStorage[MAX_PER_TX] = _maxPerTx; } function setMinPerTx(uint256 _minPerTx) external onlyOwner { require(_minPerTx > 0 && _minPerTx < dailyLimit() && _minPerTx < maxPerTx()); uintStorage[MIN_PER_TX] = _minPerTx; } /** * @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters. * @return minimum of maxPerTx parameter and remaining daily quota. */ function maxAvailablePerTx() public view returns (uint256) { uint256 _maxPerTx = maxPerTx(); uint256 _dailyLimit = dailyLimit(); uint256 _spent = totalSpentPerDay(getCurrentDay()); uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0; return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily; } function _setLimits(uint256[3] _limits) internal { require( _limits[2] > 0 && // minPerTx > 0 _limits[1] > _limits[2] && // maxPerTx > minPerTx _limits[0] > _limits[1] // dailyLimit > maxPerTx ); uintStorage[DAILY_LIMIT] = _limits[0]; uintStorage[MAX_PER_TX] = _limits[1]; uintStorage[MIN_PER_TX] = _limits[2]; emit DailyLimitChanged(_limits[0]); } function _setExecutionLimits(uint256[2] _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[EXECUTION_DAILY_LIMIT] = _limits[0]; uintStorage[EXECUTION_MAX_PER_TX] = _limits[1]; emit ExecutionDailyLimitChanged(_limits[0]); } } // File: contracts/upgradeable_contracts/BasicForeignBridge.sol pragma solidity 0.4.24; contract BasicForeignBridge is EternalStorage, Validatable, BasicBridge, BasicTokenBridge, MessageRelay { /// triggered when relay of deposit from HomeBridge is complete event RelayedMessage(address recipient, uint256 value, bytes32 transactionHash); event UserRequestForAffirmation(address recipient, uint256 value); /** * @dev Validates provided signatures and relays a given message * @param message bytes to be relayed * @param signatures bytes blob with signatures to be validated */ function executeSignatures(bytes message, bytes signatures) external { Message.hasEnoughValidSignatures(message, signatures, validatorContract(), false); address recipient; uint256 amount; bytes32 txHash; address contractAddress; (recipient, amount, txHash, contractAddress) = Message.parseMessage(message); if (withinExecutionLimit(amount)) { require(contractAddress == address(this)); require(!relayedMessages(txHash)); setRelayedMessages(txHash, true); require(onExecuteMessage(recipient, amount, txHash)); emit RelayedMessage(recipient, amount, txHash); } else { onFailedMessage(recipient, amount, txHash); } } /** * @dev Internal function for updating fallback gas price value. * @param _gasPrice new value for the gas price, zero gas price is not allowed. */ function _setGasPrice(uint256 _gasPrice) internal { require(_gasPrice > 0); super._setGasPrice(_gasPrice); } /* solcov ignore next */ function onExecuteMessage(address, uint256, bytes32) internal returns (bool); /* solcov ignore next */ function onFailedMessage(address, uint256, bytes32) internal; } // File: contracts/upgradeable_contracts/ERC20Bridge.sol pragma solidity 0.4.24; contract ERC20Bridge is BasicForeignBridge { bytes32 internal constant ERC20_TOKEN = 0x15d63b18dbc21bf4438b7972d80076747e1d93c4f87552fe498c90cbde51665e; // keccak256(abi.encodePacked("erc20token")) function erc20token() public view returns (ERC20) { return ERC20(addressStorage[ERC20_TOKEN]); } function setErc20token(address _token) internal { require(AddressUtils.isContract(_token)); addressStorage[ERC20_TOKEN] = _token; } function relayTokens(address _receiver, uint256 _amount) external { require(_receiver != address(0)); require(_receiver != address(this)); require(_amount > 0); require(withinLimit(_amount)); addTotalSpentPerDay(getCurrentDay(), _amount); erc20token().transferFrom(msg.sender, address(this), _amount); emit UserRequestForAffirmation(_receiver, _amount); } } // File: contracts/upgradeable_contracts/OtherSideBridgeStorage.sol pragma solidity 0.4.24; contract OtherSideBridgeStorage is EternalStorage { bytes32 internal constant BRIDGE_CONTRACT = 0x71483949fe7a14d16644d63320f24d10cf1d60abecc30cc677a340e82b699dd2; // keccak256(abi.encodePacked("bridgeOnOtherSide")) function _setBridgeContractOnOtherSide(address _bridgeContract) internal { require(_bridgeContract != address(0)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } function bridgeContractOnOtherSide() internal view returns (address) { return addressStorage[BRIDGE_CONTRACT]; } } // File: contracts/upgradeable_contracts/erc20_to_native/ForeignBridgeErcToNative.sol pragma solidity 0.4.24; contract ForeignBridgeErcToNative is ERC20Bridge, OtherSideBridgeStorage { function initialize( address _validatorContract, address _erc20token, uint256 _requiredBlockConfirmations, uint256 _gasPrice, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _homeDailyLimitHomeMaxPerTxArray, //[ 0 = _homeDailyLimit, 1 = _homeMaxPerTx ] address _owner, int256 _decimalShift, address _bridgeOnOtherSide ) external onlyRelevantSender returns (bool) { require(!isInitialized()); require(AddressUtils.isContract(_validatorContract)); addressStorage[VALIDATOR_CONTRACT] = _validatorContract; setErc20token(_erc20token); uintStorage[DEPLOYED_AT_BLOCK] = block.number; _setRequiredBlockConfirmations(_requiredBlockConfirmations); _setGasPrice(_gasPrice); _setLimits(_dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(_homeDailyLimitHomeMaxPerTxArray); _setDecimalShift(_decimalShift); _setOwner(_owner); _setBridgeContractOnOtherSide(_bridgeOnOtherSide); setInitialize(); return isInitialized(); } function getBridgeMode() external pure returns (bytes4 _data) { return 0x18762d46; // bytes4(keccak256(abi.encodePacked("erc-to-native-core"))) } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Since bridged tokens are locked at this contract, it is not allowed to claim them with the use of claimTokens function require(_token != address(erc20token())); claimValues(_token, _to); } function onExecuteMessage( address _recipient, uint256 _amount, bytes32 /*_txHash*/ ) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), _amount); return erc20token().transfer(_recipient, _unshiftValue(_amount)); } function onFailedMessage(address, uint256, bytes32) internal { revert(); } function relayTokens(address _receiver, uint256 _amount) external { require(_receiver != bridgeContractOnOtherSide()); require(_receiver != address(0)); require(_receiver != address(this)); require(_amount > 0); require(withinLimit(_amount)); addTotalSpentPerDay(getCurrentDay(), _amount); erc20token().transferFrom(msg.sender, address(this), _amount); emit UserRequestForAffirmation(_receiver, _amount); } } // File: contracts/interfaces/IInterestReceiver.sol pragma solidity 0.4.24; interface IInterestReceiver { function onInterestReceived(address _token) external; } // File: contracts/upgradeable_contracts/erc20_to_native/InterestConnector.sol pragma solidity 0.4.24; /** * @title InterestConnector * @dev This contract gives an abstract way of receiving interest on locked tokens. */ contract InterestConnector is Ownable, ERC20Bridge { event PaidInterest(address indexed token, address to, uint256 value); /** * @dev Throws if interest is bearing not enabled. * @param token address, for which interest should be enabled. */ modifier interestEnabled(address token) { require(isInterestEnabled(token)); /* solcov ignore next */ _; } /** * @dev Ensures that caller is an EOA. * Functions with such modifier cannot be called from other contract (as well as from GSN-like approaches) */ modifier onlyEOA { // solhint-disable-next-line avoid-tx-origin require(msg.sender == tx.origin); /* solcov ignore next */ _; } /** * @dev Tells if interest earning was enabled for particular token. * @return true, if interest bearing is enabled. */ function isInterestEnabled(address _token) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("interestEnabled", _token))]; } /** * @dev Initializes interest receiving functionality. * Only owner can call this method. * @param _token address of the token for interest earning. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. * @param _minInterestPaid minimum amount of interest that can be paid in a single call. */ function initializeInterest( address _token, uint256 _minCashThreshold, uint256 _minInterestPaid, address _interestReceiver ) external onlyOwner { require(_isInterestSupported(_token)); require(!isInterestEnabled(_token)); _setInterestEnabled(_token, true); _setMinCashThreshold(_token, _minCashThreshold); _setMinInterestPaid(_token, _minInterestPaid); _setInterestReceiver(_token, _interestReceiver); } /** * @dev Sets minimum amount of tokens that cannot be invested. * Only owner can call this method. * @param _token address of the token contract. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. */ function setMinCashThreshold(address _token, uint256 _minCashThreshold) external onlyOwner { _setMinCashThreshold(_token, _minCashThreshold); } /** * @dev Tells minimum amount of tokens that are not being invested. * @param _token address of the invested token contract. * @return amount of tokens. */ function minCashThreshold(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minCashThreshold", _token))]; } /** * @dev Sets lower limit for the paid interest amount. * Only owner can call this method. * @param _token address of the token contract. * @param _minInterestPaid minimum amount of interest paid in a single call. */ function setMinInterestPaid(address _token, uint256 _minInterestPaid) external onlyOwner { _setMinInterestPaid(_token, _minInterestPaid); } /** * @dev Tells minimum amount of paid interest in a single call. * @param _token address of the invested token contract. * @return paid interest minimum limit. */ function minInterestPaid(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minInterestPaid", _token))]; } /** * @dev Internal function that disables interest for locked funds. * Only owner can call this method. * @param _token of token to disable interest for. */ function disableInterest(address _token) external onlyOwner { _withdraw(_token, uint256(-1)); _setInterestEnabled(_token, false); } /** * @dev Tells configured address of the interest receiver. * @param _token address of the invested token contract. * @return address of the interest receiver. */ function interestReceiver(address _token) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("interestReceiver", _token))]; } /** * Updates the interest receiver address. * Only owner can call this method. * @param _token address of the invested token contract. * @param _receiver new receiver address. */ function setInterestReceiver(address _token, address _receiver) external onlyOwner { _setInterestReceiver(_token, _receiver); } /** * @dev Pays collected interest for the specific underlying token. * Requires interest for the given token to be enabled. * @param _token address of the token contract. */ function payInterest(address _token) external onlyEOA interestEnabled(_token) { uint256 interest = interestAmount(_token); require(interest >= minInterestPaid(_token)); uint256 redeemed = _safeWithdrawTokens(_token, interest); _transferInterest(_token, redeemed); } /** * @dev Tells the amount of underlying tokens that are currently invested. * @param _token address of the token contract. * @return amount of underlying tokens. */ function investedAmount(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("investedAmount", _token))]; } /** * @dev Invests all excess tokens. * Requires interest for the given token to be enabled. * @param _token address of the token contract considered. */ function invest(address _token) public interestEnabled(_token) { uint256 balance = _selfBalance(_token); uint256 minCash = minCashThreshold(_token); require(balance > minCash); uint256 amount = balance - minCash; _setInvestedAmount(_token, investedAmount(_token).add(amount)); _invest(_token, amount); } /** * @dev Internal function for transferring interest. * Calls a callback on the receiver, if it is a contract. * @param _token address of the underlying token contract. * @param _amount amount of collected tokens that should be sent. */ function _transferInterest(address _token, uint256 _amount) internal { address receiver = interestReceiver(_token); require(receiver != address(0)); ERC20(_token).transfer(receiver, _amount); if (AddressUtils.isContract(receiver)) { IInterestReceiver(receiver).onInterestReceived(_token); } emit PaidInterest(_token, receiver, _amount); } /** * @dev Internal function for setting interest enabled flag for some token. * @param _token address of the token contract. * @param _enabled true to enable interest earning, false to disable. */ function _setInterestEnabled(address _token, bool _enabled) internal { boolStorage[keccak256(abi.encodePacked("interestEnabled", _token))] = _enabled; } /** * @dev Internal function for setting the amount of underlying tokens that are currently invested. * @param _token address of the token contract. * @param _amount new amount of invested tokens. */ function _setInvestedAmount(address _token, uint256 _amount) internal { uintStorage[keccak256(abi.encodePacked("investedAmount", _token))] = _amount; } /** * @dev Internal function for withdrawing some amount of the invested tokens. * Reverts if given amount cannot be withdrawn. * @param _token address of the token contract withdrawn. * @param _amount amount of requested tokens to be withdrawn. */ function _withdraw(address _token, uint256 _amount) internal { if (_amount == 0) return; uint256 invested = investedAmount(_token); uint256 withdrawal = _amount > invested ? invested : _amount; uint256 redeemed = _safeWithdrawTokens(_token, withdrawal); _setInvestedAmount(_token, invested > redeemed ? invested - redeemed : 0); } /** * @dev Internal function for safe withdrawal of invested tokens. * Reverts if given amount cannot be withdrawn. * Additionally verifies that at least _amount of tokens were withdrawn. * @param _token address of the token contract withdrawn. * @param _amount amount of requested tokens to be withdrawn. */ function _safeWithdrawTokens(address _token, uint256 _amount) private returns (uint256) { uint256 balance = _selfBalance(_token); _withdrawTokens(_token, _amount); uint256 redeemed = _selfBalance(_token) - balance; require(redeemed >= _amount); return redeemed; } /** * @dev Internal function for setting minimum amount of tokens that cannot be invested. * @param _token address of the token contract. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. */ function _setMinCashThreshold(address _token, uint256 _minCashThreshold) internal { uintStorage[keccak256(abi.encodePacked("minCashThreshold", _token))] = _minCashThreshold; } /** * @dev Internal function for setting lower limit for paid interest amount. * @param _token address of the token contract. * @param _minInterestPaid minimum amount of interest paid in a single call. */ function _setMinInterestPaid(address _token, uint256 _minInterestPaid) internal { uintStorage[keccak256(abi.encodePacked("minInterestPaid", _token))] = _minInterestPaid; } /** * @dev Internal function for setting interest receiver address. * @param _token address of the invested token contract. * @param _receiver address of the interest receiver. */ function _setInterestReceiver(address _token, address _receiver) internal { require(_receiver != address(this)); addressStorage[keccak256(abi.encodePacked("interestReceiver", _token))] = _receiver; } /** * @dev Tells this contract balance of some specific token contract * @param _token address of the token contract. * @return contract balance. */ function _selfBalance(address _token) internal view returns (uint256) { return ERC20(_token).balanceOf(address(this)); } function _isInterestSupported(address _token) internal pure returns (bool); function _invest(address _token, uint256 _amount) internal; function _withdrawTokens(address _token, uint256 _amount) internal; function interestAmount(address _token) public view returns (uint256); } // File: contracts/interfaces/ICToken.sol pragma solidity 0.4.24; interface ICToken { function mint(uint256 mintAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function balanceOf(address account) external view returns (uint256); function balanceOfUnderlying(address account) external view returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 borrowAmount) external returns (uint256); } // File: contracts/interfaces/IComptroller.sol pragma solidity 0.4.24; interface IComptroller { function claimComp(address[] holders, address[] cTokens, bool borrowers, bool suppliers) external; } // File: contracts/upgradeable_contracts/erc20_to_native/CompoundConnector.sol pragma solidity 0.4.24; /** * @title CompoundConnector * @dev This contract allows to partially invest locked Dai tokens into Compound protocol. */ contract CompoundConnector is InterestConnector { uint256 internal constant SUCCESS = 0; /** * @dev Tells the address of the DAI token in the Ethereum Mainnet. */ function daiToken() public pure returns (ERC20) { return ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); } /** * @dev Tells the address of the cDAI token in the Ethereum Mainnet. */ function cDaiToken() public pure returns (ICToken) { return ICToken(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); } /** * @dev Tells the address of the Comptroller contract in the Ethereum Mainnet. */ function comptroller() public pure returns (IComptroller) { return IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); } /** * @dev Tells the address of the COMP token in the Ethereum Mainnet. */ function compToken() public pure returns (ERC20) { return ERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); } /** * @dev Tells the current earned interest amount. * @param _token address of the underlying token contract. * @return total amount of interest that can be withdrawn now. */ function interestAmount(address _token) public view returns (uint256) { uint256 underlyingBalance = cDaiToken().balanceOfUnderlying(address(this)); // 1 DAI is reserved for possible truncation/round errors uint256 invested = investedAmount(_token) + 1 ether; return underlyingBalance > invested ? underlyingBalance - invested : 0; } /** * @dev Tells if interest earning is supported for the specific token contract. * @param _token address of the token contract. * @return true, if interest earning is supported. */ function _isInterestSupported(address _token) internal pure returns (bool) { return _token == address(daiToken()); } /** * @dev Invests the given amount of tokens to the Compound protocol. * Converts _amount of TOKENs into X cTOKENs. * @param _token address of the token contract. * @param _amount amount of tokens to invest. */ function _invest(address _token, uint256 _amount) internal { (_token); daiToken().approve(address(cDaiToken()), _amount); require(cDaiToken().mint(_amount) == SUCCESS); } /** * @dev Withdraws at least the given amount of tokens from the Compound protocol. * Converts X cTOKENs into _amount of TOKENs. * @param _token address of the token contract. * @param _amount minimal amount of tokens to withdraw. */ function _withdrawTokens(address _token, uint256 _amount) internal { (_token); require(cDaiToken().redeemUnderlying(_amount) == SUCCESS); } /** * @dev Claims Comp token and transfers it to the associated interest receiver. */ function claimCompAndPay() external onlyEOA { address[] memory holders = new address[](1); holders[0] = address(this); address[] memory markets = new address[](1); markets[0] = address(cDaiToken()); comptroller().claimComp(holders, markets, false, true); address comp = address(compToken()); uint256 interest = _selfBalance(comp); require(interest >= minInterestPaid(comp)); _transferInterest(comp, interest); } } // File: contracts/gsn/interfaces/IRelayRecipient.sol // SPDX-License-Identifier:MIT pragma solidity 0.4.24; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public view returns (bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view returns (address); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal view returns (bytes memory); function versionRecipient() external view returns (string memory); } // File: contracts/gsn/BaseRelayRecipient.sol // SPDX-License-Identifier:MIT // solhint-disable no-inline-assembly pragma solidity 0.4.24; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ contract BaseRelayRecipient is IRelayRecipient { /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view returns (address ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96, calldataload(sub(calldatasize, 20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // we copy the msg.data , except the last 20 bytes (and update the total length) assembly { let ptr := mload(0x40) // copy only size-20 bytes let size := sub(calldatasize, 20) // structure RLP data as <offset> <length> <bytes> mstore(ptr, 0x20) mstore(add(ptr, 32), size) calldatacopy(add(ptr, 64), 0, size) return(ptr, add(size, 64)) } } else { return msg.data; } } } // File: contracts/gsn/interfaces/IKnowForwarderAddress.sol // SPDX-License-Identifier:MIT pragma solidity 0.4.24; interface IKnowForwarderAddress { /** * return the forwarder we trust to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function getTrustedForwarder() external view returns (address); } // File: contracts/upgradeable_contracts/GSNForeignERC20Bridge.sol pragma solidity 0.4.24; contract GSNForeignERC20Bridge is BasicForeignBridge, ERC20Bridge, BaseRelayRecipient, IKnowForwarderAddress { bytes32 internal constant PAYMASTER = 0xfefcc139ed357999ed60c6a013947328d52e7d9751e93fd0274a2bfae5cbcb12; // keccak256(abi.encodePacked("paymaster")) bytes32 internal constant TRUSTED_FORWARDER = 0x222cb212229f0f9bcd249029717af6845ea3d3a84f22b54e5744ac25ef224c92; // keccak256(abi.encodePacked("trustedForwarder")) function versionRecipient() external view returns (string memory) { return "1.0.1"; } function getTrustedForwarder() external view returns (address) { return addressStorage[TRUSTED_FORWARDER]; } function setTrustedForwarder(address _trustedForwarder) public onlyOwner { addressStorage[TRUSTED_FORWARDER] = _trustedForwarder; } function isTrustedForwarder(address forwarder) public view returns (bool) { return forwarder == addressStorage[TRUSTED_FORWARDER]; } function setPayMaster(address _paymaster) public onlyOwner { addressStorage[PAYMASTER] = _paymaster; } /** * @param message same as in `executeSignatures` * @param signatures same as in `executeSignatures` * @param maxTokensFee maximum amount of foreign tokens that user allows to take * as a commission */ function executeSignaturesGSN(bytes message, bytes signatures, uint256 maxTokensFee) external { // Allow only forwarder calls require(isTrustedForwarder(msg.sender), "invalid forwarder"); Message.hasEnoughValidSignatures(message, signatures, validatorContract(), false); address recipient; uint256 amount; bytes32 txHash; address contractAddress; (recipient, amount, txHash, contractAddress) = Message.parseMessage(message); if (withinExecutionLimit(amount)) { require(maxTokensFee <= amount); require(contractAddress == address(this)); require(!relayedMessages(txHash)); setRelayedMessages(txHash, true); require(onExecuteMessageGSN(recipient, amount, maxTokensFee)); emit RelayedMessage(recipient, amount, txHash); } else { onFailedMessage(recipient, amount, txHash); } } function onExecuteMessageGSN(address recipient, uint256 amount, uint256 fee) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), amount); // Send maxTokensFee to paymaster ERC20 token = erc20token(); bool first = token.transfer(addressStorage[PAYMASTER], fee); bool second = token.transfer(recipient, amount - fee); return first && second; } } // File: contracts/upgradeable_contracts/erc20_to_native/XDaiForeignBridge.sol pragma solidity 0.4.24; contract XDaiForeignBridge is ForeignBridgeErcToNative, CompoundConnector, GSNForeignERC20Bridge { function initialize( address _validatorContract, address _erc20token, uint256 _requiredBlockConfirmations, uint256 _gasPrice, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _homeDailyLimitHomeMaxPerTxArray, //[ 0 = _homeDailyLimit, 1 = _homeMaxPerTx ] address _owner, int256 _decimalShift, address _bridgeOnOtherSide ) external onlyRelevantSender returns (bool) { require(!isInitialized()); require(AddressUtils.isContract(_validatorContract)); require(_erc20token == address(daiToken())); require(_decimalShift == 0); addressStorage[VALIDATOR_CONTRACT] = _validatorContract; uintStorage[DEPLOYED_AT_BLOCK] = block.number; _setRequiredBlockConfirmations(_requiredBlockConfirmations); _setGasPrice(_gasPrice); _setLimits(_dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(_homeDailyLimitHomeMaxPerTxArray); _setOwner(_owner); _setBridgeContractOnOtherSide(_bridgeOnOtherSide); setInitialize(); return isInitialized(); } function erc20token() public view returns (ERC20) { return daiToken(); } // selector 6a641d80 function migrateTo_6_1_0(address _interestReceiver) external { bytes32 upgradeStorage = 0x6a641d806674d4ce5e98c8fdab48e66c563660255f099d81d45fa2fe8ed9cc1d; // keccak256(abi.encodePacked('migrateTo_6_1_0(address)')) require(!boolStorage[upgradeStorage]); address dai = address(daiToken()); address comp = address(compToken()); _setInterestEnabled(dai, true); _setMinCashThreshold(dai, 1000000 ether); _setMinInterestPaid(dai, 1000 ether); _setInterestReceiver(dai, _interestReceiver); _setMinInterestPaid(comp, 1 ether); _setInterestReceiver(comp, _interestReceiver); invest(dai); boolStorage[upgradeStorage] = true; } function investDai() external { invest(address(daiToken())); } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Since bridged tokens are locked at this contract, it is not allowed to claim them with the use of claimTokens function address bridgedToken = address(daiToken()); require(_token != address(bridgedToken)); require(_token != address(cDaiToken()) || !isInterestEnabled(bridgedToken)); require(_token != address(compToken()) || !isInterestEnabled(bridgedToken)); claimValues(_token, _to); } function onExecuteMessage( address _recipient, uint256 _amount, bytes32 /*_txHash*/ ) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), _amount); ERC20 token = daiToken(); ensureEnoughTokens(token, _amount); return token.transfer(_recipient, _amount); } function onExecuteMessageGSN(address recipient, uint256 amount, uint256 fee) internal returns (bool) { ensureEnoughTokens(daiToken(), amount); return super.onExecuteMessageGSN(recipient, amount, fee); } function ensureEnoughTokens(ERC20 token, uint256 amount) internal { uint256 currentBalance = token.balanceOf(address(this)); if (currentBalance < amount) { uint256 withdrawAmount = (amount - currentBalance).add(minCashThreshold(address(token))); _withdraw(address(token), withdrawAmount); } } }
* @dev Tells the address of the cDAI token in the Ethereum Mainnet./
function cDaiToken() public pure returns (ICToken) { return ICToken(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); }
1,093,428
[ 1, 21009, 87, 326, 1758, 434, 326, 276, 9793, 45, 1147, 316, 326, 512, 18664, 379, 12740, 2758, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 276, 40, 10658, 1345, 1435, 1071, 16618, 1135, 261, 45, 1268, 969, 13, 288, 203, 3639, 327, 467, 1268, 969, 12, 20, 92, 25, 72, 23, 69, 25, 5718, 41, 24, 40, 26, 4331, 40, 26, 22214, 952, 21, 41, 361, 4763, 14509, 70, 2090, 29, 8875, 41, 23, 1105, 23, 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 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol"; /** * This contract is used to deploy the volatility and inverse volatility tokens. */ contract VolmexPositionToken is Initializable, AccessControlUpgradeable, ERC20PausableUpgradeable { // Position token role, calculated as keccak256("VOLMEX_PROTOCOL_ROLE") bytes32 public constant VOLMEX_PROTOCOL_ROLE = 0x33ba6006595f7ad5c59211bde33456cab351f47602fc04f644c8690bc73c4e16; /** * @dev Grants `DEFAULT_ADMIN_ROLE` and `VOLMEX_PROTOCOL_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ function initialize(string memory name, string memory symbol) external initializer { __ERC20_init_unchained(name, symbol); __AccessControl_init_unchained(); __ERC20Pausable_init(); __ERC165_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(VOLMEX_PROTOCOL_ROLE, msg.sender); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `VOLMEX_PROTOCOL_ROLE`. */ function mint(address to, uint256 amount) public virtual { require( hasRole(VOLMEX_PROTOCOL_ROLE, msg.sender), "VolmexPositionToken: must have volmex protocol role to mint" ); _mint(to, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(address from, uint256 amount) public virtual { require( hasRole(VOLMEX_PROTOCOL_ROLE, msg.sender), "VolmexPositionToken: must have volmex protocol role to burn" ); _burn(from, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `VOLMEX_PROTOCOL_ROLE`. */ function pause() public virtual { require( hasRole(VOLMEX_PROTOCOL_ROLE, msg.sender), "VolmexPositionToken: must have volmex protocol role to pause" ); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `VOLMEX_PROTOCOL_ROLE`. */ function unpause() public virtual { require( hasRole(VOLMEX_PROTOCOL_ROLE, msg.sender), "VolmexPositionToken: must have volmex protocol role to unpause" ); _unpause(); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version 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; import "../ERC20Upgradeable.sol"; import "../../../security/PausableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable { function __ERC20Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal initializer { } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } uint256[50] private __gap; } // 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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 "./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 "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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 defaut 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @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 { } uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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 "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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); }
* @dev Unpauses all token transfers. See {ERC20Pausable} and {Pausable-_unpause}. Requirements: - the caller must have the `VOLMEX_PROTOCOL_ROLE`./
function unpause() public virtual { require( hasRole(VOLMEX_PROTOCOL_ROLE, msg.sender), "VolmexPositionToken: must have volmex protocol role to unpause" ); _unpause(); }
195,041
[ 1, 984, 8774, 6117, 777, 1147, 29375, 18, 2164, 288, 654, 39, 3462, 16507, 16665, 97, 471, 288, 16507, 16665, 17, 67, 318, 19476, 5496, 29076, 30, 300, 326, 4894, 1297, 1240, 326, 1375, 19971, 958, 60, 67, 16850, 67, 16256, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 640, 19476, 1435, 1071, 5024, 288, 203, 3639, 2583, 12, 203, 5411, 28335, 12, 19971, 958, 60, 67, 16850, 67, 16256, 16, 1234, 18, 15330, 3631, 203, 5411, 315, 17431, 81, 338, 2555, 1345, 30, 1297, 1240, 6626, 81, 338, 1771, 2478, 358, 640, 19476, 6, 203, 3639, 11272, 203, 3639, 389, 318, 19476, 5621, 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 ]
// SPDX-License-Identifier: MIT // File: contracts/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); } // File: ../token/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: ../token/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: ../token/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface 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: 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; 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); } 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); } } } } // File: 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 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; } } // File: contracts/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); } } // File: contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: ../token/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract 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(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 {} } // File: ../token/extensions/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: ../token/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @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(); } } // File: ../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() { _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); } } // File: contracts/interfaces/ITwentyFiveFF.sol pragma solidity ^0.8.0; interface ITwentyFiveFF { function addToAllowList(address[] calldata addresses) external; function onAllowList(address addr) external returns (bool); function removeFromAllowList(address[] calldata addresses) external; function allowListClaimedBy(address owner) external returns (uint256); function purchase(uint256 numberOfTokens) external payable; function purchaseWhitelist(uint256 numberOfTokens) external payable; function gift(address[] calldata to) external; function setIsActive(bool isActive) external; function setIsAllowListActive(bool isAllowListActive) external; function setAllowListMaxMint(uint256 maxMint) external; function setProof(string memory proofString) external; function withdraw() external; } // File: contracts/interfaces/ITwentyFiveFFMetadata.sol pragma solidity ^0.8.0; interface ITwentyFiveFFMetadata { function setContractURI(string calldata URI) external; function setBaseURI(string calldata URI) external; function setRevealedBaseURI(string calldata revealedBaseURI) external; function contractURI() external view returns (string memory); } // File: ../TwentyFiveFF.sol pragma solidity ^0.8.0; contract TwentyFiveFF is ERC721Enumerable, Ownable, ITwentyFiveFF, ITwentyFiveFFMetadata { using Strings for uint256; uint256 public constant PURCHASE_LIMIT = 12; uint256 public constant PRICE = 0.075 ether; uint256 public constant TwentyFiveFF_GIFT = 99; uint256 public constant TwentyFiveFF_PUBLIC = 9900; uint256 public constant TwentyFiveFF_MAX = TwentyFiveFF_GIFT + TwentyFiveFF_PUBLIC; bool public isActive = false; bool public isAllowListActive = false; string public proof; uint256 public allowListMaxMint = 3; /// @dev We will use these to be able to calculate remaining correctly. uint256 public totalGiftSupply; uint256 public totalPublicSupply; mapping(address => bool) private _allowList; mapping(address => uint256) private _allowListClaimed; string private _contractURI = ''; string private _tokenBaseURI = ''; string private _tokenRevealedBaseURI = ''; constructor(string memory name, string memory symbol) ERC721(name, symbol) {} function addToAllowList(address[] calldata addresses) external override onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Can't add zero address"); _allowList[addresses[i]] = true; /** * @dev We don't want to reset _allowListClaimed count * if we try to add someone more than once. */ _allowListClaimed[addresses[i]] > 0 ? _allowListClaimed[addresses[i]] : 0; } } function onAllowList(address addr) external view override returns (bool) { return _allowList[addr]; } function removeFromAllowList(address[] calldata addresses) external override onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Can't add zero address"); /// @dev We don't want to reset possible _allowListClaimed numbers. _allowList[addresses[i]] = false; } } /** * @dev We want to be able to distinguish tokens bought during isAllowListActive * and tokens bought outside of isAllowListActive */ function allowListClaimedBy(address owner) external view override returns (uint256) { require(owner != address(0), 'Zero address not on Allow List'); return _allowListClaimed[owner]; } function purchase(uint256 numberOfTokens) external payable override { require(isActive, 'Contract is not active'); require(!isAllowListActive, 'Only allowing from Allow List'); require(totalSupply() < TwentyFiveFF_MAX, 'All tokens have been minted'); require(numberOfTokens <= PURCHASE_LIMIT, 'Would exceed PURCHASE_LIMIT'); /** * @dev The last person to purchase might pay too much. * This way however they can't get sniped. * If this happens, we'll refund the Eth for the unavailable tokens. */ require(totalPublicSupply < TwentyFiveFF_PUBLIC, 'Purchase would exceed TwentyFiveFF_PUBLIC'); require( PRICE * numberOfTokens <= msg.value, 'ETH amount insufficient' ); for (uint256 i = 0; i < numberOfTokens; i++) { /** * @dev Since they can get here while exceeding the TwentyFiveFF_MAX, * we have to make sure to not mint any additional tokens. */ if (totalPublicSupply < TwentyFiveFF_PUBLIC) { /** * @dev Public token numbering starts after TwentyFiveFF_GIFT. * And we don't want our tokens to start at 0 but at 1. */ uint256 tokenId = TwentyFiveFF_GIFT + totalPublicSupply + 1; totalPublicSupply += 1; _safeMint(msg.sender, tokenId); } } } function purchaseWhitelist(uint256 numberOfTokens) external payable override { require(isActive, 'Contract is not active'); require(isAllowListActive, 'Whitelist minting is not active'); require(_allowList[msg.sender], 'You are not on the whitelist'); require(totalSupply() < TwentyFiveFF_MAX, 'All tokens have been minted'); require( numberOfTokens <= allowListMaxMint, 'Cannot purchase this many tokens' ); require( totalPublicSupply + numberOfTokens <= TwentyFiveFF_PUBLIC, 'Purchase would exceed TwentyFiveFF_PUBLIC' ); require( _allowListClaimed[msg.sender] + numberOfTokens <= allowListMaxMint, 'Purchase exceeds max allowed' ); require( PRICE * numberOfTokens <= msg.value, 'ETH amount insufficient' ); for (uint256 i = 0; i < numberOfTokens; i++) { /** * @dev Public token numbering starts after TwentyFiveFF_GIFT. * We don't want our tokens to start at 0 but at 1. */ uint256 tokenId = TwentyFiveFF_GIFT + totalPublicSupply + 1; totalPublicSupply += 1; _allowListClaimed[msg.sender] += 1; _safeMint(msg.sender, tokenId); } } function gift(address[] calldata to) external override onlyOwner { require(totalSupply() < TwentyFiveFF_MAX, 'All tokens have been minted'); require( totalGiftSupply + to.length <= TwentyFiveFF_GIFT, 'Not enough tokens left to gift' ); for (uint256 i = 0; i < to.length; i++) { /// @dev We don't want our tokens to start at 0 but at 1. uint256 tokenId = totalGiftSupply + 1; totalGiftSupply += 1; _safeMint(to[i], tokenId); } } function setIsActive(bool _isActive) external override onlyOwner { isActive = _isActive; } function setIsAllowListActive(bool _isAllowListActive) external override onlyOwner { isAllowListActive = _isAllowListActive; } function setAllowListMaxMint(uint256 maxMint) external override onlyOwner { allowListMaxMint = maxMint; } function setProof(string calldata proofString) external override onlyOwner { proof = proofString; } function withdraw() external override onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function setContractURI(string calldata URI) external override onlyOwner { _contractURI = URI; } function setBaseURI(string calldata URI) external override onlyOwner { _tokenBaseURI = URI; } function setRevealedBaseURI(string calldata revealedBaseURI) external override onlyOwner { _tokenRevealedBaseURI = revealedBaseURI; } function contractURI() public view override returns (string memory) { return _contractURI; } function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), 'Token does not exist'); /// @dev Convert string to bytes so we can check if it's empty or not. string memory revealedBaseURI = _tokenRevealedBaseURI; return bytes(revealedBaseURI).length > 0 ? string(abi.encodePacked(revealedBaseURI, tokenId.toString())) : _tokenBaseURI; } }
@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; } }
228,711
[ 1, 17727, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 565, 327, 1234, 18, 15330, 31, 203, 225, 289, 203, 203, 225, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 745, 892, 13, 288, 203, 565, 327, 1234, 18, 892, 31, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; 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 numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, 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 numbers, 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 numbers 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; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ 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 the balance of. * @return An 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 for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit 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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function 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; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function 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; } /** * @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 amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != 0); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(account != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender&#39;s allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burnFrom(address account, uint256 amount) internal { require(amount <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( amount); _burn(account, amount); } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require(token.approve(spender, value)); } } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.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 conform * the base architecture for crowdsales. They are *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 &#39;super&#39; where appropriate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address 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 rate 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 wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor(uint256 rate, address wallet, IERC20 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); } /** * @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) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the mount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @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 TokensPurchased( 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` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol&#39;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 { 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.safeTransfer(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: contracts/TieredPriceCrowdsale.sol /** * @title CappedWhitelistedCrowdsale * @dev Crowdsale with a limit for total contributions and per-beneficiary caps. * Combination of CappedCrowdsale and IndividuallyCappedCrowdsale */ contract TieredPriceCrowdsale is Crowdsale { uint256 private _baseRate; uint256 private _tier2Start; uint256 private _tier3Start; uint256 private _tier4Start; constructor( uint256 baseRate, uint256 openingTimeTier2, uint256 openingTimeTier3, uint256 openingTimeTier4 ) public { require(baseRate > 0); require(openingTimeTier2 > block.timestamp); require(openingTimeTier3 >= openingTimeTier2); require(openingTimeTier4 >= openingTimeTier3); _baseRate = baseRate; _tier4Start = openingTimeTier4; _tier3Start = openingTimeTier3; _tier2Start = openingTimeTier2; } function _getbonusRate() internal view returns (uint256) { // Calculate current rate with bonus if(_tier2Start > block.timestamp){ return(_baseRate * 6 / 5); } else if(_tier3Start > block.timestamp){ return(_baseRate * 11 / 10); } else if(_tier4Start > block.timestamp){ return(_baseRate * 21 / 20); } else { return(_baseRate); } } /** * @return the current bonus level. */ function bonusRate() public view returns(uint256) { return _getbonusRate(); } /** * @param tier Value that represents the tier * @return Timestamp when the tier starts */ function tierStartTime( uint256 tier ) external view returns(uint256) { if(tier == 2){ return _tier2Start; } else if(tier == 3){ return _tier3Start; } else if(tier == 4){ return _tier4Start; } return 0; } /** * @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(_getbonusRate()); } } // File: openzeppelin-solidity/contracts/access/Roles.sol /** * @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)); role.bearer[account] = true; } /** * @dev remove an account&#39;s access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); 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]; } } // File: openzeppelin-solidity/contracts/access/roles/CapperRole.sol contract CapperRole { using Roles for Roles.Role; event CapperAdded(address indexed account); event CapperRemoved(address indexed account); Roles.Role private cappers; constructor() public { cappers.add(msg.sender); } modifier onlyCapper() { require(isCapper(msg.sender)); _; } function isCapper(address account) public view returns (bool) { return cappers.has(account); } function addCapper(address account) public onlyCapper { cappers.add(account); emit CapperAdded(account); } function renounceCapper() public { cappers.remove(msg.sender); } function _removeCapper(address account) internal { cappers.remove(account); emit CapperRemoved(account); } } // File: contracts/WhitelistedCrowdsale.sol /** * @title WhitelistedCrowdsale * @dev Crowdsale with whitelist required for purchases, based on IndividuallyCappedCrowdsale. */ contract WhitelistedCrowdsale is Crowdsale, CapperRole { using SafeMath for uint256; uint256 private _invCap; mapping(address => uint256) private _contributions; mapping(address => uint256) private _caps; constructor(uint256 invCap) public { require(invCap > 0); _invCap = invCap; } /** * @dev Checks whether the beneficiary is in the whitelist. * @param beneficiary Address to be checked * @return Whether the beneficiary is whitelisted */ function isWhitelisted(address beneficiary) public view returns (bool) { return _caps[beneficiary] != 0; } /** * @dev add an address to the whitelist * @param beneficiary address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address beneficiary) public onlyCapper returns (bool) { require(beneficiary != address(0)); _caps[beneficiary] = _invCap; return isWhitelisted(beneficiary); } /** * @dev add addresses to the whitelist * @param _beneficiaries addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _beneficiaries) external onlyCapper { for (uint256 i = 0; i < _beneficiaries.length; i++) { addAddressToWhitelist(_beneficiaries[i]); } } /** * @dev remove an address from the whitelist * @param beneficiary address * @return true if the address was removed from the whitelist, false if the address wasn&#39;t already in the whitelist */ function removeAddressFromWhitelist(address beneficiary) public onlyCapper returns (bool) { require(beneficiary != address(0)); _caps[beneficiary] = 0; return isWhitelisted(beneficiary); } /** * @dev remove addresses from the whitelist * @param _beneficiaries addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren&#39;t already in the whitelist */ function removeAddressesFromWhitelist(address[] _beneficiaries) external onlyCapper { for (uint256 i = 0; i < _beneficiaries.length; i++) { removeAddressFromWhitelist(_beneficiaries[i]); } } /** * @dev Returns the amount contributed so far by a specific beneficiary. * @param beneficiary Address of contributor * @return Beneficiary contribution so far */ function getContribution(address beneficiary) public view returns (uint256) { return _contributions[beneficiary]; } /** * @dev Extend parent behavior requiring purchase to respect the beneficiary&#39;s funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal { super._preValidatePurchase(beneficiary, weiAmount); require( _contributions[beneficiary].add(weiAmount) <= _caps[beneficiary]); } /** * @dev Extend parent behavior to update beneficiary contributions * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { super._updatePurchasingState(beneficiary, weiAmount); _contributions[beneficiary] = _contributions[beneficiary].add(weiAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param cap Max amount of wei to be contributed */ constructor(uint256 cap) public { require(cap > 0); _cap = cap; } /** * @return the cap of the crowdsale. */ function cap() public view returns(uint256) { return _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised() >= _cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal { super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= _cap); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen()); _; } /** * @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; } /** * @return the crowdsale opening time. */ function openingTime() public view returns(uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns(uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp >= _openingTime && block.timestamp <= _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/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale with a one-off finalization action, where one * can do extra work after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale { using SafeMath for uint256; bool private _finalized = false; event CrowdsaleFinalized(); /** * @return true if the crowdsale is finalized, false otherwise. */ function finalized() public view returns (bool) { return _finalized; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize() public { require(!_finalized); require(hasClosed()); _finalization(); emit CrowdsaleFinalized(); _finalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super._finalization() to ensure the chain of finalization is * executed entirely. */ function _finalization() internal { } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private minters; constructor() public { minters.add(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 { minters.add(account); emit MinterAdded(account); } function renounceMinter() public { minters.remove(msg.sender); } function _removeMinter(address account) internal { minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { event MintingFinished(); bool private _mintingFinished = false; modifier onlyBeforeMintingFinished() { require(!_mintingFinished); _; } /** * @return true if the minting is finished. */ function mintingFinished() public view returns(bool) { return _mintingFinished; } /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address to, uint256 amount ) public onlyMinter onlyBeforeMintingFinished returns (bool) { _mint(to, amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyMinter onlyBeforeMintingFinished returns (bool) { _mintingFinished = true; emit MintingFinished(); return true; } } // File: openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param beneficiary Token purchaser * @param tokenAmount Number of tokens to be minted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { // Potentially dangerous assumption about the type of the token. require( ERC20Mintable(address(token())).mint(beneficiary, tokenAmount)); } } // File: contracts/PlazaCrowdsale.sol contract PlazaCrowdsale is CappedCrowdsale, FinalizableCrowdsale, MintedCrowdsale, WhitelistedCrowdsale, TieredPriceCrowdsale { constructor( uint256 openingTime, uint256 closingTime, uint256 rate, address wallet, uint256 cap, ERC20Mintable token, uint256 openingTimeTier4, uint256 openingTimeTier3, uint256 openingTimeTier2, uint256 invCap ) public Crowdsale(rate, wallet, token) CappedCrowdsale(cap) WhitelistedCrowdsale(invCap) TimedCrowdsale(openingTime, closingTime) TieredPriceCrowdsale(rate, openingTimeTier2, openingTimeTier3, openingTimeTier4) {} }
* @dev remove addresses from the whitelist @param _beneficiaries addresses @return true if at least one address was removed from the whitelist, false if all addresses weren&#39;t already in the whitelist/
function removeAddressesFromWhitelist(address[] _beneficiaries) external onlyCapper { for (uint256 i = 0; i < _beneficiaries.length; i++) { removeAddressFromWhitelist(_beneficiaries[i]); } }
6,710,114
[ 1, 4479, 6138, 628, 326, 10734, 225, 389, 70, 4009, 74, 14463, 5646, 6138, 327, 638, 309, 622, 4520, 1245, 1758, 1703, 3723, 628, 326, 10734, 16, 629, 309, 777, 6138, 22646, 275, 10, 5520, 31, 88, 1818, 316, 326, 10734, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 7148, 1265, 18927, 12, 2867, 8526, 389, 70, 4009, 74, 14463, 5646, 13, 3903, 1338, 4664, 457, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 70, 4009, 74, 14463, 5646, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1206, 1887, 1265, 18927, 24899, 70, 4009, 74, 14463, 5646, 63, 77, 19226, 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 ]
./partial_match/1313161554/0xa200B567579a577F582d292f7A1b5C4ecce195F8/sources/Comptroller.sol
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount @dev Used in liquidation (called in auToken.liquidateBorrowFresh) @param auTokenBorrowed The address of the borrowed auToken @param auTokenCollateral The address of the collateral auToken @param actualRepayAmount The amount of auTokenBorrowed underlying to convert into auTokenCollateral tokens/ Read oracle prices for borrowed and collateral markets */
function liquidateCalculateSeizeTokens(address auTokenBorrowed, address auTokenCollateral, uint actualRepayAmount) external view override returns (uint) { AuToken[] memory queries = new AuToken[](2); queries[0] = AuToken(auTokenBorrowed); queries[1] = AuToken(auTokenCollateral); uint256[] memory prices = oracle.getUnderlyingPrices(queries); uint priceBorrowedMantissa = prices[0]; uint priceCollateralMantissa = prices[1]; if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { revert PriceError(); } Exp numerator; Exp denominator; Exp ratio; denominator = mul_(Exp.wrap(priceCollateralMantissa), Exp.wrap(exchangeRateMantissa)); ratio = div_(numerator, denominator); return seizeTokens; }
16,936,444
[ 1, 8695, 1300, 434, 2430, 434, 4508, 2045, 287, 3310, 358, 695, 554, 864, 392, 6808, 3844, 225, 10286, 316, 4501, 26595, 367, 261, 11777, 316, 20309, 1345, 18, 549, 26595, 340, 38, 15318, 42, 1955, 13, 225, 20309, 1345, 38, 15318, 329, 1021, 1758, 434, 326, 29759, 329, 20309, 1345, 225, 20309, 1345, 13535, 2045, 287, 1021, 1758, 434, 326, 4508, 2045, 287, 20309, 1345, 225, 3214, 426, 10239, 6275, 1021, 3844, 434, 20309, 1345, 38, 15318, 329, 6808, 358, 1765, 1368, 20309, 1345, 13535, 2045, 287, 2430, 19, 2720, 20865, 19827, 364, 29759, 329, 471, 4508, 2045, 287, 2267, 2413, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4501, 26595, 340, 8695, 1761, 554, 5157, 12, 2867, 20309, 1345, 38, 15318, 329, 16, 1758, 20309, 1345, 13535, 2045, 287, 16, 2254, 3214, 426, 10239, 6275, 13, 3903, 1476, 3849, 1135, 261, 11890, 13, 288, 203, 3639, 432, 89, 1345, 8526, 3778, 6218, 273, 394, 432, 89, 1345, 8526, 12, 22, 1769, 203, 3639, 6218, 63, 20, 65, 273, 432, 89, 1345, 12, 8377, 1345, 38, 15318, 329, 1769, 203, 3639, 6218, 63, 21, 65, 273, 432, 89, 1345, 12, 8377, 1345, 13535, 2045, 287, 1769, 203, 3639, 2254, 5034, 8526, 3778, 19827, 273, 20865, 18, 588, 14655, 6291, 31862, 12, 13748, 1769, 203, 203, 3639, 2254, 6205, 38, 15318, 329, 49, 970, 21269, 273, 19827, 63, 20, 15533, 203, 3639, 2254, 6205, 13535, 2045, 287, 49, 970, 21269, 273, 19827, 63, 21, 15533, 203, 3639, 309, 261, 8694, 38, 15318, 329, 49, 970, 21269, 422, 374, 747, 6205, 13535, 2045, 287, 49, 970, 21269, 422, 374, 13, 288, 203, 5411, 15226, 20137, 668, 5621, 203, 3639, 289, 203, 203, 3639, 7784, 16730, 31, 203, 3639, 7784, 15030, 31, 203, 3639, 7784, 7169, 31, 203, 203, 3639, 15030, 273, 14064, 67, 12, 2966, 18, 4113, 12, 8694, 13535, 2045, 287, 49, 970, 21269, 3631, 7784, 18, 4113, 12, 16641, 4727, 49, 970, 21269, 10019, 203, 3639, 7169, 273, 3739, 67, 12, 2107, 7385, 16, 15030, 1769, 203, 203, 203, 3639, 327, 695, 554, 5157, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x000c556C21D8963c33a035bc0a8CC5aefAbD85bF/sources/contracts/Monopoly.sol
На каком квадрате игрок сейчас
mapping(address => uint) private onQuad;
8,146,506
[ 1, 145, 256, 145, 113, 225, 145, 123, 145, 113, 145, 123, 145, 127, 145, 125, 225, 145, 123, 145, 115, 145, 113, 145, 117, 146, 227, 145, 113, 146, 229, 145, 118, 225, 145, 121, 145, 116, 146, 227, 145, 127, 145, 123, 225, 146, 228, 145, 118, 145, 122, 146, 234, 145, 113, 146, 228, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 13, 3238, 603, 24483, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: Account library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } // Part: Actions library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } // Part: ICallee /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } // Part: ISoloMargin interface ISoloMargin { struct OperatorArg { address operator1; bool trusted; } function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external; function getIsGlobalOperator(address operator1) external view returns (bool); function getMarketTokenAddress(uint256 marketId) external view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) external; function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) external view returns (address); function getMarketInterestSetter(uint256 marketId) external view returns (address); function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getNumMarkets() external view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external; function ownerSetLiquidationSpread(Decimal.D256 memory spread) external; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external; function getIsLocalOperator(address owner, address operator1) external view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory); function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external; function getMarginRatio() external view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) external view returns (bool); function getRiskParams() external view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) external view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function renounceOwnership() external; function getMinBorrowedValue() external view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) external; function getMarketPrice(uint256 marketId) external view returns (address); function owner() external view returns (address); function isOwner() external view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) external; function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; function getMarketWithInfo(uint256 marketId) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) external; function getLiquidationSpread() external view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory); function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) external view returns (uint8); function getEarningsRate() external view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) external; function getRiskLimits() external view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) external view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) external; function ownerSetGlobalOperator(address operator1, bool approved) external; function transferOwnership(address newOwner) external; function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory); } // Part: IUni interface IUni{ function getAmountsOut( uint256 amountIn, address[] calldata path ) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // Part: InterestRateModel interface InterestRateModel { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256, uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @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); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: iearn-finance/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: CTokenI interface CTokenI { /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function accrualBlockNumber() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } // Part: DydxFlashloanBase contract DydxFlashloanBase { using SafeMath for uint256; function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0}), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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"); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: CErc20I interface CErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenI cTokenCollateral ) external returns (uint256); function underlying() external view returns (address); } // Part: ComptrollerI interface ComptrollerI { function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); /*** Comp claims ****/ function claimComp(address holder) external; function claimComp(address holder, CTokenI[] memory cTokens) external; function markets(address ctoken) external view returns ( bool, uint256, bool ); function compSpeeds(address ctoken) external view returns (uint256); } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.2"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: Strategy.sol /******************** * * A lender optimisation strategy for any erc20 asset * https://github.com/Grandthrax/yearnV2-generic-lender-strat * v0.4.2 * ********************* */ contract Strategy is BaseStrategy, DydxFlashloanBase, ICallee { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan); //Flash Loan Providers address private constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; // Comptroller address for compound.finance ComptrollerI private constant compound = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //Only three tokens we use address private constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; CErc20I public cToken; //address public constant DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //Operating variables uint256 public collateralTarget = 0.73 ether; // 73% uint256 public blocksToLiquidationDangerZone = 46500; // 7 days = 60*60*24*7/13 uint256 public minWant; // Default is 0. Only lend if we have enough want to be worth it. Can be set to non-zero uint256 public minCompToSell = 0.1 ether; //used both as the threshold to sell but also as a trigger for harvest //To deactivate flash loan provider if needed bool public DyDxActive = true; bool public forceMigrate; // default is false uint256 public dyDxMarketId; constructor(address _vault, address _cToken) public BaseStrategy(_vault) { cToken = CErc20I(address(_cToken)); //pre-set approvals IERC20(comp).safeApprove(uniswapRouter, type(uint256).max); want.safeApprove(address(cToken), type(uint256).max); want.safeApprove(SOLO, type(uint256).max); // You can set these parameters on deployment to whatever you want maxReportDelay = 86400; // once per 24 hours profitFactor = 100; // multiple before triggering harvest _setMarketIdFromTokenAddress(); } function name() external override view returns (string memory){ return "StrategyGenericLevCompFarm"; } /* * Control Functions */ function setDyDx(bool _dydx) external management { DyDxActive = _dydx; } function setForceMigrate(bool _force) external onlyGovernance { forceMigrate = _force; } function setMinCompToSell(uint256 _minCompToSell) external management { minCompToSell = _minCompToSell; } function setMinWant(uint256 _minWant) external management { minWant = _minWant; } function updateMarketId() external management { _setMarketIdFromTokenAddress(); } function setCollateralTarget(uint256 _collateralTarget) external management { (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); require(collateralFactorMantissa > _collateralTarget); collateralTarget = _collateralTarget; } /* * Base External Facing Functions */ /* * An accurate estimate for the total amount of assets (principle + return) * that this strategy is currently managing, denominated in terms of want tokens. */ function estimatedTotalAssets() public override view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 _claimableComp = predictCompAccrued(); uint256 currentComp = IERC20(comp).balanceOf(address(this)); // Use touch price. it doesnt matter if we are wrong as this is not used for decision making uint256 estimatedWant = priceCheck(comp, address(want),_claimableComp.add(currentComp)); uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist return want.balanceOf(address(this)).add(deposits).add(conservativeWant).sub(borrows); } //predicts our profit at next report function expectedReturn() public view returns (uint256) { uint256 estimateAssets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimateAssets) { return 0; } else { return estimateAssets - debt; } } /* * Provide a signal to the keeper that `tend()` should be called. * (keepers are always reimbursed by yEarn) * * NOTE: this call and `harvestTrigger` should never return `true` at the same time. * tendTrigger should be called with same gasCost as harvestTrigger */ function tendTrigger(uint256 gasCost) public override view returns (bool) { if (harvestTrigger(gasCost)) { //harvest takes priority return false; } return getblocksUntilLiquidation() <= blocksToLiquidationDangerZone; } //WARNING. manipulatable and simple routing. Only use for safe functions function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) { if (_amount == 0) { return 0; } address[] memory path; if(start == weth){ path = new address[](2); path[0] = weth; path[1] = end; }else{ path = new address[](3); path[0] = start; path[1] = weth; path[2] = end; } uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; } /***************** * Public non-base function ******************/ //Calculate how many blocks until we are in liquidation based on current interest rates //WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look //equation. Compound doesn't include compounding for most blocks //((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate)); function getblocksUntilLiquidation() public view returns (uint256) { (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 borrrowRate = cToken.borrowRatePerBlock(); uint256 supplyRate = cToken.supplyRatePerBlock(); uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa).div(1e18); uint256 collateralisedDeposit = collateralisedDeposit1; uint256 denom1 = borrows.mul(borrrowRate); uint256 denom2 = collateralisedDeposit.mul(supplyRate); if (denom2 >= denom1) { return type(uint256).max; } else { uint256 numer = collateralisedDeposit.sub(borrows); uint256 denom = denom1 - denom2; //minus 1 for this block return numer.mul(1e18).div(denom); } } // This function makes a prediction on how much comp is accrued // It is not 100% accurate as it uses current balances in Compound to predict into the past function predictCompAccrued() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); if (deposits == 0) { return 0; // should be impossible to have 0 balance and positive comp accrued } //comp speed is amount to borrow or deposit (so half the total distribution for want) uint256 distributionPerBlock = compound.compSpeeds(address(cToken)); uint256 totalBorrow = cToken.totalBorrows(); //total supply needs to be echanged to underlying using exchange rate uint256 totalSupplyCtoken = cToken.totalSupply(); uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18); uint256 blockShareSupply = 0; if(totalSupply > 0){ blockShareSupply = deposits.mul(distributionPerBlock).div(totalSupply); } uint256 blockShareBorrow = 0; if(totalBorrow > 0){ blockShareBorrow = borrows.mul(distributionPerBlock).div(totalBorrow); } //how much we expect to earn per block uint256 blockShare = blockShareSupply.add(blockShareBorrow); //last time we ran harvest uint256 lastReport = vault.strategies(address(this)).lastReport; uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block return blocksSinceLast.mul(blockShare); } //Returns the current position //WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between //cToken is very active so not normally an issue. function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) { (, uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate) = cToken.getAccountSnapshot(address(this)); borrows = borrowBalance; deposits = ctokenBalance.mul(exchangeRate).div(1e18); } //statechanging version function getLivePosition() public returns (uint256 deposits, uint256 borrows) { deposits = cToken.balanceOfUnderlying(address(this)); //we can use non state changing now because we updated state with balanceOfUnderlying call borrows = cToken.borrowBalanceStored(address(this)); } //Same warning as above function netBalanceLent() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); return deposits.sub(borrows); } /*********** * internal core logic *********** */ /* * A core method. * Called at beggining of harvest before providing report to owner * 1 - claim accrued comp * 2 - if enough to be worth it we sell * 3 - because we lose money on our loans we need to offset profit from comp. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; //for clarity. also reduces bytesize if (cToken.balanceOf(address(this)) == 0) { uint256 wantBalance = want.balanceOf(address(this)); //no position to harvest //but we may have some debt to return //it is too expensive to free more debt in this method so we do it in adjust position _debtPayment = Math.min(wantBalance, _debtOutstanding); return (_profit, _loss, _debtPayment); } (uint256 deposits, uint256 borrows) = getLivePosition(); //claim comp accrued _claimComp(); //sell comp _disposeOfComp(); uint256 wantBalance = want.balanceOf(address(this)); uint256 investedBalance = deposits.sub(borrows); uint256 balance = investedBalance.add(wantBalance); uint256 debt = vault.strategies(address(this)).totalDebt; //Balance - Total Debt is profit if (balance > debt) { _profit = balance - debt; if (wantBalance < _profit) { //all reserve is profit _profit = wantBalance; } else if (wantBalance > _profit.add(_debtOutstanding)){ _debtPayment = _debtOutstanding; }else{ _debtPayment = wantBalance - _profit; } } else { //we will lose money until we claim comp then we will make money //this has an unintended side effect of slowly lowering our total debt allowed _loss = debt - balance; _debtPayment = Math.min(wantBalance, _debtOutstanding); } } /* * Second core function. Happens after report call. * * Similar to deposit function from V1 strategy */ function adjustPosition(uint256 _debtOutstanding) internal override { //emergency exit is dealt with in prepareReturn if (emergencyExit) { return; } //we are spending all our cash unless we have debt outstanding uint256 _wantBal = want.balanceOf(address(this)); if(_wantBal < _debtOutstanding){ //this is graceful withdrawal. dont use backup //we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals if(cToken.balanceOf(address(this)) > 1){ _withdrawSome(_debtOutstanding - _wantBal); } return; } (uint256 position, bool deficit) = _calculateDesiredPosition(_wantBal - _debtOutstanding, true); //if we are below minimun want change it is not worth doing //need to be careful in case this pushes to liquidation if (position > minWant) { //if dydx is not active we just try our best with basic leverage if (!DyDxActive) { uint i = 0; while(position > 0){ position = position.sub(_noFlashLoan(position, deficit)); if(i >= 6){ break; } i++; } } else { //if there is huge position to improve we want to do normal leverage. it is quicker if (position > want.balanceOf(SOLO)) { position = position.sub(_noFlashLoan(position, deficit)); } //flash loan to position if(position > minWant){ doDyDxFlashLoan(deficit, position); } } } } /************* * Very important function * Input: amount we want to withdraw and whether we are happy to pay extra for Aave. * cannot be more than we have * Returns amount we were able to withdraw. notall if user has some balance left * * Deleverage position -> redeem our cTokens ******************** */ function _withdrawSome(uint256 _amount) internal returns (bool notAll) { (uint256 position, bool deficit) = _calculateDesiredPosition(_amount, false); //If there is no deficit we dont need to adjust position //if the position change is tiny do nothing if (deficit && position > minWant) { //we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage. Use Aave for extremely large loans if (DyDxActive) { position = position.sub(doDyDxFlashLoan(deficit, position)); } uint8 i = 0; //position will equal 0 unless we haven't been able to deleverage enough with flash loan //if we are not in deficit we dont need to do flash loan while (position > minWant.add(100)) { position = position.sub(_noFlashLoan(position, true)); i++; //A limit set so we don't run out of gas if (i >= 5) { notAll = true; break; } } } //now withdraw //if we want too much we just take max //This part makes sure our withdrawal does not force us into liquidation (uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition(); uint256 tempColla = collateralTarget; uint256 reservedAmount = 0; if(tempColla == 0){ tempColla = 1e15; // 0.001 * 1e18. lower we have issues } reservedAmount = borrowBalance.mul(1e18).div(tempColla); if(depositBalance >= reservedAmount){ uint256 redeemable = depositBalance.sub(reservedAmount); if (redeemable < _amount) { cToken.redeemUnderlying(redeemable); } else { cToken.redeemUnderlying(_amount); } } if(collateralTarget == 0 && want.balanceOf(address(this)) > borrowBalance){ cToken.repayBorrow(borrowBalance); } //let's sell some comp if we have more than needed //flash loan would have sent us comp if we had some accrued so we don't need to call claim comp _disposeOfComp(); } /*********** * This is the main logic for calculating how to change our lends and borrows * Input: balance. The net amount we are going to deposit/withdraw. * Input: dep. Is it a deposit or withdrawal * Output: position. The amount we want to change our current borrow position. * Output: deficit. True if we are reducing position size * * For instance deficit =false, position 100 means increase borrowed balance by 100 ****** */ function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) { //we want to use statechanging for safety (uint256 deposits, uint256 borrows) = getLivePosition(); //When we unwind we end up with the difference between borrow and supply uint256 unwoundDeposit = deposits.sub(borrows); //we want to see how close to collateral target we are. //So we take our unwound deposits and add or remove the balance we are are adding/removing. //This gives us our desired future undwoundDeposit (desired supply) uint256 desiredSupply = 0; if (dep) { desiredSupply = unwoundDeposit.add(balance); } else { if(balance > unwoundDeposit) balance = unwoundDeposit; desiredSupply = unwoundDeposit.sub(balance); } //(ds *c)/(1-c) uint256 num = desiredSupply.mul(collateralTarget); uint256 den = uint256(1e18).sub(collateralTarget); uint256 desiredBorrow = num.div(den); if (desiredBorrow > 1e5) { //stop us going right up to the wire desiredBorrow = desiredBorrow - 1e5; } //now we see if we want to add or remove balance // if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position if (desiredBorrow < borrows) { deficit = true; position = borrows - desiredBorrow; //safemath check done in if statement } else { //otherwise we want to increase position deficit = false; position = desiredBorrow - borrows; } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amount`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = want.balanceOf(address(this)); uint256 assets = netBalanceLent().add(_balance); uint256 debtOutstanding = vault.debtOutstanding(); if(debtOutstanding > assets){ _loss = debtOutstanding - assets; } if (assets < _amountNeeded) { //if we cant afford to withdraw we take all we can //withdraw all we can (uint256 deposits, uint256 borrows) = getLivePosition(); //1 token causes rounding error with withdrawUnderlying if(cToken.balanceOf(address(this)) > 1){ _withdrawSome(deposits.sub(borrows)); } _amountFreed = Math.min(_amountNeeded, want.balanceOf(address(this))); } else { if (_balance < _amountNeeded) { _withdrawSome(_amountNeeded.sub(_balance)); //overflow error if we return more than asked for _amountFreed = Math.min(_amountNeeded, want.balanceOf(address(this))); }else{ _amountFreed = _amountNeeded; } } } function _claimComp() internal { CTokenI[] memory tokens = new CTokenI[](1); tokens[0] = cToken; compound.claimComp(address(this), tokens); } //sell comp function function _disposeOfComp() internal { uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > minCompToSell) { address[] memory path = new address[](3); path[0] = comp; path[1] = weth; path[2] = address(want); IUni(uniswapRouter).swapExactTokensForTokens(_comp, uint256(0), path, address(this), now); } } //lets leave //if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered function prepareMigration(address _newStrategy) internal override { if(!forceMigrate){ (uint256 deposits, uint256 borrows) = getLivePosition(); _withdrawSome(deposits.sub(borrows)); (, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this)); require(borrowBalance < 10_000); IERC20 _comp = IERC20(comp); uint _compB = _comp.balanceOf(address(this)); if(_compB > 0){ _comp.safeTransfer(_newStrategy, _compB); } } } //Three functions covering normal leverage and deleverage situations // max is the max amount we want to increase our borrowed balance // returns the amount we actually did function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) { //we can use non-state changing because this function is always called after _calculateDesiredPosition (uint256 lent, uint256 borrowed) = getCurrentPosition(); //if we have nothing borrowed then we can't deleverage any more if (borrowed == 0 && deficit) { return 0; } (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); if (deficit) { amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa); } else { amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa); } emit Leverage(max, amount, deficit, address(0)); } //maxDeleverage is how much we want to reduce by function _normalDeleverage( uint256 maxDeleverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 deleveragedAmount) { uint256 theoreticalLent = 0; //collat ration should never be 0. if it is something is very wrong... but just incase if(collatRatio != 0){ theoreticalLent = borrowed.mul(1e18).div(collatRatio); } deleveragedAmount = lent.sub(theoreticalLent); if (deleveragedAmount >= borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount >= maxDeleverage) { deleveragedAmount = maxDeleverage; } uint256 exchangeRateStored = cToken.exchangeRateStored(); //redeemTokens = redeemAmountIn *1e18 / exchangeRate. must be more than 0 //a rounding error means we need another small addition if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){ deleveragedAmount = deleveragedAmount -10; cToken.redeemUnderlying(deleveragedAmount); //our borrow has been increased by no more than maxDeleverage cToken.repayBorrow(deleveragedAmount); } } //maxDeleverage is how much we want to increase by function _normalLeverage( uint256 maxLeverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 leveragedAmount) { uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18); leveragedAmount = theoreticalBorrow.sub(borrowed); if (leveragedAmount >= maxLeverage) { leveragedAmount = maxLeverage; } if(leveragedAmount > 10){ leveragedAmount = leveragedAmount -10; cToken.borrow(leveragedAmount); cToken.mint(want.balanceOf(address(this))); } } //called by flash loan function _loanLogic( bool deficit, uint256 amount ) internal { uint256 bal = want.balanceOf(address(this)); require(bal >= amount); // to stop malicious calls //if in deficit we repay amount and then withdraw if (deficit) { cToken.repayBorrow(amount); //if we are withdrawing we take more to cover fee cToken.redeemUnderlying( amount.add(2)); } else { //check if this failed incase we borrow into liquidation require(cToken.mint(bal) == 0); //borrow more to cover fee // fee is so low for dydx that it does not effect our liquidation risk. //DONT USE FOR AAVE cToken.borrow( amount.add(2)); } } //emergency function that we can use to deleverage manually if something is broken function manualDeleverage(uint256 amount) external management{ require(cToken.redeemUnderlying(amount) == 0); require(cToken.repayBorrow(amount) == 0); } //emergency function that we can use to deleverage manually if something is broken function manualReleaseWant(uint256 amount) external onlyGovernance{ require(cToken.redeemUnderlying(amount) ==0); } function protectedTokens() internal override view returns (address[] memory) { } /****************** * Flash loan stuff ****************/ // Flash loan DXDY // amount desired is how much we are willing for position to change function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) { if(amountDesired == 0){ return 0; } uint256 amount = amountDesired; ISoloMargin solo = ISoloMargin(SOLO); // Not enough want in DyDx. So we take all we can uint256 amountInSolo = want.balanceOf(SOLO); if (amountInSolo < amount) { amount = amountInSolo; } bytes memory data = abi.encode(deficit, amount); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(dyDxMarketId, amount); operations[1] = _getCallAction( // Encode custom data for callFunction data ); operations[2] = _getDepositAction(dyDxMarketId, amount.add(2)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); emit Leverage(amountDesired, amount, deficit, SOLO); return amount; } //returns our current collateralisation ratio. Should be compared with collateralTarget function storedCollateralisation() public view returns (uint256 collat) { (uint256 lend, uint256 borrow) = getCurrentPosition(); if (lend == 0) { return 0; } collat = uint256(1e18).mul(borrow).div(lend); } //DyDx calls this function after doing flash loan function callFunction( address sender, Account.Info memory account, bytes memory data ) public override { (bool deficit, uint256 amount) = abi.decode(data, (bool, uint256)); require(msg.sender == SOLO); require(sender == address(this)); _loanLogic(deficit, amount); } // -- Internal Helper functions -- // function _setMarketIdFromTokenAddress() internal { ISoloMargin solo = ISoloMargin(SOLO); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == address(want)) { dyDxMarketId = i; return; } } revert(); } function ethToWant(uint256 _amtInWei) public view override returns (uint256) { return priceCheck(weth, address(want), _amtInWei); } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed,) = liquidatePosition(vault.debtOutstanding()); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 position = deposits.sub(borrows); //we want to revert if we can't liquidateall if(!forceMigrate) { require(position < minWant); } } function mgtm_check() internal { require(msg.sender == governance() || msg.sender == strategist); } modifier management() { mgtm_check(); _; } }
used both as the threshold to sell but also as a trigger for harvest
uint256 public minCompToSell = 0.1 ether;
1,254,570
[ 1, 3668, 3937, 487, 326, 5573, 358, 357, 80, 1496, 2546, 487, 279, 3080, 364, 17895, 26923, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 1131, 2945, 774, 55, 1165, 273, 374, 18, 21, 225, 2437, 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 ]
./full_match/43114/0x473EAA0DeED034eeC01b6DE2Af14f0B487780bec/sources/contracts/babyjoe/babyjoe.sol
use by default 300,000 gas to process auto-claiming dividends exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract DoUKnoEsen3 is ERC20, Ownable { using SafeMath for uint256; IJoeRouter02 public uniswapV2Router; address public uniswapV2Pair; bool private swapping; JOEDividendTracker public dividendTracker; address public deadWallet = 0x000000000000000000000000000000000000dEaD; uint256 public swapTokensAtAmount = 1000000 * (10**18); mapping(address => bool) public _isBlacklisted; uint256 public JOERewardsFee = 9; uint256 public liquidityFee = 3; uint256 public marketingFee = 3; uint256 public totalFees = JOERewardsFee.add(liquidityFee).add(marketingFee); address public _marketingWalletAddress = 0x809669dF982d77180Ae0573A4c6d3Fe2B8D092B3; uint256 public gasForProcessing = 300000; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public automatedMarketMakerPairs; event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SendDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); pragma solidity ^0.6.2; constructor() public ERC20("DoUKnoEsen3", "DUKE3") { dividendTracker = new JOEDividendTracker(); IJoeRouter02 _uniswapV2Router = IJoeRouter02(0x60aE616a2155Ee3d9A68541Ba4544862310933d4); address _uniswapV2Pair = IJoeFactory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WAVAX()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(deadWallet); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); excludeFromFees(owner(), true); excludeFromFees(_marketingWalletAddress, true); excludeFromFees(address(this), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(owner(), 100000000000 * (10**18)); } receive() external payable { } function updateDividendTracker(address newAddress) public onlyOwner { require(newAddress != address(dividendTracker), "JOE: The dividend tracker already has that address"); JOEDividendTracker newDividendTracker = JOEDividendTracker(payable(newAddress)); require(newDividendTracker.owner() == address(this), "JOE: The new dividend tracker must be owned by the JOE token contract"); newDividendTracker.excludeFromDividends(address(newDividendTracker)); newDividendTracker.excludeFromDividends(address(this)); newDividendTracker.excludeFromDividends(owner()); newDividendTracker.excludeFromDividends(address(uniswapV2Router)); emit UpdateDividendTracker(newAddress, address(dividendTracker)); dividendTracker = newDividendTracker; } function updateUniswapV2Router(address newAddress) public onlyOwner { require(newAddress != address(uniswapV2Router), "JOE: The router already has that address"); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IJoeRouter02(newAddress); address _uniswapV2Pair = IJoeFactory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WAVAX()); uniswapV2Pair = _uniswapV2Pair; } function excludeFromFees(address account, bool excluded) public onlyOwner { require(_isExcludedFromFees[account] != excluded, "JOE: Account is already the value of 'excluded'"); _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setMarketingWallet(address payable wallet) external onlyOwner{ _marketingWalletAddress = wallet; } function setJOERewardsFee(uint256 value) external onlyOwner{ JOERewardsFee = value; totalFees = JOERewardsFee.add(liquidityFee).add(marketingFee); } function setLiquiditFee(uint256 value) external onlyOwner{ liquidityFee = value; totalFees = JOERewardsFee.add(liquidityFee).add(marketingFee); } function setMarketingFee(uint256 value) external onlyOwner{ marketingFee = value; totalFees = JOERewardsFee.add(liquidityFee).add(marketingFee); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "JOE: The Joe pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function blacklistAddress(address account, bool value) external onlyOwner{ _isBlacklisted[account] = value; } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "JOE: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "JOE: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function updateGasForProcessing(uint256 newValue) public onlyOwner { require(newValue >= 200000 && newValue <= 500000, "JOE: gasForProcessing must be between 200,000 and 500,000"); require(newValue != gasForProcessing, "JOE: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function excludeFromDividends(address account) external onlyOwner{ dividendTracker.excludeFromDividends(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(msg.sender, false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {} function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function swapAndSendToFee(uint256 tokens) private { uint256 initialJOEBalance = IERC20(JOE).balanceOf(address(this)); swapTokensForJOE(tokens); uint256 newBalance = (IERC20(JOE).balanceOf(address(this))).sub(initialJOEBalance); IERC20(JOE).transfer(_marketingWalletAddress, newBalance); } function swapAndLiquify(uint256 tokens) private { uint256 half = tokens.div(2); uint256 otherHalf = tokens.sub(half); uint256 initialBalance = address(this).balance; uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForAVAX(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WAVAX(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForAVAXSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function swapTokensForJOE(uint256 tokenAmount) private { address[] memory path = new address[](3); path[0] = address(this); path[1] = uniswapV2Router.WAVAX(); path[2] = JOE; _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(0), block.timestamp ); } uniswapV2Router.addLiquidityAVAX{value: ethAmount}( function swapAndSendDividends(uint256 tokens) private{ swapTokensForJOE(tokens); uint256 dividends = IERC20(JOE).balanceOf(address(this)); bool success = IERC20(JOE).transfer(address(dividendTracker), dividends); if (success) { dividendTracker.distributeJOEDividends(dividends); emit SendDividends(tokens, dividends); } } function swapAndSendDividends(uint256 tokens) private{ swapTokensForJOE(tokens); uint256 dividends = IERC20(JOE).balanceOf(address(this)); bool success = IERC20(JOE).transfer(address(dividendTracker), dividends); if (success) { dividendTracker.distributeJOEDividends(dividends); emit SendDividends(tokens, dividends); } } }
4,583,686
[ 1, 1202, 635, 805, 11631, 16, 3784, 16189, 358, 1207, 3656, 17, 14784, 310, 3739, 350, 5839, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2256, 57, 47, 2135, 6705, 275, 23, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 46, 15548, 8259, 3103, 1071, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 225, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 804, 51, 2056, 427, 26746, 8135, 1071, 31945, 8135, 31, 203, 203, 565, 1758, 1071, 8363, 16936, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 203, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 273, 15088, 380, 261, 2163, 636, 2643, 1769, 203, 377, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 389, 291, 13155, 18647, 31, 203, 203, 565, 2254, 5034, 1071, 804, 51, 654, 359, 14727, 14667, 273, 2468, 31, 203, 565, 2254, 5034, 1071, 4501, 372, 24237, 14667, 273, 890, 31, 203, 565, 2254, 5034, 1071, 13667, 310, 14667, 273, 890, 31, 203, 565, 2254, 5034, 1071, 2078, 2954, 281, 273, 804, 51, 654, 359, 14727, 14667, 18, 1289, 12, 549, 372, 24237, 14667, 2934, 1289, 12, 3355, 21747, 14667, 1769, 203, 203, 565, 1758, 1071, 389, 3355, 21747, 16936, 1887, 273, 225, 374, 92, 3672, 29, 6028, 29, 72, 42, 10689, 22, 72, 4700, 18278, 37, 73, 6260, 9036, 37, 24, 71, 26, 72, 23, 2954, 22, 38, 28, 40, 5908, 22, 38, 23, 31, 203, 203, 565, 2254, 5034, 1071, 16189, 1290, 7798, 273, 890, 2 ]
pragma solidity ^0.4.24; import "./openzeppelin/contracts/math/SafeMath.sol"; import "./openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./openzeppelin/contracts/ownership/Ownable.sol"; import "./EtherDollar.sol"; import "./Liquidator.sol"; import "./Finance.sol"; /** * @title Erc20Bank contract. */ contract Erc20Bank is Ownable { Finance internal finance; using SafeMath for uint256; uint256 public lastLoanId; uint256 public collateralPrice; uint256 public collateralRatio; uint256 public liquidationDuration; address public oraclesAddr; address public liquidatorAddr; address public etherDollarAddr; EtherDollar internal token; ERC20 internal collatralToken; Liquidator internal liquidator; uint256 constant internal PRECISION_POINT = 10 ** 3; uint256 constant internal MAX_LOAN = 10000 * 10 ** 18; uint256 constant internal COLLATERAL_MULTIPLIER = 2; uint256 constant internal COLLATERAL_TO_BASE_UNIT = 10 ** 18; address constant internal COLLATERAL_ADDRESS = 0x0; address constant internal FINANCE_ADDRESS = 0x0; enum Types { COLLATERAL_PRICE, COLLATERAL_RATIO, LIQUIDATION_DURATION } enum LoanStates { UNDEFINED, ACTIVE, UNDER_LIQUIDATION, LIQUIDATED, SETTLED } struct Loan { address recipient; uint256 collateralAmount; uint256 amount; LoanStates state; } mapping(uint256 => Loan) public loans; event LoanGot(address indexed recipient, uint256 indexed loanId, uint256 amount, uint256 collateralAmount); event LoanSettled(address recipient, uint256 indexed loanId, uint256 collateralAmount, uint256 amount); event CollateralIncreased(address indexed recipient, uint256 indexed loanId, uint256 collateralAmount); event CollateralDecreased(address indexed recipient, uint256 indexed loanId, uint256 collateralAmount); event Discharged(uint256 amount); string private constant INVALID_AMOUNT = "INVALID_AMOUNT"; string private constant INITIALIZED_BEFORE = "INITIALIZED_BEFORE"; string private constant SUFFICIENT_COLLATERAL = "SUFFICIENT_COLLATERAL"; string private constant INSUFFICIENT_COLLATERAL = "INSUFFICIENT_COLLATERAL"; string private constant INSUFFICIENT_ALLOWANCE = "INSUFFICIENT_ALLOWANCE"; string private constant ONLY_LOAN_OWNER = "ONLY_LOAN_OWNER"; string private constant ONLY_LIQUIDATOR = "ONLY_LIQUIDATOR"; string private constant ONLY_ORACLES = "ONLY_ORACLE"; string private constant INVALID_LOAN_STATE = "INVALID_LOAN_STATE"; string private constant EXCEEDED_MAX_LOAN = "EXCEEDED_MAX_LOAN"; string private constant TOKENS_NOT_AVAILABLE = "TOKENS_NOT_AVAILABLE"; string private constant FINANCE_MESSAGE = "DISCHARGE ERC20 BANK"; constructor(address tokenAddr) public { token = EtherDollar(tokenAddr); etherDollarAddr = tokenAddr; collatralToken = ERC20(COLLATERAL_ADDRESS); collateralRatio = 1500; // = 1.5 * PRECISION_POINT liquidationDuration = 7200; // = 2 hours finance = Finance(FINANCE_ADDRESS); } /** * @notice discharge extera collateral. * @param amount The amount of collateral. */ function discharge(uint256 amount) external onlyOwner { uint256 balance = collatralToken.balanceOf(address(this)); require(amount <= balance, INVALID_AMOUNT); require(collatralToken.approve(address(finance), amount)); finance.deposit(address(collatralToken), amount, FINANCE_MESSAGE); emit Discharged(amount); } /** * @notice Set Liquidator's address. * @param _liquidatorAddr The Liquidator's contract address. */ function setLiquidator(address _liquidatorAddr) external { require(liquidatorAddr == address(0), INITIALIZED_BEFORE); liquidatorAddr = _liquidatorAddr; liquidator = Liquidator(_liquidatorAddr); } /** * @notice Set oracle's address. * @param _oraclesAddr The oracle's contract address. */ function setOracle(address _oraclesAddr) external { require (oraclesAddr == address(0), INITIALIZED_BEFORE); oraclesAddr = _oraclesAddr; } /** * @notice Set important varibales by oracles. * @param _type Type of the variable. * @param value Amount of the variable. */ function setVariable(uint8 _type, uint256 value) external onlyOracles throwIfEqualToZero(value) { if (uint8(Types.COLLATERAL_PRICE) == _type) { collateralPrice = value; } else if (uint8(Types.COLLATERAL_RATIO) == _type) { collateralRatio = value; } else if (uint8(Types.LIQUIDATION_DURATION) == _type) { liquidationDuration = value; } } /** * @notice Deposit ether to borrow ether dollar. * @param amount The amount of requsted loan in ether dollar. */ function getLoan(uint256 amount) public payable throwIfEqualToZero(amount) { require (amount <= MAX_LOAN, EXCEEDED_MAX_LOAN); uint256 collateralAmount = collatralToken.allowance(msg.sender, address(this)); require (collatralToken.transferFrom(msg.sender, address(this), collateralAmount)); require (minCollateral(amount) <= collateralAmount, INSUFFICIENT_COLLATERAL); uint256 loanId = ++lastLoanId; loans[loanId].recipient = msg.sender; loans[loanId].collateralAmount = collateralAmount; loans[loanId].amount = amount; loans[loanId].state = LoanStates.ACTIVE; emit LoanGot(msg.sender, loanId, amount, collateralAmount); token.mint(msg.sender, amount); } /** * @notice Increase the loan's collateral. * @param loanId The loan id. */ function increaseCollateral(uint256 loanId) external payable checkLoanStates(loanId, LoanStates.ACTIVE) { uint256 collateralAmount = collatralToken.allowance(msg.sender, address(this)); require (collatralToken.transferFrom(msg.sender, address(this), collateralAmount)); require(0 < collateralAmount, INVALID_AMOUNT); loans[loanId].collateralAmount = loans[loanId].collateralAmount.add(collateralAmount); emit CollateralIncreased(msg.sender, loanId, collateralAmount); } /** * @notice Pay back extera collateral. * @param loanId The loan id. * @param amount The amout of extera collateral. */ function decreaseCollateral(uint256 loanId, uint256 amount) external throwIfEqualToZero(amount) onlyLoanOwner(loanId) { require(loans[loanId].state != LoanStates.UNDER_LIQUIDATION, INVALID_LOAN_STATE); require(minCollateral(loans[loanId].amount) <= loans[loanId].collateralAmount.sub(amount), INSUFFICIENT_COLLATERAL); loans[loanId].collateralAmount = loans[loanId].collateralAmount.sub(amount); emit CollateralDecreased(msg.sender, loanId, amount); require(collatralToken.transfer(loans[loanId].recipient, amount), TOKENS_NOT_AVAILABLE); } /** * @notice pay ether dollars back to settle the loan. * @param loanId The loan id. * @param amount The ether dollar amount payed back. */ function settleLoan(uint256 loanId, uint256 amount) external checkLoanStates(loanId, LoanStates.ACTIVE) throwIfEqualToZero(amount) { require(amount <= loans[loanId].amount, INVALID_AMOUNT); require(token.transferFrom(msg.sender, address(this), amount), INSUFFICIENT_ALLOWANCE); uint256 payback = loans[loanId].collateralAmount.mul(amount).div(loans[loanId].amount); token.burn(amount); loans[loanId].collateralAmount = loans[loanId].collateralAmount.sub(payback); loans[loanId].amount = loans[loanId].amount.sub(amount); if (loans[loanId].amount == 0) { loans[loanId].state = LoanStates.SETTLED; } emit LoanSettled(loans[loanId].recipient, loanId, payback, amount); require(collatralToken.transfer(loans[loanId].recipient, payback), TOKENS_NOT_AVAILABLE); } /** * @notice Start liquidation process of the loan. * @param loanId The loan id. */ function liquidate(uint256 loanId) external checkLoanStates(loanId, LoanStates.ACTIVE) { require (loans[loanId].collateralAmount < minCollateral(loans[loanId].amount), SUFFICIENT_COLLATERAL); loans[loanId].state = LoanStates.UNDER_LIQUIDATION; liquidator.startLiquidation( loanId, loans[loanId].collateralAmount, loans[loanId].amount, liquidationDuration ); } /** * @dev pay a part of the collateral to the auction's winner. * @param loanId The loan id. * @param collateral The bid of winner. * @param buyer The winner account. */ function liquidated(uint256 loanId, uint256 collateral, address buyer) external onlyLiquidator checkLoanStates(loanId, LoanStates.UNDER_LIQUIDATION) returns (bool) { require (collateral <= loans[loanId].collateralAmount, INVALID_AMOUNT); loans[loanId].collateralAmount = loans[loanId].collateralAmount.sub(collateral); loans[loanId].amount = 0; loans[loanId].state = LoanStates.LIQUIDATED; require(collatralToken.transfer(buyer, collateral), TOKENS_NOT_AVAILABLE); return true; } /** * @notice Minimum collateral in wei that is required for borrowing `amount`. * @param amount The amount of the loan. */ function minCollateral(uint256 amount) public view returns (uint256) { uint256 min = amount.mul(collateralRatio).mul(COLLATERAL_TO_BASE_UNIT).div(PRECISION_POINT).div(collateralPrice); return min; } /** * @dev Throws if called by any account other than our Oracle. */ modifier onlyOracles() { require(msg.sender == oraclesAddr, ONLY_ORACLES); _; } /** * @dev Throws if called by any account other than our Liquidator. */ modifier onlyLiquidator() { require(msg.sender == liquidatorAddr, ONLY_LIQUIDATOR); _; } /** * @dev Throws if the number is equal to zero. * @param number The number to validate. */ modifier throwIfEqualToZero(uint number) { require(number != 0, INVALID_AMOUNT); _; } /** * @dev Throws if called by any account other than the owner of the loan. * @param loanId The loan id. */ modifier onlyLoanOwner(uint256 loanId) { require(loans[loanId].recipient == msg.sender, ONLY_LOAN_OWNER); _; } /** * @dev Throws if state is not equal to needState. * @param loanId The id of the loan. * @param needState The state which needed. */ modifier checkLoanStates(uint256 loanId, LoanStates needState) { require(loans[loanId].state == needState, INVALID_LOAN_STATE); _; } }
* @notice discharge extera collateral. @param amount The amount of collateral./
function discharge(uint256 amount) external onlyOwner { uint256 balance = collatralToken.balanceOf(address(this)); require(amount <= balance, INVALID_AMOUNT); require(collatralToken.approve(address(finance), amount)); finance.deposit(address(collatralToken), amount, FINANCE_MESSAGE); emit Discharged(amount); }
1,036,927
[ 1, 2251, 16385, 431, 387, 69, 4508, 2045, 287, 18, 225, 3844, 1021, 3844, 434, 4508, 2045, 287, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1015, 16385, 12, 11890, 5034, 3844, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 2254, 5034, 11013, 273, 4508, 270, 23811, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2583, 12, 8949, 1648, 11013, 16, 10071, 67, 2192, 51, 5321, 1769, 203, 203, 3639, 2583, 12, 1293, 4801, 23811, 1345, 18, 12908, 537, 12, 2867, 12, 926, 1359, 3631, 3844, 10019, 203, 3639, 574, 1359, 18, 323, 1724, 12, 2867, 12, 1293, 4801, 23811, 1345, 3631, 3844, 16, 17563, 4722, 67, 8723, 1769, 203, 3639, 3626, 3035, 3001, 2423, 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 ]
./full_match/4/0x9AebA44EBfC75db5d11226E66EB34d383880fDc5/sources/contracts/721Creator.sol
_tokenCounter keeps track of how many tokens have ever been minted. Tokens can be burned, so the total supply may be less than this number.
{ using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); Counters.Counter private _tokenCounter; string private _baseTokenURI; constructor( string memory name, string memory symbol, string memory baseTokenURI contract Creator is ) ERC721(name, symbol) { _baseTokenURI = baseTokenURI; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } event BaseURIChanged(string baseTokenURI); function setBaseURI(string memory newBaseURI) external { _baseTokenURI = newBaseURI; emit BaseURIChanged(_baseTokenURI); } function mint(address to, string memory newTokenURI) public virtual { require( hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint" ); _safeMint(to, _tokenCounter.current(), newTokenURI); _tokenCounter.increment(); } function _safeMint( address _to, uint256 _tokenId, string memory _tokenURI ) internal virtual { _safeMint(_to, _tokenId); _setTokenURI(_tokenId, _tokenURI); } function pause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause" ); _pause(); } function unpause() public virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause" ); _unpause(); } function burn(uint256 tokenId) public virtual override { _burn(tokenId); } function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
12,520,427
[ 1, 67, 2316, 4789, 20948, 3298, 434, 3661, 4906, 2430, 1240, 14103, 2118, 312, 474, 329, 18, 13899, 848, 506, 18305, 329, 16, 1427, 326, 2078, 14467, 2026, 506, 5242, 2353, 333, 1300, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 6989, 2560, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 6236, 2560, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 15662, 4714, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 4066, 4714, 67, 16256, 8863, 203, 203, 565, 9354, 87, 18, 4789, 3238, 389, 2316, 4789, 31, 203, 565, 533, 3238, 389, 1969, 1345, 3098, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 533, 3778, 1026, 1345, 3098, 203, 203, 203, 16351, 29525, 353, 203, 565, 262, 4232, 39, 27, 5340, 12, 529, 16, 3273, 13, 288, 203, 3639, 389, 1969, 1345, 3098, 273, 1026, 1345, 3098, 31, 203, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 203, 3639, 389, 8401, 2996, 12, 6236, 2560, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 8401, 2996, 12, 4066, 4714, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 445, 389, 1969, 3098, 1435, 2713, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 1969, 1345, 3098, 31, 203, 565, 289, 203, 203, 565, 871, 3360, 3098, 5033, 12, 1080, 1026, 1345, 3098, 1769, 203, 203, 565, 445, 26435, 3098, 12, 1080, 3778, 394, 2171, 3098, 13, 3903, 288, 203, 3639, 389, 1969, 1345, 3098, 273, 394, 2171, 3098, 31, 203, 3639, 3626, 3360, 3098, 2 ]
pragma solidity ^0.4.24; contract PriceOracleInterface { /** * @notice Gets the price of a given asset * @dev fetches the price of a given asset * @param asset Asset to get the price of * @return the price scaled by 10**18, or zero if the price is not available */ function assetPrices(address asset) public view returns (uint); } contract ErrorReporter { /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE } /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(Error.OPAQUE_ERROR), uint(info), opaqueError); return uint(Error.OPAQUE_ERROR); } } contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate(address asset, uint cash, uint borrows) public view returns (uint, uint); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate(address asset, uint cash, uint borrows) public view returns (uint, uint); } contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract EIP20NonStandardInterface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public; /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint a, uint b) internal pure returns (Error, uint) { if (a == 0) { return (Error.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint a, uint b) internal pure returns (Error, uint) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns (Error, uint) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint a, uint b) internal pure returns (Error, uint) { uint c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub(uint a, uint b, uint c) internal pure returns (Error, uint) { (Error err0, uint sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn(address asset, address from, uint amount) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address asset, address from, uint amount) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address asset, address to, uint amount) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } contract Exponential is ErrorReporter, CarefulMath { // TODO: We may wish to put the result of 10**18 here instead of the expression. // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint constant expScale = 10**18; // See TODO on expScale uint constant halfExpScale = expScale/2; struct Exp { uint mantissa; } uint constant mantissaOne = 10**18; uint constant mantissaOneTenth = 10**17; /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (Error, Exp memory) { (Error err0, uint scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error error, uint result) = add(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error error, uint result) = sub(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) { (Error err0, uint scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) { (Error err0, uint descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp divisor) pure internal returns (Error, Exp memory) { /* We are doing this as: getExp(mul(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (Error err0, uint numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error err0, uint doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (Error err1, uint doubleScaledProductWithHalfScale) = add(halfExpScale, doubleScaledProduct); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint product) = div(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 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 / 10**18; } /** * @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; //TODO: Add some simple tests and this in another PR yo. } /** * @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 returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } contract MoneyMarket is Exponential, SafeToken { uint constant initialInterestIndex = 10 ** 18; uint constant defaultOriginationFee = 0; // default is zero bps uint constant minimumCollateralRatioMantissa = 11 * (10 ** 17); // 1.1 uint constant maximumLiquidationDiscountMantissa = (10 ** 17); // 0.1 /** * @notice `MoneyMarket` is the core Compound MoneyMarket contract */ constructor() public { admin = msg.sender; collateralRatio = Exp({mantissa: 2 * mantissaOne}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: 0}); // oracle must be configured via _setOracle } /** * @notice Do not pay directly into MoneyMarket, please use `supply`. */ function() payable public { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address public oracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = the total interestIndex as calculated after applying the customer's most recent balance-changing action * } */ struct Balance { uint principal; uint interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint blockNumber; InterestRateModel interestRateModel; uint totalSupply; uint supplyRateMantissa; uint supplyIndex; uint totalBorrows; uint borrowRateMantissa; uint borrowIndex; } /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken(address account, address asset, uint amount, uint startingBalance, uint borrowAmountWithFee, uint newBalance); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) */ event BorrowLiquidated(address targetAccount, address assetBorrow, uint borrowBalanceBefore, uint borrowBalanceAccumulated, uint amountRepaid, uint borrowBalanceAfter, address liquidator, address assetCollateral, uint collateralBalanceBefore, uint collateralBalanceAccumulated, uint amountSeized, uint collateralBalanceAfter); /** * @dev emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @dev newOracle - address of new oracle */ event NewOracle(address oldOracle, address newOracle); /** * @dev emitted when new market is supported by admin */ event SupportedMarket(address asset, address interestRateModel); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters(uint oldCollateralRatioMantissa, uint newCollateralRatioMantissa, uint oldLiquidationDiscountMantissa, uint newLiquidationDiscountMantissa); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee(uint oldOriginationFeeMantissa, uint newOriginationFeeMantissa); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel(address asset, address interestRateModel); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner); /** * @dev emitted when a supported market is suspended by admin */ event SuspendedMarket(address asset); /** * @dev emitted when admin either pauses or resumes the contract; newState is the resulting state */ event SetPaused(bool newState); /** * @dev Simple function to calculate min between two numbers. */ function min(uint a, uint b) pure internal returns (uint) { if (a < b) { return a; } else { return b; } } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint) { return collateralMarkets.length; } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` */ function calculateInterestIndex(uint startingInterestIndex, uint interestRateMantissa, uint blockStart, uint blockEnd) pure internal returns (Error, uint) { // Get the block delta (Error err0, uint blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar(Exp({mantissa: interestRateMantissa}), blockDelta); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp(blocksTimesRate, Exp({mantissa: mantissaOne})); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar(onePlusBlocksTimesRate, startingInterestIndex); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * * TODO: Is there a way to handle this that is less likely to overflow? */ function calculateBalance(uint startingBalance, uint interestIndexStart, uint interestIndexEnd) pure internal returns (Error, uint) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint balanceTimesIndex) = mul(startingBalance, interestIndexEnd); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. */ function getPriceForAssetAmount(address asset, uint assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` */ function getPriceForAssetAmountMulCollatRatio(address asset, uint assetAmount) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * * TODO: Track at what magnitude this fee rounds down to zero? */ function calculateBorrowAmountWithFee(uint borrowAmount) view internal returns (Error, uint) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp(originationFee, Exp({mantissa: mantissaOne})); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar(originationFeeFactor, borrowAmount); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (oracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } PriceOracleInterface oracleInterface = PriceOracleInterface(oracle); uint priceMantissa = oracleInterface.assetPrices(asset); return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) * * TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address? */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller = pendingAdmin // msg.sender can't be zero if (msg.sender != pendingAdmin) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint(Error.NO_ERROR); } /** * @notice Set new oracle, who can set asset prices * @dev Admin function to change oracle * @param newOracle New oracle address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setOracle(address newOracle) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORACLE_OWNER_CHECK); } // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. PriceOracleInterface oracleInterface = PriceOracleInterface(newOracle); oracleInterface.assetPrices(address(0)); address oldOracle = oracle; // Store oracle = newOracle oracle = newOracle; emit NewOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice set `paused` to the specified state * @dev Admin function to pause or resume the market * @param requestedState value to assign to `paused` * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPaused(bool requestedState) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSED_OWNER_CHECK); } paused = requestedState; emit SetPaused(requestedState); return uint(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int) { (Error err, Exp memory accountLiquidity, Exp memory accountShortfall) = calculateAccountLiquidity(account); require(err == Error.NO_ERROR); if (isZeroExp(accountLiquidity)) { return -1 * int(truncate(accountShortfall)); } else { return int(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) view public returns (uint) { Error err; uint newSupplyIndex; uint userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); require(err == Error.NO_ERROR); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex); require(err == Error.NO_ERROR); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) view public returns (uint) { Error err; uint newBorrowIndex; uint userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); require(err == Error.NO_ERROR); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex); require(err == Error.NO_ERROR); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use with Compound * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail(Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use with Compound. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUSPEND_MARKET_OWNER_CHECK); } // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; emit SuspendedMarket(asset); return uint(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters(uint collateralRatioMantissa, uint liquidationDiscountMantissa) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RISK_PARAMETERS_OWNER_CHECK); } Exp memory newCollateralRatio = Exp({mantissa: collateralRatioMantissa}); Exp memory newLiquidationDiscount = Exp({mantissa: liquidationDiscountMantissa}); Exp memory minimumCollateralRatio = Exp({mantissa: minimumCollateralRatioMantissa}); Exp memory maximumLiquidationDiscount = Exp({mantissa: maximumLiquidationDiscountMantissa}); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail(Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail(Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp(newLiquidationDiscount, Exp({mantissa: mantissaOne})); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if (lessThanOrEqualExp(newCollateralRatio, newLiquidationDiscountPlusOne)) { return fail(Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters(oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the origination fee (which is a multiplier on new borrows) * @dev Owner function to set the origination fee * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setOriginationFee(uint originationFeeMantissa) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORIGINATION_FEE_OWNER_CHECK); } // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee(oldOriginationFee.mantissa, originationFeeMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel(address asset, InterestRateModel interestRateModel) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity= cash - (supply + borrows) * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash - (supply + borrows) * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint amount) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK); } // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint cash = getCash(asset); (Error err0, uint equity) = addThenSub(cash, markets[asset].totalBorrows, markets[asset].totalSupply); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail(Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED); } //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint(Error.NO_ERROR); // success } /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint startingBalance; uint newSupplyIndex; uint userSupplyCurrent; uint userSupplyUpdated; uint newTotalSupply; uint currentCash; uint updatedCash; uint newSupplyRateMantissa; uint newBorrowIndex; uint newBorrowRateMantissa; } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { return fail(Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED); } // Fail gracefully if asset is not approved or has insufficient balance err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (err, localResults.userSupplyCurrent) = calculateBalance(balance.principal, balance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED); } (err, localResults.userSupplyUpdated) = add(localResults.userSupplyCurrent, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub(market.totalSupply, localResults.userSupplyUpdated, balance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; emit SupplyReceived(msg.sender, asset, amount, localResults.startingBalance, localResults.userSupplyUpdated); return uint(Error.NO_ERROR); // success } struct WithdrawLocalVars { uint withdrawAmount; uint startingBalance; uint newSupplyIndex; uint userSupplyCurrent; uint userSupplyUpdated; uint newTotalSupply; uint currentCash; uint updatedCash; uint newSupplyRateMantissa; uint newBorrowIndex; uint newBorrowRateMantissa; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; uint withdrawCapacity; } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint requestedAmount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED); } Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. (err, localResults.accountLiquidity, localResults.accountShortfall) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (err, localResults.userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue(asset, localResults.accountLiquidity); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min(localResults.withdrawCapacity, localResults.userSupplyCurrent); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub(localResults.currentCash, localResults.withdrawAmount); if (err != Error.NO_ERROR) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub(localResults.userSupplyCurrent, localResults.withdrawAmount); if (err != Error.NO_ERROR) { return fail(Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount(asset, localResults.withdrawAmount); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if (lessThanExp(localResults.accountLiquidity, localResults.ethValueOfWithdrawal) ) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub(market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; emit SupplyWithdrawn(msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, localResults.userSupplyUpdated); return uint(Error.NO_ERROR); // success } struct AccountValueLocalVars { address assetAddress; uint collateralMarketsLength; uint newSupplyIndex; uint userSupplyCurrent; Exp supplyTotalValue; Exp sumSupplies; uint newBorrowIndex; uint userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). */ function calculateAccountLiquidity(address userAddress) internal view returns (Error, Exp memory, Exp memory) { Error err; uint sumSupplyValuesMantissa; uint sumBorrowValuesMantissa; (err, sumSupplyValuesMantissa, sumBorrowValuesMantissa) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return(err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({mantissa: sumSupplyValuesMantissa}); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp(collateralRatio, Exp({mantissa: sumBorrowValuesMantissa})); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) * TODO: Possibly should add a Min(500, collateralMarkets.length) for extra safety * TODO: To help save gas we could think about using the current Market.interestIndex * accumulate interest rather than calculating it */ function calculateAccountValuesInternal(address userAddress) internal view returns (Error, uint, uint) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][localResults.assetAddress]; Balance storage borrowBalance = borrowBalances[userAddress][localResults.assetAddress]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex(currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return (err, 0, 0); } (err, localResults.userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return (err, 0, 0); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount(localResults.assetAddress, localResults.userSupplyCurrent); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, 0, 0); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp(localResults.supplyTotalValue, localResults.sumSupplies); if (err != Error.NO_ERROR) { return (err, 0, 0); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex(currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return (err, 0, 0); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return (err, 0, 0); } // In the case of borrow, we multiply the borrow value by the collateral ratio (err, localResults.borrowTotalValue) = getPriceForAssetAmount(localResults.assetAddress, localResults.userBorrowCurrent); // ( borrowCurrent* oraclePrice * collateralRatio) = borrowTotalValueInEth if (err != Error.NO_ERROR) { return (err, 0, 0); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp(localResults.borrowTotalValue, localResults.sumBorrows); if (err != Error.NO_ERROR) { return (err, 0, 0); } } } return (Error.NO_ERROR, localResults.sumSupplies.mantissa, localResults.sumBorrows.mantissa); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns (uint, uint, uint) { (Error err, uint supplyValue, uint borrowValue) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint(err), 0, 0); } return (0, supplyValue, borrowValue); } struct PayBorrowLocalVars { uint newBorrowIndex; uint userBorrowCurrent; uint repayAmount; uint userBorrowUpdated; uint newTotalBorrows; uint currentCash; uint updatedCash; uint newSupplyIndex; uint newSupplyRateMantissa; uint newBorrowRateMantissa; uint startingBalance; } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED); } PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (amount == uint(-1)) { localResults.repayAmount = min(getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent); } else { localResults.repayAmount = amount; } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub(localResults.userBorrowCurrent, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub(market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; emit BorrowRepaid(msg.sender, asset, localResults.repayAmount, localResults.startingBalance, localResults.userBorrowUpdated); return uint(Error.NO_ERROR); // success } struct BorrowLocalVars { uint newBorrowIndex; uint userBorrowCurrent; uint borrowAmountWithFee; uint userBorrowUpdated; uint newTotalBorrows; uint currentCash; uint updatedCash; uint newSupplyIndex; uint newSupplyRateMantissa; uint newBorrowRateMantissa; uint startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint newBorrowIndex_UnderwaterAsset; uint newSupplyIndex_UnderwaterAsset; uint newBorrowIndex_CollateralAsset; uint newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint updatedBorrowBalance_TargetUnderwaterAsset; uint newTotalBorrows_ProtocolUnderwaterAsset; uint startingBorrowBalance_TargetUnderwaterAsset; uint startingSupplyBalance_TargetCollateralAsset; uint startingSupplyBalance_LiquidatorCollateralAsset; uint currentSupplyBalance_TargetCollateralAsset; uint updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint updatedSupplyBalance_LiquidatorCollateralAsset; uint newTotalSupply_ProtocolCollateralAsset; uint currentCash_ProtocolUnderwaterAsset; uint updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint newSupplyRateMantissa_ProtocolUnderwaterAsset; uint newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint discountedBorrowDenominatedCollateral; uint maxCloseableBorrowAmount_TargetUnderwaterAsset; uint closeBorrowAmount_TargetUnderwaterAsset; uint seizeSupplyAmount_TargetCollateralAsset; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address targetAccount, address assetBorrow, address assetCollateral, uint requestedAmountClose) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED); } LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[targetAccount][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[targetAccount][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if(err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset (err, localResults.newBorrowIndex_UnderwaterAsset) = calculateInterestIndex(borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET); } (err, localResults.currentBorrowBalance_TargetUnderwaterAsset) = calculateBalance(borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset (err, localResults.newSupplyIndex_CollateralAsset) = calculateInterestIndex(collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET); } (err, localResults.currentSupplyBalance_TargetCollateralAsset) = calculateBalance(supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset (err, localResults.currentSupplyBalance_LiquidatorCollateralAsset) = calculateBalance(supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (err, localResults.discountedBorrowDenominatedCollateral) = calculateDiscountedBorrowDenominatedCollateral(localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. (err, localResults.discountedRepayToEvenAmount) = calculateDiscountedRepayToEvenAmount(targetAccount, localResults.underwaterAssetPrice); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (requestedAmountClose == uint(-1)) { localResults.closeBorrowAmount_TargetUnderwaterAsset = localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if (localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset) { return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) (err, localResults.seizeSupplyAmount_TargetCollateralAsset) = calculateAmountSeize(localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into Compound // Fail gracefully if asset is not approved or has insufficient balance err = checkTransferIn(assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows_ProtocolUnderwaterAsset) = addThenSub(borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. (err, localResults.newSupplyIndex_UnderwaterAsset) = calculateInterestIndex(borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET); } (rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset) = borrowMarket.interestRateModel.getSupplyRate(assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset) = borrowMarket.interestRateModel.getBorrowRate(assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. (err, localResults.newBorrowIndex_CollateralAsset) = calculateInterestIndex(collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub(localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert (err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset) = add(localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert (err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } // Save borrow market updates borrowMarket.blockNumber = getBlockNumber(); borrowMarket.totalBorrows = localResults.newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = getBlockNumber(); collateralMarket.totalSupply = localResults.newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults.newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults.newBorrowIndex_CollateralAsset; // Save user updates localResults.startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset.principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults.updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults.newBorrowIndex_UnderwaterAsset; localResults.startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset.principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults.updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults.newSupplyIndex_CollateralAsset; localResults.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset.principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults.updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults.newSupplyIndex_CollateralAsset; emitLiquidationEvent(localResults); return uint(Error.NO_ERROR); // success } /** * @dev this function exists to avoid error `CompilerError: Stack too deep, try removing local variables.` in `liquidateBorrow` */ function emitLiquidationEvent(LiquidateLocalVars memory localResults) internal { // event BorrowLiquidated(address targetAccount, address assetBorrow, uint borrowBalanceBefore, uint borrowBalanceAccumulated, uint amountRepaid, uint borrowBalanceAfter, // address liquidator, address assetCollateral, uint collateralBalanceBefore, uint collateralBalanceAccumulated, uint amountSeized, uint collateralBalanceAfter); emit BorrowLiquidated(localResults.targetAccount, localResults.assetBorrow, localResults.startingBorrowBalance_TargetUnderwaterAsset, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.updatedBorrowBalance_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.startingSupplyBalance_TargetCollateralAsset, localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset, localResults.updatedSupplyBalance_TargetCollateralAsset); } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. **/ function calculateDiscountedRepayToEvenAmount(address targetAccount, Exp memory underwaterAssetPrice) internal view returns (Error, uint) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio (err, _accountLiquidity, accountShortfall_TargetUser) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp(collateralRatio, liquidationDiscount); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp(collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne})); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp(underwaterAssetPrice, discountedCollateralRatioMinusOne); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); (err, rawResult) = divExp(accountShortfall_TargetUser, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) */ function calculateDiscountedBorrowDenominatedCollateral(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint supplyCurrent_TargetCollateralAsset) view internal returns (Error, uint) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp(Exp({mantissa: mantissaOne}), liquidationDiscount); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar(collateralPrice, supplyCurrent_TargetCollateralAsset); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp(onePlusLiquidationDiscount, underwaterAssetPrice); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral **/ function calculateAmountSeize(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint closeBorrowAmount_TargetUnderwaterAsset) internal view returns (Error, uint) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp(Exp({mantissa: mantissaOne}), liquidationDiscount); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(underwaterAssetPrice, liquidationMultiplier); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar(priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail(Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee(amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED); } // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add(localResults.userBorrowCurrent, localResults.borrowAmountWithFee); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub(market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED); } // Check customer liquidity (err, localResults.accountLiquidity, localResults.accountShortfall) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` (err, localResults.ethValueOfBorrowAmountWithFee) = getPriceForAssetAmountMulCollatRatio(asset, localResults.borrowAmountWithFee); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if (lessThanExp(localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; emit BorrowTaken(msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, localResults.userBorrowUpdated); return uint(Error.NO_ERROR); // success } }
We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferIn(asset, msg.sender, amount);
2,476,693
[ 1, 3218, 4232, 39, 17, 3462, 7412, 326, 3310, 1368, 326, 1771, 261, 7652, 30, 675, 17, 6381, 1818, 5950, 5721, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 393, 273, 741, 5912, 382, 12, 9406, 16, 1234, 18, 15330, 16, 3844, 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 ]
./full_match/137/0xAa6917d9Fb007765F0988A2Bf61Ed86dF3001D7E/sources/project_/contracts/StrategicClubExpirableNFT.sol
* See {ERC1155-_beforeTokenTransfer}/
function _beforeTokenTransfer( address operator_, address from_, address to_, uint256[] memory ids_, uint256[] memory amounts_, bytes memory data_ ) internal virtual override(ERC1155Pausable, ERC1155) { super._beforeTokenTransfer(operator_, from_, to_, ids_, amounts_, data_); }
4,765,594
[ 1, 9704, 288, 654, 39, 2499, 2539, 17, 67, 5771, 1345, 5912, 4004, 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 ]
[ 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 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 3726, 67, 16, 203, 3639, 1758, 628, 67, 16, 203, 3639, 1758, 358, 67, 16, 203, 3639, 2254, 5034, 8526, 3778, 3258, 67, 16, 203, 3639, 2254, 5034, 8526, 3778, 30980, 67, 16, 203, 3639, 1731, 3778, 501, 67, 203, 565, 262, 2713, 5024, 3849, 12, 654, 39, 2499, 2539, 16507, 16665, 16, 4232, 39, 2499, 2539, 13, 288, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 9497, 67, 16, 628, 67, 16, 358, 67, 16, 3258, 67, 16, 30980, 67, 16, 501, 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 ]